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

            exports({
                BitMask: BitMask,
                CCClass: CCClass,
                CacheMode: void 0,
                DebugMode: void 0,
                ECollider2DType: void 0,
                EJoint2DType: void 0,
                EPhysics2DDrawFlags: void 0,
                ERaycast2DType: void 0,
                ERigidBody2DType: void 0,
                Enum: Enum,
                Eventify: Eventify,
                HorizontalTextAlignment: void 0,
                InstanceMaterialType: void 0,
                Overflow: void 0,
                Physics2DManifoldType: void 0,
                SystemEventType: void 0,
                VerticalTextAlignment: void 0,
                WorldNode3DToLocalNodeUI: WorldNode3DToLocalNodeUI,
                WorldNode3DToWorldNodeUI: WorldNode3DToWorldNodeUI,
                absMax: absMax,
                absMaxComponent: absMaxComponent,
                approx: approx,
                assert: assert,
                assertID: assertID,
                bezier: bezier,
                bezierByTime: bezierByTime,
                ccenum: ccenum,
                clamp: clamp,
                clamp01: clamp01,
                color: color,
                computeRatioByType: computeRatioByType,
                createDefaultPipeline: createDefaultPipeline,
                deserialize: deserialize,
                earcut: earcut,
                equals: equals,
                error: error,
                errorID: errorID,
                find: find,
                fragmentText: fragmentText,
                getBaselineOffset: getBaselineOffset,
                getError: getError,
                getPathFromRoot: getPathFromRoot,
                getWorldTransformUntilRoot: getWorldTransformUntilRoot,
                instantiate: instantiate,
                inverseLerp: inverseLerp,
                isCustomTargetModifier: isCustomTargetModifier,
                isDisplayStats: isDisplayStats,
                isElementModifier: isElementModifier,
                isPropertyModifier: isPropertyModifier,
                isUnicodeCJK: isUnicodeCJK,
                isUnicodeSpace: isUnicodeSpace,
                isValid: isValid,
                lerp: lerp,
                log: log,
                logID: logID,
                markAsWarning: void 0,
                mat4: mat4,
                murmurhash2_32_gc: murmurhash2_32_gc,
                nextPow2: nextPow2$1,
                pingPong: pingPong,
                pseudoRandom: pseudoRandom,
                pseudoRandomRange: pseudoRandomRange,
                pseudoRandomRangeInt: pseudoRandomRangeInt,
                quat: quat,
                randomRange: randomRange,
                randomRangeInt: randomRangeInt,
                rect: rect,
                removeProperty: void 0,
                repeat: repeat,
                replaceProperty: void 0,
                safeMeasureText: safeMeasureText,
                sampleAnimationCurve: sampleAnimationCurve,
                setDefaultLogTimes: setDefaultLogTimes,
                setDisplayStats: setDisplayStats,
                size: size,
                toDegree: toDegree,
                toRadian: toRadian,
                tween: tween,
                tweenUtil: tweenUtil,
                v2: v2,
                v3: v3,
                v4: v4,
                warn: warn,
                warnID: warnID
            });

            const WECHAT = false;
            const ALIPAY = false;
            const BAIDU = false;
            const XIAOMI = false;
            const BYTEDANCE = false;
            const OPPO = false;
            const VIVO = false;
            const HUAWEI = false;
            const COCOSPLAY = false;
            const EDITOR = false;
            const PREVIEW = false;
            const BUILD = true;
            const TEST = false;
            const DEBUG = true;
            const DEV = false;
            const RUNTIME_BASED = false;
            const MINIGAME = false;
            const JSB = false;
            const SUPPORT_JIT = true;

            var _global = typeof window === 'undefined' ? global : window;

            var legacyCC = exports('cclegacy', {
              _global: _global
            });
            legacyCC.internal = {};

            {
              _global.CC_BUILD = BUILD;
              _global.CC_TEST = TEST;
              _global.CC_EDITOR = EDITOR;
              _global.CC_PREVIEW = PREVIEW;
              _global.CC_DEV = DEV;
              _global.CC_DEBUG = DEBUG;
              _global.CC_JSB = JSB;
              _global.CC_BYTEDANCE = BYTEDANCE;
              _global.CC_WECHAT = WECHAT;
              _global.CC_ALIPAY = ALIPAY;
              _global.CC_XIAOMI = XIAOMI;
              _global.CC_BAIDU = BAIDU;
              _global.CC_COCOSPLAY = COCOSPLAY;
              _global.CC_HUAWEI = HUAWEI;
              _global.CC_OPPO = OPPO;
              _global.CC_VIVO = VIVO;
              _global.CC_MINIGAME = MINIGAME;
              _global.CC_RUNTIME_BASED = RUNTIME_BASED;
              _global.CC_SUPPORT_JIT = SUPPORT_JIT;
            }

            var engineVersion = exports('VERSION', '3.2.1');
            _global.CocosEngine = legacyCC.ENGINE_VERSION = engineVersion;
            _global.cc = legacyCC;

            var debugInfos = {
            	"1100": "Expected 'data' dict, but not found. Config file: %s",
            	"1101": "Please load the resource first : %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",
            	"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",
            	"1607": "removeFromParentAndCleanup is deprecated. Use removeFromParent instead",
            	"1619": "callback function must be non-null",
            	"1620": "interval must be positive",
            	"1623": "Set '%s' to normal node (not persist root node).",
            	"1624": "Replacing with the same sgNode",
            	"1625": "The replacement sgNode should not contain any child.",
            	"1626": "Should not set alpha via 'color', set 'opacity' please.",
            	"1627": "Not support for asynchronous creating node in SG",
            	"1632": "Node name can not include '/'.",
            	"1633": "Internal error, should not remove unknown node from parent.",
            	"1635": "reorderChild: this child is not in children list.",
            	"1636": "Node's zIndex value can't be greater than cc.macro.MAX_ZINDEX, setting to the maximum value",
            	"1637": "Node's zIndex value can't be smaller than cc.macro.MIN_ZINDEX, setting to the minimum value",
            	"1638": "Private node's zIndex can't be set, it will keep cc.macro.MIN_ZINDEX as its value",
            	"1800": "cc._EventListenerKeyboard.checkAvailable(): Invalid EventListenerKeyboard!",
            	"1801": "cc._EventListenerTouchOneByOne.checkAvailable(): Invalid EventListenerTouchOneByOne!",
            	"1802": "cc._EventListenerTouchAllAtOnce.checkAvailable(): Invalid EventListenerTouchAllAtOnce!",
            	"1803": "cc._EventListenerAcceleration.checkAvailable():_onAccelerationEvent must be non-nil",
            	"1900": "Invalid parameter.",
            	"2200": "Design resolution not valid",
            	"2201": "should set resolutionPolicy",
            	"2300": "The touches is more than MAX_TOUCHES, nUnusedIndex = %s",
            	"2402": "Forward pipeline startup failed!",
            	"3103": "cc.Texture.addImage(): path should be non-null",
            	"3119": "Lazy init texture with image element failed due to image loading failure: %s",
            	"3120": "Loading texture with unsupported type: '%s'. Add '%s' into 'cc.macro.SUPPORT_TEXTURE_FORMATS' please.",
            	"3121": "Can't find a texture format supported by the current platform! Please add a fallback format in the editor.",
            	"3300": "Rect width exceeds maximum margin: %s",
            	"3301": "Rect height exceeds maximum margin: %s",
            	"3500": "0 priority is forbidden for fixed priority since it's used for scene graph based priority.",
            	"3501": "Invalid listener type!",
            	"3502": "Can't set fixed priority with scene graph based listener.",
            	"3503": "Invalid parameters.",
            	"3504": "listener must be a cc.EventListener object when adding a fixed priority listener",
            	"3505": "The listener has been registered, please don't register it again.",
            	"3506": "Unsupported listener target.",
            	"3507": "Invalid scene graph priority!",
            	"3508": "If program goes here, there should be event in dispatch.",
            	"3509": "_inDispatch should be 1 here.",
            	"3510": "%s's scene graph node not contains in the parent's children",
            	"3511": "event is undefined",
            	"3512": "Event manager only support scene graph priority for ui nodes which contain UIComponent",
            	"3520": "Device Motion Event request permission: %s",
            	"3521": "Device Motion Event request permission failed: %s",
            	"3601": "The editor property 'playOnFocus' should be used with 'executeInEditMode' in class '%s'",
            	"3602": "Unknown editor property '%s' in class '%s'.",
            	"3603": "Use 'cc.Float' or 'cc.Integer' instead of 'cc.Number' please.",
            	"3604": "Can only indicate one type attribute for %s.",
            	"3605": "The default value of %s is not instance of %s.",
            	"3606": "No needs to indicate the '%s' attribute for %s, which its default value is type of %s.",
            	"3607": "The default value of %s must be an empty string.",
            	"3608": "The type of %s must be CCString, not String.",
            	"3609": "The type of %s must be CCBoolean, not Boolean.",
            	"3610": "The type of %s must be CCFloat or CCInteger, not Number.",
            	"3611": "Can not indicate the '%s' attribute for %s, which its default value is type of %s.",
            	"3612": "%s Just set the default value to 'new %s()' and it will be handled properly.",
            	"3613": "'No need to use 'serializable: false' or 'editorOnly: true' for the getter of '%s.%s', every getter is actually non-serialized.",
            	"3614": "Should not define constructor for cc.Component %s.",
            	"3615": "Each script can have at most one Component.",
            	"3616": "Should not specify class name %s for Component which defines in project.",
            	"3618": "ctor of '%s' can not be another CCClass",
            	"3623": "Can not use 'editor' attribute, '%s' not inherits from Components.",
            	"3625": "[isChildClassOf] superclass should be function type, not",
            	"3626": "Can't remove '%s' because '%s' depends on it.",
            	"3627": "Should not add renderer component (%s) to a Canvas node.",
            	"3628": "Should not add %s to a node which size is already used by its other component.",
            	"3633": "Properties function of '%s' should return an object!",
            	"3634": "Disallow to use '.' in property name",
            	"3637": "Can not declare %s.%s, it is already defined in the prototype of %s",
            	"3639": "Can not apply the specified attribute to the getter of '%s.%s', attribute index: %s",
            	"3640": "'%s': the setter of '%s' is already defined!",
            	"3641": "Can not construct %s because it contains object property.",
            	"3644": "Please define 'type' parameter of %s.%s as the actual constructor.",
            	"3645": "Please define 'type' parameter of %s.%s as the constructor of %s.",
            	"3646": "Unknown 'type' parameter of %s.%s：%s",
            	"3647": "The length of range array must be equal or greater than 2",
            	"3648": "Can not declare %s.%s method, it is already defined in the properties of %s.",
            	"3652": "Failed to `new %s()` under the hood, %s\nIt is used for getting default values declared in TypeScript in the first place.\nPlease ensure the constructor can be called during the script's initialization.",
            	"3653": "Please do not specifiy \"default\" attribute in decorator of \"%s\" property in \"%s\" class.\nDefault value must be initialized at their declaration:\n\n \n// Before:\n@property({\n  type: cc.SpriteFrame\n  default: null  // <--\n})\nmyProp;\n// After:\n@property({\n  type: cc.SpriteFrame\n})\nmyProp = null;   // <--",
            	"3654": "Please specifiy a default value for \"%s.%s\" property at its declaration:\n\n \n// Before:\n@property(...)\nmyProp;\n// After:\n@property(...)\nmyProp = 0;",
            	"3655": "Can not specifiy \"get\" or \"set\"  attribute in decorator for \"%s\" property in \"%s\" class.\nPlease use:\n\n \n@property(...)\nget %s () {\n    ...\n}\n@property\nset %s (value) {\n    ...\n}",
            	"3659": "Violation error: extending enumerations shall have non-overlaped member names or member values",
            	"3660": "You are explicitly specifying `undefined` type to cc property \"%s\" of cc class \"%s\".\nIs this intended? If not, this may indicate a circular reference.\nFor example:\n\n \n// foo.ts\nimport { _decorator } from 'cc';\nimport { Bar } from './bar';  // Given that './bar' also reference 'foo.ts'.\n                              // When importing './bar', execution of './bar' is hung on to wait execution of 'foo.ts',\n                              // the `Bar` imported here is `undefined` until './bar' finish its execution.\n                              // It leads to that\n@_decorator.ccclass           //  ↓\nexport class Foo {            //  ↓\n    @_decorator.type(Bar)     //  → is equivalent to `@_decorator.type(undefined)`\n    public bar: Bar;          // To eliminate this error, either:\n                              // - Refactor your module structure(recommended), or\n                              // - specify the type as cc class name: `@_decorator.type('Bar'/* or any name you specified for `Bar` */)`\n}",
            	"3700": "internal error: _prefab is undefined",
            	"3701": "Failed to load prefab asset for node '%s'",
            	"3800": "The target can not be made persist because it's not a cc.Node or it doesn't have _id property.",
            	"3801": "The node can not be made persist because it's not under root node.",
            	"3802": "The node can not be made persist because it's not in current scene.",
            	"3803": "The target can not be made persist because it's not a cc.Node or it doesn't have _id property.",
            	"3804": "getComponent: Type must be non-nil",
            	"3805": "Can't add component '%s' because %s already contains the same component.",
            	"3806": "Can't add component '%s' to %s because it conflicts with the existing '%s' derived component.",
            	"3807": "addComponent: Failed to get class '%s'",
            	"3808": "addComponent: Should not add component ('%s') when the scripts are still loading.",
            	"3809": "addComponent: The component to add must be a constructor",
            	"3810": "addComponent: The component to add must be child class of cc.Component",
            	"3811": "_addComponentAt: The component to add must be a constructor",
            	"3812": "_addComponentAt: Index out of range",
            	"3813": "removeComponent: Component must be non-nil",
            	"3814": "Argument must be non-nil",
            	"3815": "Component not owned by this entity",
            	"3816": "Node '%s' is already activating",
            	"3817": "Sorry, the component of '%s' which with an index of %s is corrupted! It has been removed.",
            	"3818": "Failed to read or parse project.json",
            	"3819": "Warning: target element is not a DIV or CANVAS",
            	"3820": "The renderer doesn't support the renderMode %s",
            	"3821": "Cannot change hierarchy while activating or deactivating the parent.",
            	"3822": "addComponent: Cannot add any component to the scene.",
            	"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": "animator not added or already removed",
            	"3912": "already-playing",
            	"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.",
            	"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.",
            	"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",
            	"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",
            	"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",
            	"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.",
            	"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",
            	"9100": "texture size exceeds current device limits %d/%d",
            	"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",
            	"9620": "[Physics][Ammo]: changing the mesh is not supported after the initialization is completed",
            	"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.",
            	"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.",
            	"0100": "%s not yet implemented.",
            	"0200": "You should specify a valid DOM canvas element."
            };

            var logList = null;
            var ccLog = console.log.bind(console);
            var ccWarn = ccLog;
            var ccError = ccLog;

            var ccAssert = function ccAssert(condition, message) {
              if (!condition) {
                for (var _len = arguments.length, optionalParams = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
                  optionalParams[_key - 2] = arguments[_key];
                }

                console.log("ASSERT: " + formatString.apply(void 0, [message].concat(optionalParams)));
              }
            };

            var ccDebug = ccLog;

            function formatString(message) {
              for (var _len2 = arguments.length, optionalParams = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
                optionalParams[_key2 - 1] = arguments[_key2];
              }

              return legacyCC.js.formatStr.apply(null, [message].concat(optionalParams));
            }

            function log(message) {
              for (var _len3 = arguments.length, optionalParams = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
                optionalParams[_key3 - 1] = arguments[_key3];
              }

              return ccLog.apply(void 0, [message].concat(optionalParams));
            }
            function warn(message) {
              for (var _len4 = arguments.length, optionalParams = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
                optionalParams[_key4 - 1] = arguments[_key4];
              }

              return ccWarn.apply(void 0, [message].concat(optionalParams));
            }
            function error(message) {
              for (var _len5 = arguments.length, optionalParams = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) {
                optionalParams[_key5 - 1] = arguments[_key5];
              }

              return ccError.apply(void 0, [message].concat(optionalParams));
            }
            function assert(value, message) {
              for (var _len6 = arguments.length, optionalParams = new Array(_len6 > 2 ? _len6 - 2 : 0), _key6 = 2; _key6 < _len6; _key6++) {
                optionalParams[_key6 - 2] = arguments[_key6];
              }

              return ccAssert.apply(void 0, [value, message].concat(optionalParams));
            }
            function debug() {
              return ccDebug.apply(void 0, arguments);
            }
            function _resetDebugSetting(mode) {
              ccLog = ccWarn = ccError = ccAssert = ccDebug = function ccDebug() {};

              if (mode === DebugMode.NONE) {
                return;
              }

              if (mode > DebugMode.ERROR) {
                var logToWebPage = function logToWebPage(msg) {
                  if (!legacyCC.game.canvas) {
                    return;
                  }

                  if (!logList) {
                    var logDiv = document.createElement('Div');
                    logDiv.setAttribute('id', 'logInfoDiv');
                    logDiv.setAttribute('width', '200');
                    logDiv.setAttribute('height', legacyCC.game.canvas.height);
                    var logDivStyle = logDiv.style;
                    logDivStyle.zIndex = '99999';
                    logDivStyle.position = 'absolute';
                    logDivStyle.top = logDivStyle.left = '0';
                    logList = document.createElement('textarea');
                    logList.setAttribute('rows', '20');
                    logList.setAttribute('cols', '30');
                    logList.setAttribute('disabled', 'true');
                    var logListStyle = logList.style;
                    logListStyle.backgroundColor = 'transparent';
                    logListStyle.borderBottom = '1px solid #cccccc';
                    logListStyle.borderTopWidth = logListStyle.borderLeftWidth = logListStyle.borderRightWidth = '0px';
                    logListStyle.borderTopStyle = logListStyle.borderLeftStyle = logListStyle.borderRightStyle = 'none';
                    logListStyle.padding = '0px';
                    logListStyle.margin = '0px';
                    logDiv.appendChild(logList);
                    legacyCC.game.canvas.parentNode.appendChild(logDiv);
                  }

                  logList.value = logList.value + msg + "\r\n";
                  logList.scrollTop = logList.scrollHeight;
                };

                ccError = function ccError(message) {
                  for (var _len7 = arguments.length, optionalParams = new Array(_len7 > 1 ? _len7 - 1 : 0), _key7 = 1; _key7 < _len7; _key7++) {
                    optionalParams[_key7 - 1] = arguments[_key7];
                  }

                  logToWebPage("ERROR :  " + formatString.apply(void 0, [message].concat(optionalParams)));
                };

                ccAssert = function ccAssert(condition, message) {
                  if (!condition) {
                    for (var _len8 = arguments.length, optionalParams = new Array(_len8 > 2 ? _len8 - 2 : 0), _key8 = 2; _key8 < _len8; _key8++) {
                      optionalParams[_key8 - 2] = arguments[_key8];
                    }

                    logToWebPage("ASSERT: " + formatString.apply(void 0, [message].concat(optionalParams)));
                  }
                };

                if (mode !== DebugMode.ERROR_FOR_WEB_PAGE) {
                  ccWarn = function ccWarn(message) {
                    for (var _len9 = arguments.length, optionalParams = new Array(_len9 > 1 ? _len9 - 1 : 0), _key9 = 1; _key9 < _len9; _key9++) {
                      optionalParams[_key9 - 1] = arguments[_key9];
                    }

                    logToWebPage("WARN :  " + formatString.apply(void 0, [message].concat(optionalParams)));
                  };
                }

                if (mode === DebugMode.INFO_FOR_WEB_PAGE) {
                  ccLog = function ccLog(message) {
                    for (var _len10 = arguments.length, optionalParams = new Array(_len10 > 1 ? _len10 - 1 : 0), _key10 = 1; _key10 < _len10; _key10++) {
                      optionalParams[_key10 - 1] = arguments[_key10];
                    }

                    logToWebPage(formatString.apply(void 0, [message].concat(optionalParams)));
                  };
                }
              } else if (console) {
                if (!console.error) {
                  console.error = console.log;
                }

                if (!console.warn) {
                  console.warn = console.log;
                }

                if ( console.error.bind) {
                  ccError = console.error.bind(console);
                } else {
                  ccError =  function (message) {
                    for (var _len11 = arguments.length, optionalParams = new Array(_len11 > 1 ? _len11 - 1 : 0), _key11 = 1; _key11 < _len11; _key11++) {
                      optionalParams[_key11 - 1] = arguments[_key11];
                    }

                    return console.error.apply(console, [message].concat(optionalParams));
                  };
                }

                ccAssert = function ccAssert(condition, message) {
                  if (!condition) {
                    for (var _len12 = arguments.length, optionalParams = new Array(_len12 > 2 ? _len12 - 2 : 0), _key12 = 2; _key12 < _len12; _key12++) {
                      optionalParams[_key12 - 2] = arguments[_key12];
                    }

                    var errorText = formatString.apply(void 0, [message].concat(optionalParams));

                    {
                      throw new Error(errorText);
                    }
                  }
                };
              }

              if (mode !== DebugMode.ERROR) {
                if (console.warn.bind) {
                  ccWarn = console.warn.bind(console);
                } else {
                  ccWarn =  function (message) {
                    for (var _len13 = arguments.length, optionalParams = new Array(_len13 > 1 ? _len13 - 1 : 0), _key13 = 1; _key13 < _len13; _key13++) {
                      optionalParams[_key13 - 1] = arguments[_key13];
                    }

                    return console.warn.apply(console, [message].concat(optionalParams));
                  };
                }
              }

              if (mode === DebugMode.INFO) {
                if (console.log.bind) {
                  ccLog = console.log.bind(console);
                } else {
                  ccLog = function ccLog(message) {
                    for (var _len15 = arguments.length, optionalParams = new Array(_len15 > 1 ? _len15 - 1 : 0), _key15 = 1; _key15 < _len15; _key15++) {
                      optionalParams[_key15 - 1] = arguments[_key15];
                    }

                    return console.log.apply(console, [message].concat(optionalParams));
                  };
                }
              }

              if (mode <= DebugMode.VERBOSE) {
                if (typeof console.debug === 'function') {
                  var vendorDebug = console.debug;

                  ccDebug = function ccDebug() {
                    return vendorDebug.apply(void 0, arguments);
                  };
                }
              }
            }
            function _throw(error_) {
              {
                var stack = error_.stack;

                if (stack) {
                  error( stack);
                } else {
                  error(error_);
                }

                return undefined;
              }
            }

            function getTypedFormatter(type) {
              return function (id) {
                var msg =  debugInfos[id] || 'unknown id' ;

                for (var _len16 = arguments.length, args = new Array(_len16 > 1 ? _len16 - 1 : 0), _key16 = 1; _key16 < _len16; _key16++) {
                  args[_key16 - 1] = arguments[_key16];
                }

                if (args.length === 0) {
                  return msg;
                }

                return  formatString.apply(void 0, [msg].concat(args)) ;
              };
            }

            var logFormatter = getTypedFormatter();
            function logID(id) {
              for (var _len17 = arguments.length, optionalParams = new Array(_len17 > 1 ? _len17 - 1 : 0), _key17 = 1; _key17 < _len17; _key17++) {
                optionalParams[_key17 - 1] = arguments[_key17];
              }

              log(logFormatter.apply(void 0, [id].concat(optionalParams)));
            }
            var warnFormatter = getTypedFormatter();
            function warnID(id) {
              for (var _len18 = arguments.length, optionalParams = new Array(_len18 > 1 ? _len18 - 1 : 0), _key18 = 1; _key18 < _len18; _key18++) {
                optionalParams[_key18 - 1] = arguments[_key18];
              }

              warn(warnFormatter.apply(void 0, [id].concat(optionalParams)));
            }
            var errorFormatter = getTypedFormatter();
            function errorID(id) {
              for (var _len19 = arguments.length, optionalParams = new Array(_len19 > 1 ? _len19 - 1 : 0), _key19 = 1; _key19 < _len19; _key19++) {
                optionalParams[_key19 - 1] = arguments[_key19];
              }

              error(errorFormatter.apply(void 0, [id].concat(optionalParams)));
            }
            var assertFormatter = getTypedFormatter();
            function assertID(condition, id) {
              if (condition) {
                return;
              }

              for (var _len20 = arguments.length, optionalParams = new Array(_len20 > 2 ? _len20 - 2 : 0), _key20 = 2; _key20 < _len20; _key20++) {
                optionalParams[_key20 - 2] = arguments[_key20];
              }

              assert(false, assertFormatter.apply(void 0, [id].concat(optionalParams)));
            }
            var DebugMode;

            (function (DebugMode) {
              DebugMode[DebugMode["NONE"] = 0] = "NONE";
              DebugMode[DebugMode["VERBOSE"] = 1] = "VERBOSE";
              DebugMode[DebugMode["INFO"] = 2] = "INFO";
              DebugMode[DebugMode["WARN"] = 3] = "WARN";
              DebugMode[DebugMode["ERROR"] = 4] = "ERROR";
              DebugMode[DebugMode["INFO_FOR_WEB_PAGE"] = 5] = "INFO_FOR_WEB_PAGE";
              DebugMode[DebugMode["WARN_FOR_WEB_PAGE"] = 6] = "WARN_FOR_WEB_PAGE";
              DebugMode[DebugMode["ERROR_FOR_WEB_PAGE"] = 7] = "ERROR_FOR_WEB_PAGE";
            })(DebugMode || (DebugMode = exports('DebugMode', {})));

            function getError(errorId) {
              for (var _len21 = arguments.length, param = new Array(_len21 > 1 ? _len21 - 1 : 0), _key21 = 1; _key21 < _len21; _key21++) {
                param[_key21 - 1] = arguments[_key21];
              }

              return errorFormatter.apply(void 0, [errorId].concat(param));
            }
            function isDisplayStats() {
              return legacyCC.profiler ? legacyCC.profiler.isShowingStats() : false;
            }
            function setDisplayStats(displayStats) {
              if (legacyCC.profiler) {
                displayStats ? legacyCC.profiler.showStats() : legacyCC.profiler.hideStats();
                legacyCC.game.config.showFPS = !!displayStats;
              }
            }

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

            var INT_BITS = 32;
            var INT_MAX = 0x7fffffff;
            var INT_MIN = -1 << INT_BITS - 1;
            function sign(v) {
              return (v > 0) - (v < 0);
            }
            function abs(v) {
              var mask = v >> INT_BITS - 1;
              return (v ^ mask) - mask;
            }
            function min(x, y) {
              return y ^ (x ^ y) & -(x < y);
            }
            function max(x, y) {
              return x ^ (x ^ y) & -(x < y);
            }
            function isPow2(v) {
              return !(v & v - 1) && !!v;
            }
            function log2(v) {
              var r;
              var shift;
              r = (v > 0xFFFF) << 4;
              v >>>= r;
              shift = (v > 0xFF) << 3;
              v >>>= shift;
              r |= shift;
              shift = (v > 0xF) << 2;
              v >>>= shift;
              r |= shift;
              shift = (v > 0x3) << 1;
              v >>>= shift;
              r |= shift;
              return r | v >> 1;
            }
            function log10(v) {
              return v >= 1000000000 ? 9 : v >= 100000000 ? 8 : v >= 10000000 ? 7 : v >= 1000000 ? 6 : v >= 100000 ? 5 : v >= 10000 ? 4 : v >= 1000 ? 3 : v >= 100 ? 2 : v >= 10 ? 1 : 0;
            }
            function popCount(v) {
              v -= v >>> 1 & 0x55555555;
              v = (v & 0x33333333) + (v >>> 2 & 0x33333333);
              return (v + (v >>> 4) & 0xF0F0F0F) * 0x1010101 >>> 24;
            }
            function countTrailingZeros(v) {
              var c = 32;
              v &= -v;

              if (v) {
                c--;
              }

              if (v & 0x0000FFFF) {
                c -= 16;
              }

              if (v & 0x00FF00FF) {
                c -= 8;
              }

              if (v & 0x0F0F0F0F) {
                c -= 4;
              }

              if (v & 0x33333333) {
                c -= 2;
              }

              if (v & 0x55555555) {
                c -= 1;
              }

              return c;
            }
            function nextPow2(v) {
              v += v === 0;
              --v;
              v |= v >>> 1;
              v |= v >>> 2;
              v |= v >>> 4;
              v |= v >>> 8;
              v |= v >>> 16;
              return v + 1;
            }
            function prevPow2(v) {
              v |= v >>> 1;
              v |= v >>> 2;
              v |= v >>> 4;
              v |= v >>> 8;
              v |= v >>> 16;
              return v - (v >>> 1);
            }
            function parity(v) {
              v ^= v >>> 16;
              v ^= v >>> 8;
              v ^= v >>> 4;
              v &= 0xf;
              return 0x6996 >>> v & 1;
            }
            var REVERSE_TABLE = new Array(256);

            (function (tab) {
              for (var i = 0; i < 256; ++i) {
                var v = i;
                var r = i;
                var s = 7;

                for (v >>>= 1; v; v >>>= 1) {
                  r <<= 1;
                  r |= v & 1;
                  --s;
                }

                tab[i] = r << s & 0xff;
              }
            })(REVERSE_TABLE);

            function reverse(v) {
              return REVERSE_TABLE[v & 0xff] << 24 | REVERSE_TABLE[v >>> 8 & 0xff] << 16 | REVERSE_TABLE[v >>> 16 & 0xff] << 8 | REVERSE_TABLE[v >>> 24 & 0xff];
            }
            function interleave2(x, y) {
              x &= 0xFFFF;
              x = (x | x << 8) & 0x00FF00FF;
              x = (x | x << 4) & 0x0F0F0F0F;
              x = (x | x << 2) & 0x33333333;
              x = (x | x << 1) & 0x55555555;
              y &= 0xFFFF;
              y = (y | y << 8) & 0x00FF00FF;
              y = (y | y << 4) & 0x0F0F0F0F;
              y = (y | y << 2) & 0x33333333;
              y = (y | y << 1) & 0x55555555;
              return x | y << 1;
            }
            function deinterleave2(v, n) {
              v = v >>> n & 0x55555555;
              v = (v | v >>> 1) & 0x33333333;
              v = (v | v >>> 2) & 0x0F0F0F0F;
              v = (v | v >>> 4) & 0x00FF00FF;
              v = (v | v >>> 16) & 0x000FFFF;
              return v << 16 >> 16;
            }
            function interleave3(x, y, z) {
              x &= 0x3FF;
              x = (x | x << 16) & 4278190335;
              x = (x | x << 8) & 251719695;
              x = (x | x << 4) & 3272356035;
              x = (x | x << 2) & 1227133513;
              y &= 0x3FF;
              y = (y | y << 16) & 4278190335;
              y = (y | y << 8) & 251719695;
              y = (y | y << 4) & 3272356035;
              y = (y | y << 2) & 1227133513;
              x |= y << 1;
              z &= 0x3FF;
              z = (z | z << 16) & 4278190335;
              z = (z | z << 8) & 251719695;
              z = (z | z << 4) & 3272356035;
              z = (z | z << 2) & 1227133513;
              return x | z << 2;
            }
            function deinterleave3(v, n) {
              v = v >>> n & 1227133513;
              v = (v | v >>> 2) & 3272356035;
              v = (v | v >>> 4) & 251719695;
              v = (v | v >>> 8) & 4278190335;
              v = (v | v >>> 16) & 0x3FF;
              return v << 22 >> 22;
            }
            function nextCombination(v) {
              var t = v | v - 1;
              return t + 1 | (~t & -~t) - 1 >>> countTrailingZeros(v) + 1;
            }

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

            var defaultLogTimes = 10;
            function setDefaultLogTimes(times) {
              if (times > 0) {
                defaultLogTimes = times;
              }
            }
            var replaceProperty;
            var removeProperty;
            var markAsWarning;
            var replacePropertyLog;
            var markAsWarningLog;
            var removePropertyLog;
            var messageID = 0;
            var messageMap = new Map();

            replacePropertyLog = function replacePropertyLog(n, dp, n2, newp, f, id, s) {
              var item = messageMap.get(id);

              if (item && item.logTimes > item.count) {
                f("'%s' is deprecated, please use '%s' instead. " + s, n + "." + dp, n2 + "." + newp);
                item.count++;
              }
            };

            replaceProperty = exports('replaceProperty', function replaceProperty(owner, ownerName, properties) {
              if (owner == null) return;
              properties.forEach(function (item) {
                var id = messageID++;
                messageMap.set(id, {
                  id: id,
                  count: 0,
                  logTimes: item.logTimes !== undefined ? item.logTimes : defaultLogTimes
                });
                var target = item.target != null ? item.target : owner;
                var newName = item.newName != null ? item.newName : item.name;
                var targetName = item.targetName != null ? item.targetName : ownerName;
                var sameTarget = target === owner;
                var suggest = item.suggest ? "(" + item.suggest + ")" : '';

                if (item.customFunction != null) {
                  owner[item.name] = function () {
                    var _ref;

                    replacePropertyLog(ownerName, item.name, targetName, newName, warn, id, suggest);
                    return (_ref = item.customFunction).call.apply(_ref, [this].concat(Array.prototype.slice.call(arguments)));
                  };
                } else if (item.customSetter != null || item.customGetter != null) {
                  var hasSetter = item.customSetter != null;
                  var hasGetter = item.customGetter != null;

                  if (hasSetter && hasGetter) {
                    Object.defineProperty(owner, item.name, {
                      get: function get() {
                        replacePropertyLog(ownerName, item.name, targetName, newName, warn, id, suggest);
                        return item.customGetter.call(this);
                      },
                      set: function set(v) {
                        replacePropertyLog(ownerName, item.name, targetName, newName, warn, id, suggest);
                        item.customSetter.call(this, v);
                      },
                      enumerable: false
                    });
                  } else if (hasSetter) {
                    Object.defineProperty(owner, item.name, {
                      set: function set(v) {
                        replacePropertyLog(ownerName, item.name, targetName, newName, warn, id, suggest);
                        item.customSetter.call(this, v);
                      },
                      enumerable: false
                    });
                  } else if (hasGetter) {
                    Object.defineProperty(owner, item.name, {
                      get: function get() {
                        replacePropertyLog(ownerName, item.name, targetName, newName, warn, id, suggest);
                        return item.customGetter.call(this);
                      },
                      enumerable: false
                    });
                  }
                } else {
                  Object.defineProperty(owner, item.name, {
                    get: function get() {
                      replacePropertyLog(ownerName, item.name, targetName, newName, warn, id, suggest);
                      return sameTarget ? this[newName] : target[newName];
                    },
                    set: function set(v) {
                      replacePropertyLog(ownerName, item.name, targetName, newName, warn, id, suggest);

                      if (sameTarget) {
                        this[newName] = v;
                      } else {
                        target[newName] = v;
                      }
                    },
                    enumerable: false
                  });
                }
              });
            });

            removePropertyLog = function removePropertyLog(n, dp, f, id, s) {
              var item = messageMap.get(id);

              if (item && item.logTimes > item.count) {
                f("'%s' has been removed. " + s, n + "." + dp);
                item.count++;
              }
            };

            removeProperty = exports('removeProperty', function removeProperty(owner, ownerName, properties) {
              if (owner == null) return;
              properties.forEach(function (item) {
                var id = messageID++;
                messageMap.set(id, {
                  id: id,
                  count: 0,
                  logTimes: item.logTimes !== undefined ? item.logTimes : defaultLogTimes
                });
                var suggest = item.suggest ? "(" + item.suggest + ")" : '';
                Object.defineProperty(owner, item.name, {
                  get: function get() {
                    return removePropertyLog(ownerName, item.name, error, id, suggest);
                  },
                  set: function set() {
                    removePropertyLog(ownerName, item.name, error, id, suggest);
                  },
                  enumerable: false
                });
              });
            });

            markAsWarningLog = function markAsWarningLog(n, dp, f, id, s) {
              var item = messageMap.get(id);

              if (item && item.logTimes > item.count) {
                f("'%s' is deprecated. " + s, n + "." + dp);
                item.count++;
              }
            };

            markAsWarning = exports('markAsWarning', function markAsWarning(owner, ownerName, properties) {
              if (owner == null) return;

              var _defaultGetSet = function _defaultGetSet(d, n, dp, f, id, s) {
                if (d.get) {
                  var oldGet = d.get;

                  d.get = function () {
                    markAsWarningLog(n, dp, f, id, s);
                    return oldGet.call(this);
                  };
                }

                if (d.set) {
                  var oldSet = d.set;

                  d.set = function (v) {
                    markAsWarningLog(n, dp, f, id, s);
                    oldSet.call(this, v);
                  };
                }

                Object.defineProperty(owner, dp, d);
              };

              properties.forEach(function (item) {
                var deprecatedProp = item.name;
                var descriptor = Object.getOwnPropertyDescriptor(owner, deprecatedProp);

                if (!descriptor || !descriptor.configurable) {
                  return;
                }

                var id = messageID++;
                messageMap.set(id, {
                  id: id,
                  count: 0,
                  logTimes: item.logTimes !== undefined ? item.logTimes : defaultLogTimes
                });
                var suggest = item.suggest ? "(" + item.suggest + ")" : '';

                if (descriptor.value != null) {
                  if (typeof descriptor.value === 'function') {
                    var oldValue = descriptor.value;

                    owner[deprecatedProp] = function () {
                      markAsWarningLog(ownerName, deprecatedProp, warn, id, suggest);
                      return oldValue.call.apply(oldValue, [this].concat(Array.prototype.slice.call(arguments)));
                    };
                  } else {
                    _defaultGetSet(descriptor, ownerName, deprecatedProp, warn, id, suggest);
                  }
                } else {
                  _defaultGetSet(descriptor, ownerName, deprecatedProp, warn, id, suggest);
                }

                Object.defineProperty(owner, deprecatedProp, {
                  enumerable: false
                });
              });
            });

            function _defineProperties(target, props) {
              for (var i = 0; i < props.length; i++) {
                var descriptor = props[i];
                descriptor.enumerable = descriptor.enumerable || false;
                descriptor.configurable = true;
                if ("value" in descriptor) descriptor.writable = true;
                Object.defineProperty(target, descriptor.key, descriptor);
              }
            }

            function _createClass(Constructor, protoProps, staticProps) {
              if (protoProps) _defineProperties(Constructor.prototype, protoProps);
              if (staticProps) _defineProperties(Constructor, staticProps);
              return Constructor;
            }

            function _extends() {
              _extends = Object.assign || function (target) {
                for (var i = 1; i < arguments.length; i++) {
                  var source = arguments[i];

                  for (var key in source) {
                    if (Object.prototype.hasOwnProperty.call(source, key)) {
                      target[key] = source[key];
                    }
                  }
                }

                return target;
              };

              return _extends.apply(this, arguments);
            }

            function _inheritsLoose(subClass, superClass) {
              subClass.prototype = Object.create(superClass.prototype);
              subClass.prototype.constructor = subClass;

              _setPrototypeOf(subClass, superClass);
            }

            function _setPrototypeOf(o, p) {
              _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
                o.__proto__ = p;
                return o;
              };

              return _setPrototypeOf(o, p);
            }

            function _isNativeReflectConstruct() {
              if (typeof Reflect === "undefined" || !Reflect.construct) return false;
              if (Reflect.construct.sham) return false;
              if (typeof Proxy === "function") return true;

              try {
                Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
                return true;
              } catch (e) {
                return false;
              }
            }

            function _construct(Parent, args, Class) {
              if (_isNativeReflectConstruct()) {
                _construct = Reflect.construct;
              } else {
                _construct = function _construct(Parent, args, Class) {
                  var a = [null];
                  a.push.apply(a, args);
                  var Constructor = Function.bind.apply(Parent, a);
                  var instance = new Constructor();
                  if (Class) _setPrototypeOf(instance, Class.prototype);
                  return instance;
                };
              }

              return _construct.apply(null, arguments);
            }

            function _assertThisInitialized(self) {
              if (self === void 0) {
                throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
              }

              return self;
            }

            function _unsupportedIterableToArray(o, minLen) {
              if (!o) return;
              if (typeof o === "string") return _arrayLikeToArray(o, minLen);
              var n = Object.prototype.toString.call(o).slice(8, -1);
              if (n === "Object" && o.constructor) n = o.constructor.name;
              if (n === "Map" || n === "Set") return Array.from(o);
              if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
            }

            function _arrayLikeToArray(arr, len) {
              if (len == null || len > arr.length) len = arr.length;

              for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];

              return arr2;
            }

            function _createForOfIteratorHelperLoose(o, allowArrayLike) {
              var it;

              if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
                if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
                  if (it) o = it;
                  var i = 0;
                  return function () {
                    if (i >= o.length) return {
                      done: true
                    };
                    return {
                      done: false,
                      value: o[i++]
                    };
                  };
                }

                throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
              }

              it = o[Symbol.iterator]();
              return it.next.bind(it);
            }

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

            var MutableForwardIterator = function () {
              function MutableForwardIterator(array) {
                this.i = 0;
                this.array = array;
              }

              var _proto = MutableForwardIterator.prototype;

              _proto.remove = function remove(value) {
                var index = this.array.indexOf(value);

                if (index >= 0) {
                  this.removeAt(index);
                }
              };

              _proto.removeAt = function removeAt(i) {
                this.array.splice(i, 1);

                if (i <= this.i) {
                  --this.i;
                }
              };

              _proto.fastRemove = function fastRemove(value) {
                var index = this.array.indexOf(value);

                if (index >= 0) {
                  this.fastRemoveAt(index);
                }
              };

              _proto.fastRemoveAt = function fastRemoveAt(i) {
                var array = this.array;
                array[i] = array[array.length - 1];
                --array.length;

                if (i <= this.i) {
                  --this.i;
                }
              };

              _proto.push = function push(item) {
                this.array.push(item);
              };

              _createClass(MutableForwardIterator, [{
                key: "length",
                get: function get() {
                  return this.array.length;
                },
                set: function set(value) {
                  this.array.length = value;

                  if (this.i >= value) {
                    this.i = value - 1;
                  }
                }
              }]);

              return MutableForwardIterator;
            }();

            function removeAt(array, index) {
              array.splice(index, 1);
            }
            function fastRemoveAt(array, index) {
              var length = array.length;

              if (index < 0 || index >= length) {
                return;
              }

              array[index] = array[length - 1];
              array.length = length - 1;
            }
            function remove(array, value) {
              var index = array.indexOf(value);

              if (index >= 0) {
                removeAt(array, index);
                return true;
              } else {
                return false;
              }
            }
            function fastRemove(array, value) {
              var index = array.indexOf(value);

              if (index >= 0) {
                array[index] = array[array.length - 1];
                --array.length;
              }
            }
            function removeIf(array, predicate) {
              var index = array.findIndex(predicate);

              if (index >= 0) {
                var _value = array[index];
                removeAt(array, index);
                return _value;
              }
            }
            function verifyType(array, type) {
              if (array && array.length > 0) {
                for (var _iterator = _createForOfIteratorHelperLoose(array), _step; !(_step = _iterator()).done;) {
                  var item = _step.value;

                  if (!(item instanceof type)) {
                    logID(1300);
                    return false;
                  }
                }
              }

              return true;
            }
            function removeArray(array, removals) {
              for (var i = 0, l = removals.length; i < l; i++) {
                remove(array, removals[i]);
              }
            }
            function appendObjectsAt(array, objects, index) {
              array.splice.apply(array, [index, 0].concat(objects));
              return array;
            }
            function contains(array, value) {
              return array.indexOf(value) >= 0;
            }
            function copy(array) {
              var len = array.length;
              var cloned = new Array(len);

              for (var i = 0; i < len; i += 1) {
                cloned[i] = array[i];
              }

              return cloned;
            }

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

            var NonUuidMark = '.';

            var IDGenerator = function () {
              function IDGenerator(category) {
                this.id = void 0;
                this.prefix = void 0;
                this.id = 0 | Math.random() * 998;
                this.prefix = category ? category + NonUuidMark : '';
              }

              var _proto = IDGenerator.prototype;

              _proto.getNewId = function getNewId() {

                return this.prefix + ++this.id;
              };

              return IDGenerator;
            }();

            IDGenerator.global = new IDGenerator('global');

            var tempCIDGenerator = new IDGenerator('TmpCId.');
            var aliasesTag = typeof Symbol === 'undefined' ? '__aliases__' : Symbol('[[Aliases]]');
            var classNameTag = '__classname__';
            var classIdTag = '__cid__';
            function isNumber(object) {
              return typeof object === 'number' || object instanceof Number;
            }
            function isString(object) {
              return typeof object === 'string' || object instanceof String;
            }
            function isEmptyObject(obj) {
              for (var key in obj) {
                return false;
              }

              return true;
            }
            var value = function () {
              var descriptor = {
                value: undefined,
                enumerable: false,
                writable: false,
                configurable: true
              };
              return function (object, propertyName, value_, writable, enumerable) {
                descriptor.value = value_;
                descriptor.writable = writable;
                descriptor.enumerable = enumerable;
                Object.defineProperty(object, propertyName, descriptor);
                descriptor.value = undefined;
              };
            }();
            var getset = function () {
              var descriptor = {
                get: undefined,
                set: undefined,
                enumerable: false
              };
              return function (object, propertyName, getter, setter, enumerable, configurable) {
                if (enumerable === void 0) {
                  enumerable = false;
                }

                if (configurable === void 0) {
                  configurable = false;
                }

                if (typeof setter === 'boolean') {
                  enumerable = setter;
                  setter = undefined;
                }

                descriptor.get = getter;
                descriptor.set = setter;
                descriptor.enumerable = enumerable;
                descriptor.configurable = configurable;
                Object.defineProperty(object, propertyName, descriptor);
                descriptor.get = undefined;
                descriptor.set = undefined;
              };
            }();
            var get = function () {
              var descriptor = {
                get: undefined,
                enumerable: false,
                configurable: false
              };
              return function (object, propertyName, getter, enumerable, configurable) {
                descriptor.get = getter;
                descriptor.enumerable = enumerable;
                descriptor.configurable = configurable;
                Object.defineProperty(object, propertyName, descriptor);
                descriptor.get = undefined;
              };
            }();
            var set = function () {
              var descriptor = {
                set: undefined,
                enumerable: false,
                configurable: false
              };
              return function (object, propertyName, setter, enumerable, configurable) {
                descriptor.set = setter;
                descriptor.enumerable = enumerable;
                descriptor.configurable = configurable;
                Object.defineProperty(object, propertyName, descriptor);
                descriptor.set = undefined;
              };
            }();
            function createMap(forceDictMode) {
              var map = Object.create(null);

              if (forceDictMode) {
                var INVALID_IDENTIFIER_1 = '.';
                var INVALID_IDENTIFIER_2 = '/';
                map[INVALID_IDENTIFIER_1] = 1;
                map[INVALID_IDENTIFIER_2] = 1;
                delete map[INVALID_IDENTIFIER_1];
                delete map[INVALID_IDENTIFIER_2];
              }

              return map;
            }
            function getClassName(objOrCtor) {
              if (typeof objOrCtor === 'function') {
                var prototype = objOrCtor.prototype;

                if (prototype && prototype.hasOwnProperty(classNameTag) && prototype[classNameTag]) {
                  return prototype[classNameTag];
                }

                var retval = '';

                if (objOrCtor.name) {
                  retval = objOrCtor.name;
                }

                if (objOrCtor.toString) {
                  var arr;
                  var str = objOrCtor.toString();

                  if (str.charAt(0) === '[') {
                    arr = str.match(/\[\w+\s*(\w+)\]/);
                  } else {
                    arr = str.match(/function\s*(\w+)/);
                  }

                  if (arr && arr.length === 2) {
                    retval = arr[1];
                  }
                }

                return retval !== 'Object' ? retval : '';
              } else if (objOrCtor && objOrCtor.constructor) {
                return getClassName(objOrCtor.constructor);
              }

              return '';
            }
            function obsolete(object, obsoleted, newExpr, writable) {
              var extractPropName = /([^.]+)$/;
              var oldProp = extractPropName.exec(obsoleted)[0];
              var newProp = extractPropName.exec(newExpr)[0];

              function getter() {

                return this[newProp];
              }

              function setter(value_) {

                this[newProp] = value_;
              }

              if (writable) {
                getset(object, oldProp, getter, setter);
              } else {
                get(object, oldProp, getter);
              }
            }
            function obsoletes(obj, objName, props, writable) {
              for (var obsoleted in props) {
                var newName = props[obsoleted];
                obsolete(obj, objName + "." + obsoleted, newName, writable);
              }
            }
            var REGEXP_NUM_OR_STR = /(%d)|(%s)/;
            var REGEXP_STR = /%s/;
            function formatStr(msg) {
              for (var _len = arguments.length, subst = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
                subst[_key - 1] = arguments[_key];
              }

              if (arguments.length === 0) {
                return '';
              }

              if (subst.length === 0) {
                return "" + msg;
              }

              var hasSubstitution = typeof msg === 'string' && REGEXP_NUM_OR_STR.test(msg);

              if (hasSubstitution) {
                for (var _iterator = _createForOfIteratorHelperLoose(subst), _step; !(_step = _iterator()).done;) {
                  var arg = _step.value;
                  var regExpToTest = typeof arg === 'number' ? REGEXP_NUM_OR_STR : REGEXP_STR;

                  if (regExpToTest.test(msg)) {
                    var notReplaceFunction = "" + arg;
                    msg = msg.replace(regExpToTest, notReplaceFunction);
                  } else {
                    msg += " " + arg;
                  }
                }
              } else {
                for (var _iterator2 = _createForOfIteratorHelperLoose(subst), _step2; !(_step2 = _iterator2()).done;) {
                  var _arg = _step2.value;
                  msg += " " + _arg;
                }
              }

              return msg;
            }
            function shiftArguments() {
              var len = arguments.length - 1;
              var args = new Array(len);

              for (var i = 0; i < len; ++i) {
                args[i] = arguments[i + 1];
              }

              return args;
            }
            function getPropertyDescriptor(object, propertyName) {
              while (object) {
                var pd = Object.getOwnPropertyDescriptor(object, propertyName);

                if (pd) {
                  return pd;
                }

                object = Object.getPrototypeOf(object);
              }

              return null;
            }

            function _copyprop(name, source, target) {
              var pd = getPropertyDescriptor(source, name);

              if (pd) {
                Object.defineProperty(target, name, pd);
              }
            }

            function addon(object) {
              object = object || {};

              for (var _len2 = arguments.length, sources = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
                sources[_key2 - 1] = arguments[_key2];
              }

              for (var _i = 0, _sources = sources; _i < _sources.length; _i++) {
                var source = _sources[_i];

                if (source) {
                  if (typeof source !== 'object') {
                    errorID(5402, source);
                    continue;
                  }

                  for (var name in source) {
                    if (!(name in object)) {
                      _copyprop(name, source, object);
                    }
                  }
                }
              }

              return object;
            }
            function mixin(object) {
              object = object || {};

              for (var _len3 = arguments.length, sources = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
                sources[_key3 - 1] = arguments[_key3];
              }

              for (var _i2 = 0, _sources2 = sources; _i2 < _sources2.length; _i2++) {
                var source = _sources2[_i2];

                if (source) {
                  if (typeof source !== 'object') {
                    errorID(5403, source);
                    continue;
                  }

                  for (var name in source) {
                    _copyprop(name, source, object);
                  }
                }
              }

              return object;
            }
            function extend(cls, base) {

              for (var p in base) {
                if (base.hasOwnProperty(p)) {
                  cls[p] = base[p];
                }
              }

              cls.prototype = Object.create(base.prototype, {
                constructor: {
                  value: cls,
                  writable: true,
                  configurable: true
                }
              });
              return cls;
            }
            function getSuper(constructor) {
              var proto = constructor.prototype;
              var dunderProto = proto && Object.getPrototypeOf(proto);
              return dunderProto && dunderProto.constructor;
            }
            function isChildClassOf(subclass, superclass) {
              if (subclass && superclass) {
                if (typeof subclass !== 'function') {
                  return false;
                }

                if (typeof superclass !== 'function') {

                  return false;
                }

                if (subclass === superclass) {
                  return true;
                }

                for (;;) {
                  subclass = getSuper(subclass);

                  if (!subclass) {
                    return false;
                  }

                  if (subclass === superclass) {
                    return true;
                  }
                }
              }

              return false;
            }
            function clear(object) {
              for (var _i3 = 0, _Object$keys = Object.keys(object); _i3 < _Object$keys.length; _i3++) {
                var key = _Object$keys[_i3];
                delete object[key];
              }
            }

            function isTempClassId(id) {
              return typeof id !== 'string' || id.startsWith(tempCIDGenerator.prefix);
            }

            var _idToClass = createMap(true);
            var _nameToClass = createMap(true);

            function setup(tag, table) {
              return function (id, constructor) {
                if (constructor.prototype.hasOwnProperty(tag)) {
                  delete table[constructor.prototype[tag]];
                }

                value(constructor.prototype, tag, id);

                if (id) {
                  var registered = table[id];

                  if (registered && registered !== constructor) {
                    var err = "A Class already exists with the same " + tag + " : \"" + id + "\".";

                    error(err);
                  } else {
                    table[id] = constructor;
                  }
                }
              };
            }

            var _setClassId = setup('__cid__', _idToClass);
            var doSetClassName = setup('__classname__', _nameToClass);
            function setClassName(className, constructor) {
              doSetClassName(className, constructor);

              if (!constructor.prototype.hasOwnProperty(classIdTag)) {
                var id = className || tempCIDGenerator.getNewId();

                if (id) {
                  _setClassId(id, constructor);
                }
              }
            }
            function setClassAlias(target, alias) {
              var nameRegistry = _nameToClass[alias];
              var idRegistry = _idToClass[alias];
              var ok = true;

              if (nameRegistry && nameRegistry !== target) {
                error("\"" + alias + "\" has already been set as name or alias of another class.");
                ok = false;
              }

              if (idRegistry && idRegistry !== target) {
                error("\"" + alias + "\" has already been set as id or alias of another class.");
                ok = false;
              }

              if (ok) {
                var classAliases = target[aliasesTag];

                if (!classAliases) {
                  classAliases = [];
                  target[aliasesTag] = classAliases;
                }

                classAliases.push(alias);
                _nameToClass[alias] = target;
                _idToClass[alias] = target;
              }
            }
            function unregisterClass() {
              for (var _len4 = arguments.length, constructors = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
                constructors[_key4] = arguments[_key4];
              }

              for (var _i4 = 0, _constructors = constructors; _i4 < _constructors.length; _i4++) {
                var _constructor = _constructors[_i4];
                var p = _constructor.prototype;
                var classId = p[classIdTag];

                if (classId) {
                  delete _idToClass[classId];
                }

                var classname = p[classNameTag];

                if (classname) {
                  delete _nameToClass[classname];
                }

                var aliases = p[aliasesTag];

                if (aliases) {
                  for (var iAlias = 0; iAlias < aliases.length; ++iAlias) {
                    var alias = aliases[iAlias];
                    delete _nameToClass[alias];
                    delete _idToClass[alias];
                  }
                }
              }
            }
            function _getClassById(classId) {
              return _idToClass[classId];
            }
            function getClassByName(classname) {
              return _nameToClass[classname];
            }
            function _getClassId(obj, allowTempId) {
              allowTempId = typeof allowTempId !== 'undefined' ? allowTempId : true;
              var res;

              if (typeof obj === 'function' && obj.prototype.hasOwnProperty(classIdTag)) {
                res = obj.prototype[classIdTag];

                if (!allowTempId && ( EDITOR) && isTempClassId(res)) {
                  return '';
                }

                return res;
              }

              if (obj && obj.constructor) {
                var prototype = obj.constructor.prototype;

                if (prototype && prototype.hasOwnProperty(classIdTag)) {
                  res = obj[classIdTag];

                  if (!allowTempId && ( EDITOR) && isTempClassId(res)) {
                    return '';
                  }

                  return res;
                }
              }

              return '';
            }

            var Pool = function () {
              var _proto = Pool.prototype;

              _proto.get = function get() {
                return this._get();
              };

              function Pool(_0, _1) {
                this.count = void 0;
                this._pool = void 0;
                this._cleanup = void 0;
                var size = _1 === undefined ? _0 : _1;
                var cleanupFunc = _1 === undefined ? null : _0;
                this.count = 0;
                this._pool = new Array(size);
                this._cleanup = cleanupFunc;
              }

              _proto._get = function _get() {
                if (this.count > 0) {
                  --this.count;
                  var cache = this._pool[this.count];
                  this._pool[this.count] = null;
                  return cache;
                }

                return null;
              };

              _proto.put = function put(obj) {
                var pool = this._pool;

                if (this.count < pool.length) {
                  if (this._cleanup && this._cleanup(obj) === false) {
                    return;
                  }

                  pool[this.count] = obj;
                  ++this.count;
                }
              };

              _proto.resize = function resize(length) {
                if (length >= 0) {
                  this._pool.length = length;

                  if (this.count > length) {
                    this.count = length;
                  }
                }
              };

              return Pool;
            }();

            var array = jsarray;
            var js = {
              IDGenerator: IDGenerator,
              Pool: Pool,
              array: jsarray,
              isNumber: isNumber,
              isString: isString,
              isEmptyObject: isEmptyObject,
              getPropertyDescriptor: getPropertyDescriptor,
              addon: addon,
              mixin: mixin,
              extend: extend,
              getSuper: getSuper,
              isChildClassOf: isChildClassOf,
              clear: clear,
              value: value,
              getset: getset,
              get: get,
              set: set,
              unregisterClass: unregisterClass,
              getClassName: getClassName,
              setClassName: setClassName,
              setClassAlias: setClassAlias,
              getClassByName: getClassByName,

              get _registeredClassNames() {
                return _extends({}, _nameToClass);
              },

              set _registeredClassNames(value) {
                clear(_nameToClass);
                Object.assign(_nameToClass, value);
              },

              get _registeredClassIds() {
                return _extends({}, _idToClass);
              },

              set _registeredClassIds(value) {
                clear(_idToClass);
                Object.assign(_idToClass, value);
              },

              _getClassId: _getClassId,
              _setClassId: _setClassId,
              _getClassById: _getClassById,
              obsolete: obsolete,
              obsoletes: obsoletes,
              formatStr: formatStr,
              shiftArguments: shiftArguments,
              createMap: createMap
            };
            legacyCC.js = js;

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

            function BitMask(obj) {
              if ('__bitmask__' in obj) {
                return obj;
              }

              value(obj, '__bitmask__', null, true);
              var lastIndex = -1;
              var keys = Object.keys(obj);

              for (var i = 0; i < keys.length; i++) {
                var key = keys[i];
                var val = obj[key];

                if (val === -1) {
                  val = ++lastIndex;
                  obj[key] = val;
                } else if (typeof val === 'number') {
                  lastIndex = val;
                } else if (typeof val === 'string' && Number.isInteger(parseFloat(key))) {
                  continue;
                }

                var reverseKey = "" + val;

                if (key !== reverseKey) {

                  value(obj, reverseKey, key);
                }
              }

              return obj;
            }

            BitMask.isBitMask = function (BitMaskType) {
              return BitMaskType && BitMaskType.hasOwnProperty('__bitmask__');
            };

            BitMask.getList = function (BitMaskDef) {
              if (BitMaskDef.__bitmask__) {
                return BitMaskDef.__bitmask__;
              }

              var bitlist = BitMaskDef.__bitmask__ = [];

              for (var name in BitMaskDef) {
                var v = BitMaskDef[name];

                if (Number.isInteger(v)) {
                  bitlist.push({
                    name: name,
                    value: v
                  });
                }
              }

              bitlist.sort(function (a, b) {
                return a.value - b.value;
              });
              return bitlist;
            };
            legacyCC.BitMask = BitMask;

            function assertIsNonNullable(expr, message) {
              assertIsTrue(!(expr === null || expr === undefined), message);
            }
            function assertIsTrue(expr, message) {
              if ( !expr) {
                throw new Error("Assertion failed: " + (message !== null && message !== void 0 ? message : '<no-message>'));
              }
            }

            function Enum(obj) {
              if ('__enums__' in obj) {
                return obj;
              }

              value(obj, '__enums__', null, true);
              return Enum.update(obj);
            }

            Enum.update = function (obj) {
              var lastIndex = -1;
              var keys = Object.keys(obj);

              for (var i = 0; i < keys.length; i++) {
                var key = keys[i];
                var val = obj[key];

                if (val === -1) {
                  val = ++lastIndex;
                  obj[key] = val;
                } else if (typeof val === 'number') {
                  lastIndex = val;
                } else if (typeof val === 'string' && Number.isInteger(parseFloat(key))) {
                  continue;
                }

                var reverseKey = "" + val;

                if (key !== reverseKey) {

                  value(obj, reverseKey, key);
                }
              }

              if (Array.isArray(obj.__enums__)) {
                updateList(obj);
              }

              return obj;
            };

            (function (_Enum) {})(Enum || (Enum = exports('Enum', {})));

            Enum.isEnum = function (enumType) {
              return enumType && enumType.hasOwnProperty('__enums__');
            };

            function assertIsEnum(enumType) {
              assertIsTrue(enumType.hasOwnProperty('__enums__'));
            }

            Enum.getList = function (enumType) {
              assertIsEnum(enumType);

              if (enumType.__enums__) {
                return enumType.__enums__;
              }

              return updateList(enumType);
            };

            function updateList(enumType) {
              assertIsEnum(enumType);
              var enums = enumType.__enums__ || [];
              enums.length = 0;

              for (var name in enumType) {
                var v = enumType[name];

                if (Number.isInteger(v)) {
                  enums.push({
                    name: name,
                    value: v
                  });
                }
              }

              enums.sort(function (a, b) {
                return a.value - b.value;
              });
              enumType.__enums__ = enums;
              return enums;
            }

            function ccenum(enumType) {
              if (!('__enums__' in enumType)) {
                value(enumType, '__enums__', null, true);
              }
            }
            legacyCC.Enum = Enum;

            var ValueType = exports('ValueType', function () {
              function ValueType() {}

              var _proto = ValueType.prototype;

              _proto.clone = function clone() {
                errorID(100, getClassName(this) + ".clone");
                return this;
              };

              _proto.equals = function equals(other) {
                return false;
              };

              _proto.set = function set(other) {
                errorID(100, getClassName(this) + ".set");
              };

              _proto.toString = function toString() {
                return "" + {};
              };

              return ValueType;
            }());
            setClassName('cc.ValueType', ValueType);
            legacyCC.ValueType = ValueType;

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

            var BUILTIN_CLASSID_RE = /^(?:cc|dragonBones|sp|ccsg)\..+/;
            var BASE64_KEYS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
            var values = new Array(123);

            for (var i = 0; i < 123; ++i) {
              values[i] = 64;
            }

            for (var _i = 0; _i < 64; ++_i) {
              values[BASE64_KEYS.charCodeAt(_i)] = _i;
            }

            var BASE64_VALUES = values;
            function propertyDefine(ctor, sameNameGetSets, diffNameGetSets) {
              function define(np, propName, getter, setter) {
                var pd = Object.getOwnPropertyDescriptor(np, propName);

                if (pd) {
                  if (pd.get) {
                    np[getter] = pd.get;
                  }

                  if (pd.set && setter) {
                    np[setter] = pd.set;
                  }
                } else {
                  var getterFunc = np[getter];

                  {
                    getset(np, propName, getterFunc, np[setter]);
                  }
                }
              }

              var propName;
              var np = ctor.prototype;

              for (var _i2 = 0; _i2 < sameNameGetSets.length; _i2++) {
                propName = sameNameGetSets[_i2];
                var suffix = propName[0].toUpperCase() + propName.slice(1);
                define(np, propName, "get" + suffix, "set" + suffix);
              }

              for (propName in diffNameGetSets) {
                var gs = diffNameGetSets[propName];
                define(np, propName, gs[0], gs[1]);
              }
            }
            function pushToMap(map, key, value, pushFront) {
              var exists = map[key];

              if (exists) {
                if (Array.isArray(exists)) {
                  if (pushFront) {
                    exists.push(exists[0]);
                    exists[0] = value;
                  } else {
                    exists.push(value);
                  }
                } else {
                  map[key] = pushFront ? [value, exists] : [exists, value];
                }
              } else {
                map[key] = value;
              }
            }
            function contains$1(refNode, otherNode) {
              if (typeof refNode.contains === 'function') {
                return refNode.contains(otherNode);
              } else if (typeof refNode.compareDocumentPosition === 'function') {
                return !!(refNode.compareDocumentPosition(otherNode) & 16);
              } else {
                var node = otherNode.parentNode;

                if (node) {
                  do {
                    if (node === refNode) {
                      return true;
                    } else {
                      node = node.parentNode;
                    }
                  } while (node !== null);
                }

                return false;
              }
            }
            function isDomNode(obj) {
              if (typeof window === 'object' && typeof Node === 'function') {
                return obj instanceof Node;
              } else {
                return obj && typeof obj === 'object' && typeof obj.nodeType === 'number' && typeof obj.nodeName === 'string';
              }
            }
            function callInNextTick(callback, p1, p2) {
              if (callback) {
                setTimeout(function () {
                  callback(p1, p2);
                }, 0);
              }
            }
            function tryCatchFunctor_EDITOR(funcName) {
              return Function('target', "" + ('try {\n' + '  target.') + funcName + "();\n" + "}\n" + "catch (e) {\n" + "  cc._throw(e);\n" + "}");
            }
            function isPlainEmptyObj_DEV(obj) {
              if (!obj || obj.constructor !== Object) {
                return false;
              }

              return isEmptyObject(obj);
            }
            function clampf(value, min_inclusive, max_inclusive) {
              if (min_inclusive > max_inclusive) {
                var temp = min_inclusive;
                min_inclusive = max_inclusive;
                max_inclusive = temp;
              }

              return value < min_inclusive ? min_inclusive : value < max_inclusive ? value : max_inclusive;
            }
            function degreesToRadians(angle) {
              return angle * macro.RAD;
            }
            function radiansToDegrees(angle) {
              return angle * macro.DEG;
            }
            legacyCC.misc = {
              BUILTIN_CLASSID_RE: BUILTIN_CLASSID_RE,
              BASE64_VALUES: BASE64_VALUES,
              propertyDefine: propertyDefine,
              pushToMap: pushToMap,
              contains: contains$1,
              isDomNode: isDomNode,
              callInNextTick: callInNextTick,
              isPlainEmptyObj_DEV: isPlainEmptyObj_DEV,
              clampf: clampf,
              degreesToRadians: degreesToRadians,
              radiansToDegrees: radiansToDegrees
            };

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

            var DELIMETER = '$_$';
            function createAttrsSingle(owner, superAttrs) {
              var attrs = superAttrs ? Object.create(superAttrs) : {};
              value(owner, '__attrs__', attrs);
              return attrs;
            }
            function createAttrs(subclass) {
              if (typeof subclass !== 'function') {
                var instance = subclass;
                return createAttrsSingle(instance, getClassAttrs(instance.constructor));
              }

              var superClass;
              var chains = legacyCC.Class.getInheritanceChain(subclass);

              for (var i = chains.length - 1; i >= 0; i--) {
                var cls = chains[i];

                var attrs = cls.hasOwnProperty('__attrs__') && cls.__attrs__;

                if (!attrs) {
                  superClass = chains[i + 1];
                  createAttrsSingle(cls, superClass && superClass.__attrs__);
                }
              }

              superClass = chains[0];
              createAttrsSingle(subclass, superClass && superClass.__attrs__);
              return subclass.__attrs__;
            }
            function attr(constructor, propertyName) {
              var attrs = getClassAttrs(constructor);
              var prefix = propertyName + DELIMETER;
              var ret = {};

              for (var key in attrs) {
                if (key.startsWith(prefix)) {
                  ret[key.slice(prefix.length)] = attrs[key];
                }
              }

              return ret;
            }
            function getClassAttrs(constructor) {
              return constructor.hasOwnProperty('__attrs__') && constructor.__attrs__ || createAttrs(constructor);
            }
            function setClassAttr(ctor, propName, key, value) {
              getClassAttrs(ctor)[propName + DELIMETER + key] = value;
            }
            var PrimitiveType = function () {
              function PrimitiveType(name, defaultValue) {
                this.name = void 0;
                this["default"] = void 0;
                this.name = name;
                this["default"] = defaultValue;
              }

              var _proto = PrimitiveType.prototype;

              _proto.toString = function toString() {
                return this.name;
              };

              return PrimitiveType;
            }();
            var CCInteger = exports('CCInteger', new PrimitiveType('Integer', 0));
            legacyCC.Integer = CCInteger;
            legacyCC.CCInteger = CCInteger;
            var CCFloat = exports('CCFloat', new PrimitiveType('Float', 0.0));
            legacyCC.Float = CCFloat;
            legacyCC.CCFloat = CCFloat;

            var CCBoolean = exports('CCBoolean', new PrimitiveType('Boolean', false));
            legacyCC.Boolean = CCBoolean;
            legacyCC.CCBoolean = CCBoolean;
            var CCString = exports('CCString', new PrimitiveType('String', ''));
            legacyCC.String = CCString;
            legacyCC.CCString = CCString;
            function getTypeChecker_ET(type, attributeName) {
              return function (constructor, mainPropertyName) {
                var propInfo = "\"" + getClassName(constructor) + "." + mainPropertyName + "\"";
                var mainPropAttrs = attr(constructor, mainPropertyName);
                var mainPropAttrsType = mainPropAttrs.type;

                if (mainPropAttrsType === CCInteger || mainPropAttrsType === CCFloat) {
                  mainPropAttrsType = 'Number';
                } else if (mainPropAttrsType === CCString || mainPropAttrsType === CCBoolean) {
                  mainPropAttrsType = "" + mainPropAttrsType;
                }

                if (mainPropAttrsType !== type) {
                  warnID(3604, propInfo);
                  return;
                }

                if (!mainPropAttrs.hasOwnProperty('default')) {
                  return;
                }

                var defaultVal = mainPropAttrs["default"];

                if (typeof defaultVal === 'undefined') {
                  return;
                }

                var isContainer = Array.isArray(defaultVal) || isPlainEmptyObj_DEV(defaultVal);

                if (isContainer) {
                  return;
                }

                var defaultType = typeof defaultVal;
                var type_lowerCase = type.toLowerCase();

                if (defaultType === type_lowerCase) {
                  if (type_lowerCase === 'object') {
                    if (defaultVal && !(defaultVal instanceof mainPropAttrs.ctor)) {
                      warnID(3605, propInfo, getClassName(mainPropAttrs.ctor));
                    } else {
                      return;
                    }
                  } else if (type !== 'Number') {
                    warnID(3606, attributeName, propInfo, type);
                  }
                } else if (defaultType !== 'function') {
                  if (type === CCString["default"] && defaultVal == null) {
                    warnID(3607, propInfo);
                  } else {
                    warnID(3611, attributeName, propInfo, defaultType);
                  }
                } else {
                  return;
                }

                delete mainPropAttrs.type;
              };
            }
            function getObjTypeChecker_ET(typeCtor) {
              return function (classCtor, mainPropName) {
                getTypeChecker_ET('Object', 'type')(classCtor, mainPropName);
                var defaultDef = getClassAttrs(classCtor)[mainPropName + DELIMETER + "default"];
                var defaultVal = legacyCC.Class.getDefault(defaultDef);

                if (!Array.isArray(defaultVal) && isChildClassOf(typeCtor, legacyCC.ValueType)) {
                  var typename = getClassName(typeCtor);
                  var info = formatStr('No need to specify the "type" of "%s.%s" because %s is a child class of ValueType.', getClassName(classCtor), mainPropName, typename);

                  if (defaultDef) {
                    log(info);
                  } else {
                    warnID(3612, info, typename, getClassName(classCtor), mainPropName, typename);
                  }
                }
              };
            }

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

            var SerializableAttrs = {
              "default": {},
              serializable: {},
              editorOnly: {},
              formerlySerializedAs: {}
            };

            function parseNotify(val, propName, notify, properties) {
              if (val.get || val.set) {

                return;
              }

              if (val.hasOwnProperty('default')) {
                var newKey = "_N$" + propName;

                val.get = function () {
                  return this[newKey];
                };

                val.set = function (value) {
                  var oldValue = this[newKey];
                  this[newKey] = value;
                  notify.call(this, oldValue);
                };

                var newValue = {};
                properties[newKey] = newValue;

                for (var attr in SerializableAttrs) {
                  var v = SerializableAttrs[attr];

                  if (val.hasOwnProperty(attr)) {
                    newValue[attr] = val[attr];

                    if (!v.canUsedInGet) {
                      delete val[attr];
                    }
                  }
                }
              }
            }

            function parseType(val, type, className, propName) {

              if (Array.isArray(type)) {

                if (type.length > 0) {
                  val.type = type = type[0];
                } else {
                  return errorID(5508, className, propName);
                }
              }

              if (typeof type === 'function') {
                if (type === String) {
                  val.type = legacyCC.String;
                } else if (type === Boolean) {
                  val.type = legacyCC.Boolean;
                } else if (type === Number) {
                  val.type = legacyCC.Float;
                }
              }
            }

            function _wrapOptions(isGetset, _default, type) {
              var res = isGetset ? {
                _short: true
              } : {
                _short: true,
                "default": _default
              };

              if (type) {
                res.type = type;
              }

              return res;
            }

            function getFullFormOfProperty(options, isGetset) {
              var isLiteral = options && options.constructor === Object;

              if (!isLiteral) {
                if (Array.isArray(options) && options.length > 0) {
                  return _wrapOptions(isGetset, [], options);
                } else if (typeof options === 'function') {
                  var type = options;
                  return _wrapOptions(isGetset, isChildClassOf(type, legacyCC.ValueType) ? new type() : null, type);
                } else if (options instanceof PrimitiveType) {
                  return _wrapOptions(isGetset, options["default"]);
                } else {
                  return _wrapOptions(isGetset, options);
                }
              }

              return null;
            }
            function preprocessAttrs(properties, className, cls) {
              for (var propName in properties) {
                var val = properties[propName];
                var fullForm = getFullFormOfProperty(val, false);

                if (fullForm) {
                  val = properties[propName] = fullForm;
                }

                if (val) {

                  var notify = val.notify;

                  if (notify) {
                    {
                      parseNotify(val, propName, notify, properties);
                    }
                  }

                  if ('type' in val) {
                    parseType(val, val.type, className, propName);
                  }
                }
              }
            }

            var requiringFrames = [];
            function push(module, uuid, script, importMeta) {
              if (script === undefined) {
                script = uuid;
                uuid = '';
              }

              requiringFrames.push({
                uuid: uuid,
                script: script,
                module: module,
                exports: module.exports,
                beh: null,
                importMeta: importMeta
              });
            }
            function pop() {
              var frameInfo = requiringFrames.pop();
              var module = frameInfo.module;
              var exports = module.exports;

              if (exports === frameInfo.exports) {
                for (var anykey in exports) {
                  return;
                }

                module.exports = exports = frameInfo.cls;
              }
            }
            function peek() {
              return requiringFrames[requiringFrames.length - 1];
            }
            legacyCC._RF = {
              push: push,
              pop: pop,
              peek: peek
            };

            var DELIMETER$1 = DELIMETER;

            function pushUnique(array, item) {
              if (array.indexOf(item) < 0) {
                array.push(item);
              }
            }

            var deferredInitializer = {
              datas: null,
              push: function push(data) {
                if (this.datas) {
                  this.datas.push(data);
                } else {
                  this.datas = [data];
                  var self = this;
                  setTimeout(function () {
                    self.init();
                  }, 0);
                }
              },
              init: function init() {
                var datas = this.datas;

                if (datas) {
                  for (var i = 0; i < datas.length; ++i) {
                    var data = datas[i];
                    var cls = data.cls;
                    var properties = data.props;

                    if (typeof properties === 'function') {
                      properties = properties();
                    }

                    var name = getClassName(cls);

                    if (properties) {
                      declareProperties(cls, name, properties, cls.$super, data.mixins);
                    } else {
                      errorID(3633, name);
                    }
                  }

                  this.datas = null;
                }
              }
            };

            function appendProp(cls, name) {

              pushUnique(cls.__props__, name);
            }

            function defineProp(cls, className, propName, val) {

              appendProp(cls, propName);
              parseAttributes(cls, val, className, propName);
            }

            function defineGetSet(cls, name, propName, val) {
              var getter = val.get;
              var setter = 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 mixinWithInherited(dest, src, filter) {
              for (var prop in src) {
                if (!dest.hasOwnProperty(prop) && (!filter || filter(prop))) {
                  Object.defineProperty(dest, prop, getPropertyDescriptor(src, prop));
                }
              }
            }

            function doDefine(className, baseClass, mixins, options) {
              var ctor = options.ctor;

              var ctors = [ctor];
              var fireClass = ctor;
              value(fireClass, '__ctors__', ctors.length > 0 ? ctors : null, true);
              var prototype = fireClass.prototype;

              if (baseClass) {
                fireClass.$super = baseClass;
              }

              if (mixins) {
                for (var m = mixins.length - 1; m >= 0; m--) {
                  var mixin = mixins[m];
                  mixinWithInherited(prototype, mixin.prototype);

                  if (CCClass._isCCClass(mixin)) {
                    mixinWithInherited(getClassAttrs(fireClass), getClassAttrs(mixin));
                  }
                }

                prototype.constructor = fireClass;
              }

              setClassName(className, fireClass);
              return fireClass;
            }

            function define(className, baseClass, mixins, options) {
              var Component = legacyCC.Component;
              var frame = peek();

              if (frame && isChildClassOf(baseClass, Component)) {
                if (isChildClassOf(frame.cls, Component)) {
                  errorID(3615);
                  return null;
                }

                className = className || frame.script;
              }

              var cls = doDefine(className, baseClass, mixins, options);

              if (frame) {
                if (isChildClassOf(baseClass, Component)) {
                  var uuid = frame.uuid;

                  if (uuid) {
                    _setClassId(uuid, cls);
                  }

                  frame.cls = cls;
                } else if (!isChildClassOf(frame.cls, Component)) {
                  frame.cls = cls;
                }
              }

              return cls;
            }

            function getNewValueTypeCodeJit(value) {
              var clsName = getClassName(value);
              var type = value.constructor;
              var res = "new " + clsName + "(";

              for (var i = 0; i < type.__props__.length; i++) {
                var prop = type.__props__[i];
                var propVal = value[prop];

                res += propVal;

                if (i < type.__props__.length - 1) {
                  res += ',';
                }
              }

              return res + ")";
            }

            function escapeForJS(s) {
              return JSON.stringify(s).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
            }

            var IDENTIFIER_RE = /^[A-Za-z_$][0-9A-Za-z_$]*$/;

            function declareProperties(cls, className, properties, baseClass, mixins) {
              cls.__props__ = [];

              if (baseClass && baseClass.__props__) {
                cls.__props__ = baseClass.__props__.slice();
              }

              if (mixins) {
                for (var m = 0; m < mixins.length; ++m) {
                  var mixin = mixins[m];

                  if (mixin.__props__) {
                    cls.__props__ = cls.__props__.concat(mixin.__props__.filter(function (x) {
                      return cls.__props__.indexOf(x) < 0;
                    }));
                  }
                }
              }

              if (properties) {
                preprocessAttrs(properties, className);

                for (var propName in properties) {
                  var val = properties[propName];

                  if (!val.get && !val.set) {
                    defineProp(cls, className, propName, val);
                  } else {
                    defineGetSet(cls, className, propName, val);
                  }
                }
              }

              var attrs = getClassAttrs(cls);
              cls.__values__ = cls.__props__.filter(function (prop) {
                return attrs[prop + DELIMETER$1 + "serializable"] !== false;
              });
            }

            function CCClass(options) {
              var name = options.name;
              var base = options["extends"];
              var mixins = options.mixins;
              var cls = define(name, base, mixins, options);

              if (!name) {
                name = legacyCC.js.getClassName(cls);
              }

              cls._sealed = true;

              if (base) {
                base._sealed = false;
              }

              var properties = options.properties;

              if (typeof properties === 'function' || base && base.__props__ === null || mixins && mixins.some(function (x) {
                return x.__props__ === null;
              })) {
                {
                  deferredInitializer.push({
                    cls: cls,
                    props: properties,
                    mixins: mixins
                  });
                  cls.__props__ = cls.__values__ = null;
                }
              } else {
                declareProperties(cls, name, properties, base, options.mixins);
              }

              var editor = options.editor;

              if (editor) {
                if (isChildClassOf(base, legacyCC.Component)) {
                  legacyCC.Component._registerEditorProps(cls, editor);
                }
              }

              return cls;
            }

            CCClass._isCCClass = function isCCClass(constructor) {
              var _constructor$hasOwnPr;

              return constructor === null || constructor === void 0 ? void 0 : (_constructor$hasOwnPr = constructor.hasOwnProperty) === null || _constructor$hasOwnPr === void 0 ? void 0 : _constructor$hasOwnPr.call(constructor, '__ctors__');
            };

            CCClass.fastDefine = function (className, constructor, serializableFields) {
              setClassName(className, constructor);
              var props = constructor.__props__ = constructor.__values__ = Object.keys(serializableFields);
              var attrs = getClassAttrs(constructor);

              for (var i = 0; i < props.length; i++) {
                var key = props[i];
                attrs[key + DELIMETER$1 + "visible"] = false;
                attrs[key + DELIMETER$1 + "default"] = serializableFields[key];
              }
            };

            CCClass.Attr = attributeUtils;
            CCClass.attr = attr;

            function getInheritanceChain(constructor) {
              var chain = [];

              for (;;) {
                constructor = getSuper(constructor);

                if (!constructor) {
                  break;
                }

                if (constructor !== Object) {
                  chain.push(constructor);
                }
              }

              return chain;
            }

            CCClass.getInheritanceChain = getInheritanceChain;
            var PrimitiveTypes = {
              Integer: 'Number',
              Float: 'Number',
              Boolean: 'Boolean',
              String: 'String'
            };

            function parseAttributes(constructor, attributes, className, propertyName, usedInGetter) {
              var attrs = null;
              var propertyNamePrefix = '';

              function initAttrs() {
                propertyNamePrefix = propertyName + DELIMETER$1;
                return attrs = getClassAttrs(constructor);
              }

              if ('type' in attributes && typeof attributes.type === 'undefined') {
                warnID(3660, propertyName, className);
              }
              var type = attributes.type;

              if (type) {
                var primitiveType = PrimitiveTypes[type];

                if (primitiveType) {
                  (attrs || initAttrs())[propertyNamePrefix + "type"] = type;
                } else if (type === 'Object') ; else if (typeof type === 'object') {
                    if (Enum.isEnum(type)) {
                      (attrs || initAttrs())[propertyNamePrefix + "type"] = 'Enum';
                      attrs[propertyNamePrefix + "enumList"] = Enum.getList(type);
                    } else if (BitMask.isBitMask(type)) {
                      (attrs || initAttrs())[propertyNamePrefix + "type"] = 'BitMask';
                      attrs[propertyNamePrefix + "bitmaskList"] = BitMask.getList(type);
                    } else ;
                  } else if (typeof type === 'function') {
                    (attrs || initAttrs())[propertyNamePrefix + "type"] = 'Object';
                    attrs[propertyNamePrefix + "ctor"] = type;
                  } else ;
              }

              if ('default' in attributes) {
                (attrs || initAttrs())[propertyNamePrefix + "default"] = attributes["default"];
              }

              var parseSimpleAttribute = function parseSimpleAttribute(attributeName, expectType) {
                if (attributeName in attributes) {
                  var val = attributes[attributeName];

                  if (typeof val === expectType) {
                    (attrs || initAttrs())[propertyNamePrefix + attributeName] = val;
                  }
                }
              };

              if (attributes.editorOnly) {
                {
                  (attrs || initAttrs())[propertyNamePrefix + "editorOnly"] = true;
                }
              }

              if (attributes.__noImplicit) {
                var _attributes$serializa;

                (attrs || initAttrs())[propertyNamePrefix + "serializable"] = (_attributes$serializa = attributes.serializable) !== null && _attributes$serializa !== void 0 ? _attributes$serializa : false;
              } else if (attributes.serializable === false) {
                {
                  (attrs || initAttrs())[propertyNamePrefix + "serializable"] = false;
                }
              }

              parseSimpleAttribute('formerlySerializedAs', 'string');

              var range = attributes.range;

              if (range) {
                if (Array.isArray(range)) {
                  if (range.length >= 2) {
                    (attrs || initAttrs())[propertyNamePrefix + "min"] = range[0];
                    attrs[propertyNamePrefix + "max"] = range[1];

                    if (range.length > 2) {
                      attrs[propertyNamePrefix + "step"] = range[2];
                    }
                  }
                }
              }

              parseSimpleAttribute('min', 'number');
              parseSimpleAttribute('max', 'number');
              parseSimpleAttribute('step', 'number');
            }

            CCClass.isArray = function (defaultVal) {
              defaultVal = getDefault(defaultVal);
              return Array.isArray(defaultVal);
            };

            CCClass.getDefault = getDefault;
            CCClass.escapeForJS = escapeForJS;
            CCClass.IDENTIFIER_RE = IDENTIFIER_RE;
            CCClass.getNewValueTypeCode =  getNewValueTypeCodeJit;
            legacyCC.Class = CCClass;

            var _d2r = Math.PI / 180.0;

            var _r2d = 180.0 / Math.PI;

            var EPSILON = exports('EPSILON', 0.000001);
            function equals(a, b) {
              return Math.abs(a - b) <= EPSILON * Math.max(1.0, Math.abs(a), Math.abs(b));
            }
            function approx(a, b, maxDiff) {
              maxDiff = maxDiff || EPSILON;
              return Math.abs(a - b) <= maxDiff;
            }
            function clamp(val, min, max) {
              if (min > max) {
                var temp = min;
                min = max;
                max = temp;
              }

              return val < min ? min : val > max ? max : val;
            }
            function clamp01(val) {
              return val < 0 ? 0 : val > 1 ? 1 : val;
            }
            function lerp(from, to, ratio) {
              return from + (to - from) * ratio;
            }
            function toRadian(a) {
              return a * _d2r;
            }
            function toDegree(a) {
              return a * _r2d;
            }
            var random = exports('random', Math.random);
            function randomRange(min, max) {
              return Math.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$1(val) {
              --val;
              val = val >> 1 | val;
              val = val >> 2 | val;
              val = val >> 4 | val;
              val = val >> 8 | val;
              val = val >> 16 | val;
              ++val;
              return val;
            }
            function repeat(t, length) {
              return t - Math.floor(t / length) * length;
            }
            function pingPong(t, length) {
              t = repeat(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;
              }
            }

            var toFloat = 1 / 255;
            var Color = exports('Color', function (_ValueType) {
              _inheritsLoose(Color, _ValueType);

              Color.clone = function clone(a) {
                var out = new Color();

                if (a._val) {
                  out._val = a._val;
                } else {
                  out._val = (a.a << 24 >>> 0) + (a.b << 16) + (a.g << 8) + a.r;
                }

                return out;
              };

              Color.copy = function copy(out, a) {
                out.r = a.r;
                out.g = a.g;
                out.b = a.b;
                out.a = a.a;
                return out;
              };

              Color.set = function set(out, r, g, b, a) {
                out.r = r;
                out.g = g;
                out.b = b;
                out.a = a;
                return out;
              };

              Color.fromHEX = function fromHEX(out, hexString) {
                hexString = hexString.indexOf('#') === 0 ? hexString.substring(1) : hexString;
                out.r = parseInt(hexString.substr(0, 2), 16) || 0;
                out.g = parseInt(hexString.substr(2, 2), 16) || 0;
                out.b = parseInt(hexString.substr(4, 2), 16) || 0;
                out.a = parseInt(hexString.substr(6, 2), 16) || 255;
                out._val = (out.a << 24 >>> 0) + (out.b << 16) + (out.g << 8) + out.r;
                return out;
              };

              Color.add = function add(out, a, b) {
                out.r = a.r + b.r;
                out.g = a.g + b.g;
                out.b = a.b + b.b;
                out.a = a.a + b.a;
                return out;
              };

              Color.subtract = function subtract(out, a, b) {
                out.r = a.r - b.r;
                out.g = a.g - b.g;
                out.b = a.b - b.b;
                out.a = a.a - b.a;
                return out;
              };

              Color.multiply = function multiply(out, a, b) {
                out.r = a.r * b.r;
                out.g = a.g * b.g;
                out.b = a.b * b.b;
                out.a = a.a * b.a;
                return out;
              };

              Color.divide = function divide(out, a, b) {
                out.r = a.r / b.r;
                out.g = a.g / b.g;
                out.b = a.b / b.b;
                out.a = a.a / b.a;
                return out;
              };

              Color.scale = function scale(out, a, b) {
                out.r = a.r * b;
                out.g = a.g * b;
                out.b = a.b * b;
                out.a = a.a * b;
                return out;
              };

              Color.lerp = function lerp(out, from, to, ratio) {
                var r = from.r;
                var g = from.g;
                var b = from.b;
                var a = from.a;
                r += (to.r - r) * ratio;
                g += (to.g - g) * ratio;
                b += (to.b - b) * ratio;
                a += (to.a - a) * ratio;
                out._val = Math.floor((a << 24 >>> 0) + (b << 16) + (g << 8) + r);
                return out;
              };

              Color.toArray = function toArray(out, a, ofs) {
                if (ofs === void 0) {
                  ofs = 0;
                }

                var scale = a instanceof Color || a.a > 1 ? 1 / 255 : 1;
                out[ofs + 0] = a.r * scale;
                out[ofs + 1] = a.g * scale;
                out[ofs + 2] = a.b * scale;
                out[ofs + 3] = a.a * scale;
                return out;
              };

              Color.fromArray = function fromArray(arr, out, ofs) {
                if (ofs === void 0) {
                  ofs = 0;
                }

                out.r = arr[ofs + 0] * 255;
                out.g = arr[ofs + 1] * 255;
                out.b = arr[ofs + 2] * 255;
                out.a = arr[ofs + 3] * 255;
                return out;
              };

              Color.strictEquals = function strictEquals(a, b) {
                return a.r === b.r && a.g === b.g && a.b === b.b && a.a === b.a;
              };

              Color.equals = function equals(a, b, epsilon) {
                if (epsilon === void 0) {
                  epsilon = EPSILON;
                }

                return Math.abs(a.r - b.r) <= epsilon * Math.max(1.0, Math.abs(a.r), Math.abs(b.r)) && Math.abs(a.g - b.g) <= epsilon * Math.max(1.0, Math.abs(a.g), Math.abs(b.g)) && Math.abs(a.b - b.b) <= epsilon * Math.max(1.0, Math.abs(a.b), Math.abs(b.b)) && Math.abs(a.a - b.a) <= epsilon * Math.max(1.0, Math.abs(a.a), Math.abs(b.a));
              };

              Color.hex = function hex(a) {
                return (a.r * 255 << 24 | a.g * 255 << 16 | a.b * 255 << 8 | a.a * 255) >>> 0;
              };

              function Color(r, g, b, a) {
                var _this;

                _this = _ValueType.call(this) || this;
                _this._val = 0;

                if (typeof r === 'string') {
                  _this.fromHEX(r);
                } else if (g !== undefined) {
                  _this.set(r, g, b, a);
                } else {
                  _this.set(r);
                }

                return _this;
              }

              var _proto = Color.prototype;

              _proto.clone = function clone() {
                var ret = new Color();
                ret._val = this._val;
                return ret;
              };

              _proto.equals = function equals(other) {
                return other && this._val === other._val;
              };

              _proto.lerp = function lerp(to, ratio) {
                var r = this.r;
                var g = this.g;
                var b = this.b;
                var a = this.a;
                r += (to.r - r) * ratio;
                g += (to.g - g) * ratio;
                b += (to.b - b) * ratio;
                a += (to.a - a) * ratio;
                this._val = Math.floor((a << 24 >>> 0) + (b << 16) + (g << 8) + r);
                return this;
              };

              _proto.toString = function toString() {
                return "rgba(" + this.r.toFixed() + ", " + this.g.toFixed() + ", " + this.b.toFixed() + ", " + this.a.toFixed() + ")";
              };

              _proto.toCSS = function toCSS(opt) {
                if (opt === void 0) {
                  opt = 'rgba';
                }

                if (opt === 'rgba') {
                  return "rgba(" + this.r + "," + this.g + "," + this.b + "," + (this.a * toFloat).toFixed(2) + ")";
                } else if (opt === 'rgb') {
                  return "rgb(" + this.r + "," + this.g + "," + this.b + ")";
                } else {
                  return "#" + this.toHEX(opt);
                }
              };

              _proto.fromHEX = function fromHEX(hexString) {
                hexString = hexString.indexOf('#') === 0 ? hexString.substring(1) : hexString;
                var r = parseInt(hexString.substr(0, 2), 16) || 0;
                var g = parseInt(hexString.substr(2, 2), 16) || 0;
                var b = parseInt(hexString.substr(4, 2), 16) || 0;
                var a = parseInt(hexString.substr(6, 2), 16) || 255;
                this._val = (a << 24 >>> 0) + (b << 16) + (g << 8) + (r | 0);
                return this;
              };

              _proto.toHEX = function toHEX(fmt) {
                if (fmt === void 0) {
                  fmt = '#rrggbb';
                }

                var prefix = '0';
                var hex = [(this.r < 16 ? prefix : '') + this.r.toString(16), (this.g < 16 ? prefix : '') + this.g.toString(16), (this.b < 16 ? prefix : '') + this.b.toString(16)];

                if (fmt === '#rgb') {
                  hex[0] = hex[0][0];
                  hex[1] = hex[1][0];
                  hex[2] = hex[2][0];
                } else if (fmt === '#rrggbbaa') {
                  hex.push((this.a < 16 ? prefix : '') + this.a.toString(16));
                }

                return hex.join('');
              };

              _proto.toRGBValue = function toRGBValue() {
                return this._val & 0x00ffffff;
              };

              _proto.fromHSV = function fromHSV(h, s, v) {
                var r = 0;
                var g = 0;
                var b = 0;

                if (s === 0) {
                  r = g = b = v;
                } else if (v === 0) {
                  r = g = b = 0;
                } else {
                  if (h === 1) {
                    h = 0;
                  }

                  h *= 6;
                  var i = Math.floor(h);
                  var f = h - i;
                  var p = v * (1 - s);
                  var q = v * (1 - s * f);
                  var t = v * (1 - s * (1 - f));

                  switch (i) {
                    case 0:
                      r = v;
                      g = t;
                      b = p;
                      break;

                    case 1:
                      r = q;
                      g = v;
                      b = p;
                      break;

                    case 2:
                      r = p;
                      g = v;
                      b = t;
                      break;

                    case 3:
                      r = p;
                      g = q;
                      b = v;
                      break;

                    case 4:
                      r = t;
                      g = p;
                      b = v;
                      break;

                    case 5:
                      r = v;
                      g = p;
                      b = q;
                      break;
                  }
                }

                r *= 255;
                g *= 255;
                b *= 255;
                this._val = (this.a << 24 >>> 0) + (b << 16) + (g << 8) + (r | 0);
                return this;
              };

              _proto.toHSV = function toHSV() {
                var r = this.r * toFloat;
                var g = this.g * toFloat;
                var b = this.b * toFloat;
                var hsv = {
                  h: 0,
                  s: 0,
                  v: 0
                };
                var max = Math.max(r, g, b);
                var min = Math.min(r, g, b);
                var delta = 0;
                hsv.v = max;
                hsv.s = max ? (max - min) / max : 0;

                if (!hsv.s) {
                  hsv.h = 0;
                } else {
                  delta = max - min;

                  if (r === max) {
                    hsv.h = (g - b) / delta;
                  } else if (g === max) {
                    hsv.h = 2 + (b - r) / delta;
                  } else {
                    hsv.h = 4 + (r - g) / delta;
                  }

                  hsv.h /= 6;

                  if (hsv.h < 0) {
                    hsv.h += 1.0;
                  }
                }

                return hsv;
              };

              _proto.set = function set(r, g, b, a) {
                if (typeof r === 'object') {
                  if (r._val != null) {
                    this._val = r._val;
                  } else {
                    g = r.g || 0;
                    b = r.b || 0;
                    a = typeof r.a === 'number' ? r.a : 255;
                    r = r.r || 0;
                    this._val = (a << 24 >>> 0) + (b << 16) + (g << 8) + (r | 0);
                  }
                } else {
                  r = r || 0;
                  g = g || 0;
                  b = b || 0;
                  a = typeof a === 'number' ? a : 255;
                  this._val = (a << 24 >>> 0) + (b << 16) + (g << 8) + (r | 0);
                }

                return this;
              };

              _proto.multiply = function multiply(other) {
                var r = (this._val & 0x000000ff) * other.r >> 8;
                var g = (this._val & 0x0000ff00) * other.g >> 8;
                var b = (this._val & 0x00ff0000) * other.b >> 8;
                var a = ((this._val & 0xff000000) >>> 8) * other.a;
                this._val = a & 0xff000000 | b & 0x00ff0000 | g & 0x0000ff00 | r & 0x000000ff;
                return this;
              };

              _proto._set_r_unsafe = function _set_r_unsafe(red) {
                this._val = (this._val & 0xffffff00 | red) >>> 0;
                return this;
              };

              _proto._set_g_unsafe = function _set_g_unsafe(green) {
                this._val = (this._val & 0xffff00ff | green << 8) >>> 0;
                return this;
              };

              _proto._set_b_unsafe = function _set_b_unsafe(blue) {
                this._val = (this._val & 0xff00ffff | blue << 16) >>> 0;
                return this;
              };

              _proto._set_a_unsafe = function _set_a_unsafe(alpha) {
                this._val = (this._val & 0x00ffffff | alpha << 24) >>> 0;
                return this;
              };

              _createClass(Color, [{
                key: "r",
                get: function get() {
                  return this._val & 0x000000ff;
                },
                set: function set(red) {
                  red = ~~clamp(red, 0, 255);
                  this._val = (this._val & 0xffffff00 | red) >>> 0;
                }
              }, {
                key: "g",
                get: function get() {
                  return (this._val & 0x0000ff00) >> 8;
                },
                set: function set(green) {
                  green = ~~clamp(green, 0, 255);
                  this._val = (this._val & 0xffff00ff | green << 8) >>> 0;
                }
              }, {
                key: "b",
                get: function get() {
                  return (this._val & 0x00ff0000) >> 16;
                },
                set: function set(blue) {
                  blue = ~~clamp(blue, 0, 255);
                  this._val = (this._val & 0xff00ffff | blue << 16) >>> 0;
                }
              }, {
                key: "a",
                get: function get() {
                  return (this._val & 0xff000000) >>> 24;
                },
                set: function set(alpha) {
                  alpha = ~~clamp(alpha, 0, 255);
                  this._val = (this._val & 0x00ffffff | alpha << 24) >>> 0;
                }
              }, {
                key: "x",
                get: function get() {
                  return this.r * toFloat;
                },
                set: function set(value) {
                  this.r = value * 255;
                }
              }, {
                key: "y",
                get: function get() {
                  return this.g * toFloat;
                },
                set: function set(value) {
                  this.g = value * 255;
                }
              }, {
                key: "z",
                get: function get() {
                  return this.b * toFloat;
                },
                set: function set(value) {
                  this.b = value * 255;
                }
              }, {
                key: "w",
                get: function get() {
                  return this.a * toFloat;
                },
                set: function set(value) {
                  this.a = value * 255;
                }
              }]);

              return Color;
            }(ValueType));
            Color.WHITE = Object.freeze(new Color(255, 255, 255, 255));
            Color.GRAY = Object.freeze(new Color(127, 127, 127, 255));
            Color.BLACK = Object.freeze(new Color(0, 0, 0, 255));
            Color.TRANSPARENT = Object.freeze(new Color(0, 0, 0, 0));
            Color.RED = Object.freeze(new Color(255, 0, 0, 255));
            Color.GREEN = Object.freeze(new Color(0, 255, 0, 255));
            Color.BLUE = Object.freeze(new Color(0, 0, 255, 255));
            Color.CYAN = Object.freeze(new Color(0, 255, 255, 255));
            Color.MAGENTA = Object.freeze(new Color(255, 0, 255, 255));
            Color.YELLOW = Object.freeze(new Color(255, 255, 0, 255));
            CCClass.fastDefine('cc.Color', Color, {
              r: 0,
              g: 0,
              b: 0,
              a: 255
            });
            legacyCC.Color = Color;
            function color(r, g, b, a) {
              return new Color(r, g, b, a);
            }
            legacyCC.color = color;

            var Vec3 = exports('Vec3', function (_ValueType) {
              _inheritsLoose(Vec3, _ValueType);

              Vec3.zero = function zero(out) {
                out.x = 0;
                out.y = 0;
                out.z = 0;
                return out;
              };

              Vec3.clone = function clone(a) {
                return new Vec3(a.x, a.y, a.z);
              };

              Vec3.copy = function copy(out, a) {
                out.x = a.x;
                out.y = a.y;
                out.z = a.z;
                return out;
              };

              Vec3.set = function set(out, x, y, z) {
                out.x = x;
                out.y = y;
                out.z = z;
                return out;
              };

              Vec3.add = function add(out, a, b) {
                out.x = a.x + b.x;
                out.y = a.y + b.y;
                out.z = a.z + b.z;
                return out;
              };

              Vec3.subtract = function subtract(out, a, b) {
                out.x = a.x - b.x;
                out.y = a.y - b.y;
                out.z = a.z - b.z;
                return out;
              };

              Vec3.multiply = function multiply(out, a, b) {
                out.x = a.x * b.x;
                out.y = a.y * b.y;
                out.z = a.z * b.z;
                return out;
              };

              Vec3.divide = function divide(out, a, b) {
                out.x = a.x / b.x;
                out.y = a.y / b.y;
                out.z = a.z / b.z;
                return out;
              };

              Vec3.ceil = function ceil(out, a) {
                out.x = Math.ceil(a.x);
                out.y = Math.ceil(a.y);
                out.z = Math.ceil(a.z);
                return out;
              };

              Vec3.floor = function floor(out, a) {
                out.x = Math.floor(a.x);
                out.y = Math.floor(a.y);
                out.z = Math.floor(a.z);
                return out;
              };

              Vec3.min = function min(out, a, b) {
                out.x = Math.min(a.x, b.x);
                out.y = Math.min(a.y, b.y);
                out.z = Math.min(a.z, b.z);
                return out;
              };

              Vec3.max = function max(out, a, b) {
                out.x = Math.max(a.x, b.x);
                out.y = Math.max(a.y, b.y);
                out.z = Math.max(a.z, b.z);
                return out;
              };

              Vec3.round = function round(out, a) {
                out.x = Math.round(a.x);
                out.y = Math.round(a.y);
                out.z = Math.round(a.z);
                return out;
              };

              Vec3.multiplyScalar = function multiplyScalar(out, a, b) {
                out.x = a.x * b;
                out.y = a.y * b;
                out.z = a.z * b;
                return out;
              };

              Vec3.scaleAndAdd = function scaleAndAdd(out, a, b, scale) {
                out.x = a.x + b.x * scale;
                out.y = a.y + b.y * scale;
                out.z = a.z + b.z * scale;
                return out;
              };

              Vec3.distance = function distance(a, b) {
                var x = b.x - a.x;
                var y = b.y - a.y;
                var z = b.z - a.z;
                return Math.sqrt(x * x + y * y + z * z);
              };

              Vec3.squaredDistance = function squaredDistance(a, b) {
                var x = b.x - a.x;
                var y = b.y - a.y;
                var z = b.z - a.z;
                return x * x + y * y + z * z;
              };

              Vec3.len = function len(a) {
                var x = a.x;
                var y = a.y;
                var z = a.z;
                return Math.sqrt(x * x + y * y + z * z);
              };

              Vec3.lengthSqr = function lengthSqr(a) {
                var x = a.x;
                var y = a.y;
                var z = a.z;
                return x * x + y * y + z * z;
              };

              Vec3.negate = function negate(out, a) {
                out.x = -a.x;
                out.y = -a.y;
                out.z = -a.z;
                return out;
              };

              Vec3.invert = function invert(out, a) {
                out.x = 1.0 / a.x;
                out.y = 1.0 / a.y;
                out.z = 1.0 / a.z;
                return out;
              };

              Vec3.invertSafe = function invertSafe(out, a) {
                var x = a.x;
                var y = a.y;
                var z = a.z;

                if (Math.abs(x) < EPSILON) {
                  out.x = 0;
                } else {
                  out.x = 1.0 / x;
                }

                if (Math.abs(y) < EPSILON) {
                  out.y = 0;
                } else {
                  out.y = 1.0 / y;
                }

                if (Math.abs(z) < EPSILON) {
                  out.z = 0;
                } else {
                  out.z = 1.0 / z;
                }

                return out;
              };

              Vec3.normalize = function normalize(out, a) {
                var x = a.x;
                var y = a.y;
                var z = a.z;
                var len = x * x + y * y + z * z;

                if (len > 0) {
                  len = 1 / Math.sqrt(len);
                  out.x = x * len;
                  out.y = y * len;
                  out.z = z * len;
                }

                return out;
              };

              Vec3.dot = function dot(a, b) {
                return a.x * b.x + a.y * b.y + a.z * b.z;
              };

              Vec3.cross = function cross(out, a, b) {
                var ax = a.x,
                    ay = a.y,
                    az = a.z;
                var bx = b.x,
                    by = b.y,
                    bz = b.z;
                out.x = ay * bz - az * by;
                out.y = az * bx - ax * bz;
                out.z = ax * by - ay * bx;
                return out;
              };

              Vec3.lerp = function lerp(out, a, b, t) {
                out.x = a.x + t * (b.x - a.x);
                out.y = a.y + t * (b.y - a.y);
                out.z = a.z + t * (b.z - a.z);
                return out;
              };

              Vec3.random = function random$1(out, scale) {
                scale = scale || 1.0;
                var phi = random() * 2.0 * Math.PI;
                var cosTheta = random() * 2 - 1;
                var sinTheta = Math.sqrt(1 - cosTheta * cosTheta);
                out.x = sinTheta * Math.cos(phi) * scale;
                out.y = sinTheta * Math.sin(phi) * scale;
                out.z = cosTheta * scale;
                return out;
              };

              Vec3.transformMat4 = function transformMat4(out, a, m) {
                var x = a.x;
                var y = a.y;
                var z = a.z;
                var rhw = m.m03 * x + m.m07 * y + m.m11 * z + m.m15;
                rhw = rhw ? Math.abs(1 / rhw) : 1;
                out.x = (m.m00 * x + m.m04 * y + m.m08 * z + m.m12) * rhw;
                out.y = (m.m01 * x + m.m05 * y + m.m09 * z + m.m13) * rhw;
                out.z = (m.m02 * x + m.m06 * y + m.m10 * z + m.m14) * rhw;
                return out;
              };

              Vec3.transformMat4Normal = function transformMat4Normal(out, a, m) {
                var x = a.x;
                var y = a.y;
                var z = a.z;
                var rhw = m.m03 * x + m.m07 * y + m.m11 * z;
                rhw = rhw ? Math.abs(1 / rhw) : 1;
                out.x = (m.m00 * x + m.m04 * y + m.m08 * z) * rhw;
                out.y = (m.m01 * x + m.m05 * y + m.m09 * z) * rhw;
                out.z = (m.m02 * x + m.m06 * y + m.m10 * z) * rhw;
                return out;
              };

              Vec3.transformMat3 = function transformMat3(out, a, m) {
                var x = a.x;
                var y = a.y;
                var z = a.z;
                out.x = x * m.m00 + y * m.m03 + z * m.m06;
                out.y = x * m.m01 + y * m.m04 + z * m.m07;
                out.z = x * m.m02 + y * m.m05 + z * m.m08;
                return out;
              };

              Vec3.transformAffine = function transformAffine(out, v, m) {
                var x = v.x;
                var y = v.y;
                var z = v.z;
                out.x = m.m00 * x + m.m04 * y + m.m08 * z + m.m12;
                out.y = m.m01 * x + m.m05 * y + m.m09 * z + m.m13;
                out.x = m.m02 * x + m.m06 * y + m.m10 * z + m.m14;
                return out;
              };

              Vec3.transformQuat = function transformQuat(out, a, q) {
                var ix = q.w * a.x + q.y * a.z - q.z * a.y;
                var iy = q.w * a.y + q.z * a.x - q.x * a.z;
                var iz = q.w * a.z + q.x * a.y - q.y * a.x;
                var iw = -q.x * a.x - q.y * a.y - q.z * a.z;
                out.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;
                out.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;
                out.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;
                return out;
              };

              Vec3.transformRTS = function transformRTS(out, a, r, t, s) {
                var x = a.x * s.x;
                var y = a.y * s.y;
                var z = a.z * s.z;
                var ix = r.w * x + r.y * z - r.z * y;
                var iy = r.w * y + r.z * x - r.x * z;
                var iz = r.w * z + r.x * y - r.y * x;
                var iw = -r.x * x - r.y * y - r.z * z;
                out.x = ix * r.w + iw * -r.x + iy * -r.z - iz * -r.y + t.x;
                out.y = iy * r.w + iw * -r.y + iz * -r.x - ix * -r.z + t.y;
                out.z = iz * r.w + iw * -r.z + ix * -r.y - iy * -r.x + t.z;
                return out;
              };

              Vec3.transformInverseRTS = function transformInverseRTS(out, a, r, t, s) {
                var x = a.x - t.x;
                var y = a.y - t.y;
                var z = a.z - t.z;
                var ix = r.w * x - r.y * z + r.z * y;
                var iy = r.w * y - r.z * x + r.x * z;
                var iz = r.w * z - r.x * y + r.y * x;
                var iw = r.x * x + r.y * y + r.z * z;
                out.x = (ix * r.w + iw * r.x + iy * r.z - iz * r.y) / s.x;
                out.y = (iy * r.w + iw * r.y + iz * r.x - ix * r.z) / s.y;
                out.z = (iz * r.w + iw * r.z + ix * r.y - iy * r.x) / s.z;
                return out;
              };

              Vec3.rotateX = function rotateX(out, v, o, a) {
                var x = v.x - o.x;
                var y = v.y - o.y;
                var z = v.z - o.z;
                var cos = Math.cos(a);
                var sin = Math.sin(a);
                var rx = x;
                var ry = y * cos - z * sin;
                var rz = y * sin + z * cos;
                out.x = rx + o.x;
                out.y = ry + o.y;
                out.z = rz + o.z;
                return out;
              };

              Vec3.rotateY = function rotateY(out, v, o, a) {
                var x = v.x - o.x;
                var y = v.y - o.y;
                var z = v.z - o.z;
                var cos = Math.cos(a);
                var sin = Math.sin(a);
                var rx = z * sin + x * cos;
                var ry = y;
                var rz = z * cos - x * sin;
                out.x = rx + o.x;
                out.y = ry + o.y;
                out.z = rz + o.z;
                return out;
              };

              Vec3.rotateZ = function rotateZ(out, v, o, a) {
                var x = v.x - o.x;
                var y = v.y - o.y;
                var z = v.z - o.z;
                var cos = Math.cos(a);
                var sin = Math.sin(a);
                var rx = x * cos - y * sin;
                var ry = x * sin + y * cos;
                var rz = z;
                out.x = rx + o.x;
                out.y = ry + o.y;
                out.z = rz + o.z;
                return out;
              };

              Vec3.toArray = function toArray(out, v, ofs) {
                if (ofs === void 0) {
                  ofs = 0;
                }

                out[ofs + 0] = v.x;
                out[ofs + 1] = v.y;
                out[ofs + 2] = v.z;
                return out;
              };

              Vec3.fromArray = function fromArray(out, arr, ofs) {
                if (ofs === void 0) {
                  ofs = 0;
                }

                out.x = arr[ofs + 0];
                out.y = arr[ofs + 1];
                out.z = arr[ofs + 2];
                return out;
              };

              Vec3.strictEquals = function strictEquals(a, b) {
                return a.x === b.x && a.y === b.y && a.z === b.z;
              };

              Vec3.equals = function equals(a, b, epsilon) {
                if (epsilon === void 0) {
                  epsilon = EPSILON;
                }

                var a0 = a.x,
                    a1 = a.y,
                    a2 = a.z;
                var b0 = b.x,
                    b1 = b.y,
                    b2 = b.z;
                return Math.abs(a0 - b0) <= epsilon * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= epsilon * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= epsilon * Math.max(1.0, Math.abs(a2), Math.abs(b2));
              };

              Vec3.angle = function angle(a, b) {
                Vec3.normalize(v3_1, a);
                Vec3.normalize(v3_2, b);
                var cosine = Vec3.dot(v3_1, v3_2);

                if (cosine > 1.0) {
                  return 0;
                }

                if (cosine < -1.0) {
                  return Math.PI;
                }

                return Math.acos(cosine);
              };

              Vec3.projectOnPlane = function projectOnPlane(out, a, n) {
                return Vec3.subtract(out, a, Vec3.project(out, a, n));
              };

              Vec3.project = function project(out, a, b) {
                var sqrLen = Vec3.lengthSqr(b);

                if (sqrLen < 0.000001) {
                  return Vec3.set(out, 0, 0, 0);
                } else {
                  return Vec3.multiplyScalar(out, b, Vec3.dot(a, b) / sqrLen);
                }
              };

              function Vec3(x, y, z) {
                var _this;

                _this = _ValueType.call(this) || this;

                if (x && typeof x === 'object') {
                  _this.x = x.x;
                  _this.y = x.y;
                  _this.z = x.z;
                } else {
                  _this.x = x || 0;
                  _this.y = y || 0;
                  _this.z = z || 0;
                }

                return _this;
              }

              var _proto = Vec3.prototype;

              _proto.clone = function clone() {
                return new Vec3(this.x, this.y, this.z);
              };

              _proto.set = function set(x, y, z) {
                if (x && typeof x === 'object') {
                  this.x = x.x;
                  this.y = x.y;
                  this.z = x.z;
                } else {
                  this.x = x || 0;
                  this.y = y || 0;
                  this.z = z || 0;
                }

                return this;
              };

              _proto.equals = function equals(other, epsilon) {
                if (epsilon === void 0) {
                  epsilon = EPSILON;
                }

                return Math.abs(this.x - other.x) <= epsilon * Math.max(1.0, Math.abs(this.x), Math.abs(other.x)) && Math.abs(this.y - other.y) <= epsilon * Math.max(1.0, Math.abs(this.y), Math.abs(other.y)) && Math.abs(this.z - other.z) <= epsilon * Math.max(1.0, Math.abs(this.z), Math.abs(other.z));
              };

              _proto.equals3f = function equals3f(x, y, z, epsilon) {
                if (epsilon === void 0) {
                  epsilon = EPSILON;
                }

                return Math.abs(this.x - x) <= epsilon * Math.max(1.0, Math.abs(this.x), Math.abs(x)) && Math.abs(this.y - y) <= epsilon * Math.max(1.0, Math.abs(this.y), Math.abs(y)) && Math.abs(this.z - z) <= epsilon * Math.max(1.0, Math.abs(this.z), Math.abs(z));
              };

              _proto.strictEquals = function strictEquals(other) {
                return this.x === other.x && this.y === other.y && this.z === other.z;
              };

              _proto.strictEquals3f = function strictEquals3f(x, y, z) {
                return this.x === x && this.y === y && this.z === z;
              };

              _proto.toString = function toString() {
                return "(" + this.x.toFixed(2) + ", " + this.y.toFixed(2) + ", " + this.z.toFixed(2) + ")";
              };

              _proto.lerp = function lerp(to, ratio) {
                this.x += ratio * (to.x - this.x);
                this.y += ratio * (to.y - this.y);
                this.z += ratio * (to.z - this.z);
                return this;
              };

              _proto.add = function add(other) {
                this.x += other.x;
                this.y += other.y;
                this.z += other.z;
                return this;
              };

              _proto.add3f = function add3f(x, y, z) {
                this.x += x;
                this.y += y;
                this.z += z;
                return this;
              };

              _proto.subtract = function subtract(other) {
                this.x -= other.x;
                this.y -= other.y;
                this.z -= other.z;
                return this;
              };

              _proto.subtract3f = function subtract3f(x, y, z) {
                this.x -= x;
                this.y -= y;
                this.z -= z;
                return this;
              };

              _proto.multiplyScalar = function multiplyScalar(scalar) {
                if (typeof scalar === 'object') {
                  console.warn('should use Vec3.multiply for vector * vector operation');
                }

                this.x *= scalar;
                this.y *= scalar;
                this.z *= scalar;
                return this;
              };

              _proto.multiply = function multiply(other) {
                if (typeof other !== 'object') {
                  console.warn('should use Vec3.scale for vector * scalar operation');
                }

                this.x *= other.x;
                this.y *= other.y;
                this.z *= other.z;
                return this;
              };

              _proto.multiply3f = function multiply3f(x, y, z) {
                this.x *= x;
                this.y *= y;
                this.z *= z;
                return this;
              };

              _proto.divide = function divide(other) {
                this.x /= other.x;
                this.y /= other.y;
                this.z /= other.z;
                return this;
              };

              _proto.divide3f = function divide3f(x, y, z) {
                this.x /= x;
                this.y /= y;
                this.z /= z;
                return this;
              };

              _proto.negative = function negative() {
                this.x = -this.x;
                this.y = -this.y;
                this.z = -this.z;
                return this;
              };

              _proto.clampf = function clampf(minInclusive, maxInclusive) {
                this.x = clamp(this.x, minInclusive.x, maxInclusive.x);
                this.y = clamp(this.y, minInclusive.y, maxInclusive.y);
                this.z = clamp(this.z, minInclusive.z, maxInclusive.z);
                return this;
              };

              _proto.dot = function dot(other) {
                return this.x * other.x + this.y * other.y + this.z * other.z;
              };

              _proto.cross = function cross(other) {
                var ax = this.x,
                    ay = this.y,
                    az = this.z;
                var bx = other.x,
                    by = other.y,
                    bz = other.z;
                this.x = ay * bz - az * by;
                this.y = az * bx - ax * bz;
                this.z = ax * by - ay * bx;
                return this;
              };

              _proto.length = function length() {
                return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
              };

              _proto.lengthSqr = function lengthSqr() {
                return this.x * this.x + this.y * this.y + this.z * this.z;
              };

              _proto.normalize = function normalize() {
                var x = this.x;
                var y = this.y;
                var z = this.z;
                var len = x * x + y * y + z * z;

                if (len > 0) {
                  len = 1 / Math.sqrt(len);
                  this.x = x * len;
                  this.y = y * len;
                  this.z = z * len;
                }

                return this;
              };

              _proto.transformMat4 = function transformMat4(matrix) {
                var x = this.x;
                var y = this.y;
                var z = this.z;
                var rhw = matrix.m03 * x + matrix.m07 * y + matrix.m11 * z + matrix.m15;
                rhw = rhw ? 1 / rhw : 1;
                this.x = (matrix.m00 * x + matrix.m04 * y + matrix.m08 * z + matrix.m12) * rhw;
                this.y = (matrix.m01 * x + matrix.m05 * y + matrix.m09 * z + matrix.m13) * rhw;
                this.z = (matrix.m02 * x + matrix.m06 * y + matrix.m10 * z + matrix.m14) * rhw;
                return this;
              };

              return Vec3;
            }(ValueType));
            Vec3.UNIT_X = Object.freeze(new Vec3(1, 0, 0));
            Vec3.UNIT_Y = Object.freeze(new Vec3(0, 1, 0));
            Vec3.UNIT_Z = Object.freeze(new Vec3(0, 0, 1));
            Vec3.RIGHT = Object.freeze(new Vec3(1, 0, 0));
            Vec3.UP = Object.freeze(new Vec3(0, 1, 0));
            Vec3.FORWARD = Object.freeze(new Vec3(0, 0, -1));
            Vec3.ZERO = Object.freeze(new Vec3(0, 0, 0));
            Vec3.ONE = Object.freeze(new Vec3(1, 1, 1));
            Vec3.NEG_ONE = Object.freeze(new Vec3(-1, -1, -1));
            var v3_1 = new Vec3();
            var v3_2 = new Vec3();
            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);
            }
            legacyCC.v3 = v3;

            var Mat3 = exports('Mat3', function (_ValueType) {
              _inheritsLoose(Mat3, _ValueType);

              Mat3.clone = function clone(a) {
                return new Mat3(a.m00, a.m01, a.m02, a.m03, a.m04, a.m05, a.m06, a.m07, a.m08);
              };

              Mat3.copy = function copy(out, a) {
                out.m00 = a.m00;
                out.m01 = a.m01;
                out.m02 = a.m02;
                out.m03 = a.m03;
                out.m04 = a.m04;
                out.m05 = a.m05;
                out.m06 = a.m06;
                out.m07 = a.m07;
                out.m08 = a.m08;
                return out;
              };

              Mat3.set = function set(out, m00, m01, m02, m10, m11, m12, m20, m21, m22) {
                out.m00 = m00;
                out.m01 = m01;
                out.m02 = m02;
                out.m03 = m10;
                out.m04 = m11;
                out.m05 = m12;
                out.m06 = m20;
                out.m07 = m21;
                out.m08 = m22;
                return out;
              };

              Mat3.identity = function identity(out) {
                out.m00 = 1;
                out.m01 = 0;
                out.m02 = 0;
                out.m03 = 0;
                out.m04 = 1;
                out.m05 = 0;
                out.m06 = 0;
                out.m07 = 0;
                out.m08 = 1;
                return out;
              };

              Mat3.transpose = function transpose(out, a) {
                if (out === a) {
                  var a01 = a.m01;
                  var a02 = a.m02;
                  var a12 = a.m05;
                  out.m01 = a.m03;
                  out.m02 = a.m06;
                  out.m03 = a01;
                  out.m05 = a.m07;
                  out.m06 = a02;
                  out.m07 = a12;
                } else {
                  out.m00 = a.m00;
                  out.m01 = a.m03;
                  out.m02 = a.m06;
                  out.m03 = a.m01;
                  out.m04 = a.m04;
                  out.m05 = a.m07;
                  out.m06 = a.m02;
                  out.m07 = a.m05;
                  out.m08 = a.m08;
                }

                return out;
              };

              Mat3.invert = function invert(out, a) {
                var a00 = a.m00;
                var a01 = a.m01;
                var a02 = a.m02;
                var a10 = a.m03;
                var a11 = a.m04;
                var a12 = a.m05;
                var a20 = a.m06;
                var a21 = a.m07;
                var a22 = a.m08;
                var b01 = a22 * a11 - a12 * a21;
                var b11 = -a22 * a10 + a12 * a20;
                var b21 = a21 * a10 - a11 * a20;
                var det = a00 * b01 + a01 * b11 + a02 * b21;

                if (det === 0) {
                  out.m00 = 0;
                  out.m01 = 0;
                  out.m02 = 0;
                  out.m03 = 0;
                  out.m04 = 0;
                  out.m05 = 0;
                  out.m06 = 0;
                  out.m07 = 0;
                  out.m08 = 0;
                  return out;
                }

                det = 1.0 / det;
                out.m00 = b01 * det;
                out.m01 = (-a22 * a01 + a02 * a21) * det;
                out.m02 = (a12 * a01 - a02 * a11) * det;
                out.m03 = b11 * det;
                out.m04 = (a22 * a00 - a02 * a20) * det;
                out.m05 = (-a12 * a00 + a02 * a10) * det;
                out.m06 = b21 * det;
                out.m07 = (-a21 * a00 + a01 * a20) * det;
                out.m08 = (a11 * a00 - a01 * a10) * det;
                return out;
              };

              Mat3.determinant = function determinant(a) {
                var a00 = a.m00;
                var a01 = a.m01;
                var a02 = a.m02;
                var a10 = a.m03;
                var a11 = a.m04;
                var a12 = a.m05;
                var a20 = a.m06;
                var a21 = a.m07;
                var a22 = a.m08;
                return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);
              };

              Mat3.multiply = function multiply(out, a, b) {
                var a00 = a.m00;
                var a01 = a.m01;
                var a02 = a.m02;
                var a10 = a.m03;
                var a11 = a.m04;
                var a12 = a.m05;
                var a20 = a.m06;
                var a21 = a.m07;
                var a22 = a.m08;
                var b00 = b.m00;
                var b01 = b.m01;
                var b02 = b.m02;
                var b10 = b.m03;
                var b11 = b.m04;
                var b12 = b.m05;
                var b20 = b.m06;
                var b21 = b.m07;
                var b22 = b.m08;
                out.m00 = b00 * a00 + b01 * a10 + b02 * a20;
                out.m01 = b00 * a01 + b01 * a11 + b02 * a21;
                out.m02 = b00 * a02 + b01 * a12 + b02 * a22;
                out.m03 = b10 * a00 + b11 * a10 + b12 * a20;
                out.m04 = b10 * a01 + b11 * a11 + b12 * a21;
                out.m05 = b10 * a02 + b11 * a12 + b12 * a22;
                out.m06 = b20 * a00 + b21 * a10 + b22 * a20;
                out.m07 = b20 * a01 + b21 * a11 + b22 * a21;
                out.m08 = b20 * a02 + b21 * a12 + b22 * a22;
                return out;
              };

              Mat3.multiplyMat4 = function multiplyMat4(out, a, b) {
                var a00 = a.m00;
                var a01 = a.m01;
                var a02 = a.m02;
                var a10 = a.m03;
                var a11 = a.m04;
                var a12 = a.m05;
                var a20 = a.m06;
                var a21 = a.m07;
                var a22 = a.m08;
                var b00 = b.m00;
                var b01 = b.m01;
                var b02 = b.m02;
                var b10 = b.m04;
                var b11 = b.m05;
                var b12 = b.m06;
                var b20 = b.m08;
                var b21 = b.m09;
                var b22 = b.m10;
                out.m00 = b00 * a00 + b01 * a10 + b02 * a20;
                out.m01 = b00 * a01 + b01 * a11 + b02 * a21;
                out.m02 = b00 * a02 + b01 * a12 + b02 * a22;
                out.m03 = b10 * a00 + b11 * a10 + b12 * a20;
                out.m04 = b10 * a01 + b11 * a11 + b12 * a21;
                out.m05 = b10 * a02 + b11 * a12 + b12 * a22;
                out.m06 = b20 * a00 + b21 * a10 + b22 * a20;
                out.m07 = b20 * a01 + b21 * a11 + b22 * a21;
                out.m08 = b20 * a02 + b21 * a12 + b22 * a22;
                return out;
              };

              Mat3.transform = function transform(out, a, v) {
                var a00 = a.m00;
                var a01 = a.m01;
                var a02 = a.m02;
                var a10 = a.m03;
                var a11 = a.m04;
                var a12 = a.m05;
                var a20 = a.m06;
                var a21 = a.m07;
                var a22 = a.m08;
                var x = v.x;
                var y = v.y;
                out.m00 = a00;
                out.m01 = a01;
                out.m02 = a02;
                out.m03 = a10;
                out.m04 = a11;
                out.m05 = a12;
                out.m06 = x * a00 + y * a10 + a20;
                out.m07 = x * a01 + y * a11 + a21;
                out.m08 = x * a02 + y * a12 + a22;
                return out;
              };

              Mat3.scale = function scale(out, a, v) {
                var x = v.x;
                var y = v.y;
                out.m00 = x * a.m00;
                out.m01 = x * a.m01;
                out.m02 = x * a.m02;
                out.m03 = y * a.m03;
                out.m04 = y * a.m04;
                out.m05 = y * a.m05;
                out.m06 = a.m06;
                out.m07 = a.m07;
                out.m08 = a.m08;
                return out;
              };

              Mat3.rotate = function rotate(out, a, rad) {
                var a00 = a.m00;
                var a01 = a.m01;
                var a02 = a.m02;
                var a10 = a.m03;
                var a11 = a.m04;
                var a12 = a.m05;
                var a20 = a.m06;
                var a21 = a.m07;
                var a22 = a.m08;
                var s = Math.sin(rad);
                var c = Math.cos(rad);
                out.m00 = c * a00 + s * a10;
                out.m01 = c * a01 + s * a11;
                out.m02 = c * a02 + s * a12;
                out.m03 = c * a10 - s * a00;
                out.m04 = c * a11 - s * a01;
                out.m05 = c * a12 - s * a02;
                out.m06 = a20;
                out.m07 = a21;
                out.m08 = a22;
                return out;
              };

              Mat3.fromMat4 = function fromMat4(out, a) {
                out.m00 = a.m00;
                out.m01 = a.m01;
                out.m02 = a.m02;
                out.m03 = a.m04;
                out.m04 = a.m05;
                out.m05 = a.m06;
                out.m06 = a.m08;
                out.m07 = a.m09;
                out.m08 = a.m10;
                return out;
              };

              Mat3.fromViewUp = function fromViewUp(out, view, up) {
                if (Vec3.lengthSqr(view) < EPSILON * EPSILON) {
                  Mat3.identity(out);
                  return out;
                }

                up = up || Vec3.UNIT_Y;
                Vec3.normalize(v3_1$1, Vec3.cross(v3_1$1, up, view));

                if (Vec3.lengthSqr(v3_1$1) < EPSILON * EPSILON) {
                  Mat3.identity(out);
                  return out;
                }

                Vec3.cross(v3_2$1, view, v3_1$1);
                Mat3.set(out, v3_1$1.x, v3_1$1.y, v3_1$1.z, v3_2$1.x, v3_2$1.y, v3_2$1.z, view.x, view.y, view.z);
                return out;
              };

              Mat3.fromTranslation = function fromTranslation(out, v) {
                out.m00 = 1;
                out.m01 = 0;
                out.m02 = 0;
                out.m03 = 0;
                out.m04 = 1;
                out.m05 = 0;
                out.m06 = v.x;
                out.m07 = v.y;
                out.m08 = 1;
                return out;
              };

              Mat3.fromScaling = function fromScaling(out, v) {
                out.m00 = v.x;
                out.m01 = 0;
                out.m02 = 0;
                out.m03 = 0;
                out.m04 = v.y;
                out.m05 = 0;
                out.m06 = 0;
                out.m07 = 0;
                out.m08 = 1;
                return out;
              };

              Mat3.fromRotation = function fromRotation(out, rad) {
                var s = Math.sin(rad);
                var c = Math.cos(rad);
                out.m00 = c;
                out.m01 = s;
                out.m02 = 0;
                out.m03 = -s;
                out.m04 = c;
                out.m05 = 0;
                out.m06 = 0;
                out.m07 = 0;
                out.m08 = 1;
                return out;
              };

              Mat3.fromQuat = function fromQuat(out, q) {
                var x = q.x;
                var y = q.y;
                var z = q.z;
                var w = q.w;
                var x2 = x + x;
                var y2 = y + y;
                var z2 = z + z;
                var xx = x * x2;
                var yx = y * x2;
                var yy = y * y2;
                var zx = z * x2;
                var zy = z * y2;
                var zz = z * z2;
                var wx = w * x2;
                var wy = w * y2;
                var wz = w * z2;
                out.m00 = 1 - yy - zz;
                out.m03 = yx - wz;
                out.m06 = zx + wy;
                out.m01 = yx + wz;
                out.m04 = 1 - xx - zz;
                out.m07 = zy - wx;
                out.m02 = zx - wy;
                out.m05 = zy + wx;
                out.m08 = 1 - xx - yy;
                return out;
              };

              Mat3.inverseTransposeMat4 = function inverseTransposeMat4(out, a) {
                var a00 = a.m00;
                var a01 = a.m01;
                var a02 = a.m02;
                var a03 = a.m03;
                var a10 = a.m04;
                var a11 = a.m05;
                var a12 = a.m06;
                var a13 = a.m07;
                var a20 = a.m08;
                var a21 = a.m09;
                var a22 = a.m10;
                var a23 = a.m11;
                var a30 = a.m12;
                var a31 = a.m13;
                var a32 = a.m14;
                var a33 = a.m15;
                var b00 = a00 * a11 - a01 * a10;
                var b01 = a00 * a12 - a02 * a10;
                var b02 = a00 * a13 - a03 * a10;
                var b03 = a01 * a12 - a02 * a11;
                var b04 = a01 * a13 - a03 * a11;
                var b05 = a02 * a13 - a03 * a12;
                var b06 = a20 * a31 - a21 * a30;
                var b07 = a20 * a32 - a22 * a30;
                var b08 = a20 * a33 - a23 * a30;
                var b09 = a21 * a32 - a22 * a31;
                var b10 = a21 * a33 - a23 * a31;
                var b11 = a22 * a33 - a23 * a32;
                var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;

                if (!det) {
                  return null;
                }

                det = 1.0 / det;
                out.m00 = (a11 * b11 - a12 * b10 + a13 * b09) * det;
                out.m01 = (a12 * b08 - a10 * b11 - a13 * b07) * det;
                out.m02 = (a10 * b10 - a11 * b08 + a13 * b06) * det;
                out.m03 = (a02 * b10 - a01 * b11 - a03 * b09) * det;
                out.m04 = (a00 * b11 - a02 * b08 + a03 * b07) * det;
                out.m05 = (a01 * b08 - a00 * b10 - a03 * b06) * det;
                out.m06 = (a31 * b05 - a32 * b04 + a33 * b03) * det;
                out.m07 = (a32 * b02 - a30 * b05 - a33 * b01) * det;
                out.m08 = (a30 * b04 - a31 * b02 + a33 * b00) * det;
                return out;
              };

              Mat3.toArray = function toArray(out, m, ofs) {
                if (ofs === void 0) {
                  ofs = 0;
                }

                out[ofs + 0] = m.m00;
                out[ofs + 1] = m.m01;
                out[ofs + 2] = m.m02;
                out[ofs + 3] = m.m03;
                out[ofs + 4] = m.m04;
                out[ofs + 5] = m.m05;
                out[ofs + 6] = m.m06;
                out[ofs + 7] = m.m07;
                out[ofs + 8] = m.m08;
                return out;
              };

              Mat3.fromArray = function fromArray(out, arr, ofs) {
                if (ofs === void 0) {
                  ofs = 0;
                }

                out.m00 = arr[ofs + 0];
                out.m01 = arr[ofs + 1];
                out.m02 = arr[ofs + 2];
                out.m03 = arr[ofs + 3];
                out.m04 = arr[ofs + 4];
                out.m05 = arr[ofs + 5];
                out.m06 = arr[ofs + 6];
                out.m07 = arr[ofs + 7];
                out.m08 = arr[ofs + 8];
                return out;
              };

              Mat3.add = function add(out, a, b) {
                out.m00 = a.m00 + b.m00;
                out.m01 = a.m01 + b.m01;
                out.m02 = a.m02 + b.m02;
                out.m03 = a.m03 + b.m03;
                out.m04 = a.m04 + b.m04;
                out.m05 = a.m05 + b.m05;
                out.m06 = a.m06 + b.m06;
                out.m07 = a.m07 + b.m07;
                out.m08 = a.m08 + b.m08;
                return out;
              };

              Mat3.subtract = function subtract(out, a, b) {
                out.m00 = a.m00 - b.m00;
                out.m01 = a.m01 - b.m01;
                out.m02 = a.m02 - b.m02;
                out.m03 = a.m03 - b.m03;
                out.m04 = a.m04 - b.m04;
                out.m05 = a.m05 - b.m05;
                out.m06 = a.m06 - b.m06;
                out.m07 = a.m07 - b.m07;
                out.m08 = a.m08 - b.m08;
                return out;
              };

              Mat3.multiplyScalar = function multiplyScalar(out, a, b) {
                out.m00 = a.m00 * b;
                out.m01 = a.m01 * b;
                out.m02 = a.m02 * b;
                out.m03 = a.m03 * b;
                out.m04 = a.m04 * b;
                out.m05 = a.m05 * b;
                out.m06 = a.m06 * b;
                out.m07 = a.m07 * b;
                out.m08 = a.m08 * b;
                return out;
              };

              Mat3.multiplyScalarAndAdd = function multiplyScalarAndAdd(out, a, b, scale) {
                out.m00 = b.m00 * scale + a.m00;
                out.m01 = b.m01 * scale + a.m01;
                out.m02 = b.m02 * scale + a.m02;
                out.m03 = b.m03 * scale + a.m03;
                out.m04 = b.m04 * scale + a.m04;
                out.m05 = b.m05 * scale + a.m05;
                out.m06 = b.m06 * scale + a.m06;
                out.m07 = b.m07 * scale + a.m07;
                out.m08 = b.m08 * scale + a.m08;
                return out;
              };

              Mat3.strictEquals = function strictEquals(a, b) {
                return a.m00 === b.m00 && a.m01 === b.m01 && a.m02 === b.m02 && a.m03 === b.m03 && a.m04 === b.m04 && a.m05 === b.m05 && a.m06 === b.m06 && a.m07 === b.m07 && a.m08 === b.m08;
              };

              Mat3.equals = function equals(a, b, epsilon) {
                if (epsilon === void 0) {
                  epsilon = EPSILON;
                }

                return Math.abs(a.m00 - b.m00) <= epsilon * Math.max(1.0, Math.abs(a.m00), Math.abs(b.m00)) && Math.abs(a.m01 - b.m01) <= epsilon * Math.max(1.0, Math.abs(a.m01), Math.abs(b.m01)) && Math.abs(a.m02 - b.m02) <= epsilon * Math.max(1.0, Math.abs(a.m02), Math.abs(b.m02)) && Math.abs(a.m03 - b.m03) <= epsilon * Math.max(1.0, Math.abs(a.m03), Math.abs(b.m03)) && Math.abs(a.m04 - b.m04) <= epsilon * Math.max(1.0, Math.abs(a.m04), Math.abs(b.m04)) && Math.abs(a.m05 - b.m05) <= epsilon * Math.max(1.0, Math.abs(a.m05), Math.abs(b.m05)) && Math.abs(a.m06 - b.m06) <= epsilon * Math.max(1.0, Math.abs(a.m06), Math.abs(b.m06)) && Math.abs(a.m07 - b.m07) <= epsilon * Math.max(1.0, Math.abs(a.m07), Math.abs(b.m07)) && Math.abs(a.m08 - b.m08) <= epsilon * Math.max(1.0, Math.abs(a.m08), Math.abs(b.m08));
              };

              function Mat3(m00, m01, m02, m03, m04, m05, m06, m07, m08) {
                var _this;

                if (m00 === void 0) {
                  m00 = 1;
                }

                if (m01 === void 0) {
                  m01 = 0;
                }

                if (m02 === void 0) {
                  m02 = 0;
                }

                if (m03 === void 0) {
                  m03 = 0;
                }

                if (m04 === void 0) {
                  m04 = 1;
                }

                if (m05 === void 0) {
                  m05 = 0;
                }

                if (m06 === void 0) {
                  m06 = 0;
                }

                if (m07 === void 0) {
                  m07 = 0;
                }

                if (m08 === void 0) {
                  m08 = 1;
                }

                _this = _ValueType.call(this) || this;

                if (typeof m00 === 'object') {
                  _this.m00 = m00.m00;
                  _this.m01 = m00.m01;
                  _this.m02 = m00.m02;
                  _this.m03 = m00.m03;
                  _this.m04 = m00.m04;
                  _this.m05 = m00.m05;
                  _this.m06 = m00.m06;
                  _this.m07 = m00.m07;
                  _this.m08 = m00.m08;
                } else {
                  _this.m00 = m00;
                  _this.m01 = m01;
                  _this.m02 = m02;
                  _this.m03 = m03;
                  _this.m04 = m04;
                  _this.m05 = m05;
                  _this.m06 = m06;
                  _this.m07 = m07;
                  _this.m08 = m08;
                }

                return _this;
              }

              var _proto = Mat3.prototype;

              _proto.clone = function clone() {
                var t = this;
                return new Mat3(t.m00, t.m01, t.m02, t.m03, t.m04, t.m05, t.m06, t.m07, t.m08);
              };

              _proto.set = function set(m00, m01, m02, m03, m04, m05, m06, m07, m08) {
                if (m00 === void 0) {
                  m00 = 1;
                }

                if (m01 === void 0) {
                  m01 = 0;
                }

                if (m02 === void 0) {
                  m02 = 0;
                }

                if (m03 === void 0) {
                  m03 = 0;
                }

                if (m04 === void 0) {
                  m04 = 1;
                }

                if (m05 === void 0) {
                  m05 = 0;
                }

                if (m06 === void 0) {
                  m06 = 0;
                }

                if (m07 === void 0) {
                  m07 = 0;
                }

                if (m08 === void 0) {
                  m08 = 1;
                }

                if (typeof m00 === 'object') {
                  this.m00 = m00.m00;
                  this.m01 = m00.m01;
                  this.m02 = m00.m02;
                  this.m03 = m00.m03;
                  this.m04 = m00.m04;
                  this.m05 = m00.m05;
                  this.m06 = m00.m06;
                  this.m07 = m00.m07;
                  this.m08 = m00.m08;
                } else {
                  this.m00 = m00;
                  this.m01 = m01;
                  this.m02 = m02;
                  this.m03 = m03;
                  this.m04 = m04;
                  this.m05 = m05;
                  this.m06 = m06;
                  this.m07 = m07;
                  this.m08 = m08;
                }

                return this;
              };

              _proto.equals = function equals(other, epsilon) {
                if (epsilon === void 0) {
                  epsilon = EPSILON;
                }

                return Math.abs(this.m00 - other.m00) <= epsilon * Math.max(1.0, Math.abs(this.m00), Math.abs(other.m00)) && Math.abs(this.m01 - other.m01) <= epsilon * Math.max(1.0, Math.abs(this.m01), Math.abs(other.m01)) && Math.abs(this.m02 - other.m02) <= epsilon * Math.max(1.0, Math.abs(this.m02), Math.abs(other.m02)) && Math.abs(this.m03 - other.m03) <= epsilon * Math.max(1.0, Math.abs(this.m03), Math.abs(other.m03)) && Math.abs(this.m04 - other.m04) <= epsilon * Math.max(1.0, Math.abs(this.m04), Math.abs(other.m04)) && Math.abs(this.m05 - other.m05) <= epsilon * Math.max(1.0, Math.abs(this.m05), Math.abs(other.m05)) && Math.abs(this.m06 - other.m06) <= epsilon * Math.max(1.0, Math.abs(this.m06), Math.abs(other.m06)) && Math.abs(this.m07 - other.m07) <= epsilon * Math.max(1.0, Math.abs(this.m07), Math.abs(other.m07)) && Math.abs(this.m08 - other.m08) <= epsilon * Math.max(1.0, Math.abs(this.m08), Math.abs(other.m08));
              };

              _proto.strictEquals = function strictEquals(other) {
                return this.m00 === other.m00 && this.m01 === other.m01 && this.m02 === other.m02 && this.m03 === other.m03 && this.m04 === other.m04 && this.m05 === other.m05 && this.m06 === other.m06 && this.m07 === other.m07 && this.m08 === other.m08;
              };

              _proto.toString = function toString() {
                var t = this;
                return "[\n" + t.m00 + ", " + t.m01 + ", " + t.m02 + ",\n" + t.m03 + ",\n" + t.m04 + ", " + t.m05 + ",\n" + t.m06 + ", " + t.m07 + ",\n" + t.m08 + "\n" + "]";
              };

              _proto.identity = function identity() {
                this.m00 = 1;
                this.m01 = 0;
                this.m02 = 0;
                this.m03 = 0;
                this.m04 = 1;
                this.m05 = 0;
                this.m06 = 0;
                this.m07 = 0;
                this.m08 = 1;
                return this;
              };

              _proto.transpose = function transpose() {
                var a01 = this.m01;
                var a02 = this.m02;
                var a12 = this.m05;
                this.m01 = this.m03;
                this.m02 = this.m06;
                this.m03 = a01;
                this.m05 = this.m07;
                this.m06 = a02;
                this.m07 = a12;
                return this;
              };

              _proto.invert = function invert() {
                var a00 = this.m00;
                var a01 = this.m01;
                var a02 = this.m02;
                var a10 = this.m03;
                var a11 = this.m04;
                var a12 = this.m05;
                var a20 = this.m06;
                var a21 = this.m07;
                var a22 = this.m08;
                var b01 = a22 * a11 - a12 * a21;
                var b11 = -a22 * a10 + a12 * a20;
                var b21 = a21 * a10 - a11 * a20;
                var det = a00 * b01 + a01 * b11 + a02 * b21;

                if (det === 0) {
                  this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
                  return this;
                }

                det = 1.0 / det;
                this.m00 = b01 * det;
                this.m01 = (-a22 * a01 + a02 * a21) * det;
                this.m02 = (a12 * a01 - a02 * a11) * det;
                this.m03 = b11 * det;
                this.m04 = (a22 * a00 - a02 * a20) * det;
                this.m05 = (-a12 * a00 + a02 * a10) * det;
                this.m06 = b21 * det;
                this.m07 = (-a21 * a00 + a01 * a20) * det;
                this.m08 = (a11 * a00 - a01 * a10) * det;
                return this;
              };

              _proto.determinant = function determinant() {
                var a00 = this.m00;
                var a01 = this.m01;
                var a02 = this.m02;
                var a10 = this.m03;
                var a11 = this.m04;
                var a12 = this.m05;
                var a20 = this.m06;
                var a21 = this.m07;
                var a22 = this.m08;
                return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);
              };

              _proto.add = function add(mat) {
                this.m00 += mat.m00;
                this.m01 += mat.m01;
                this.m02 += mat.m02;
                this.m03 += mat.m03;
                this.m04 += mat.m04;
                this.m05 += mat.m05;
                this.m06 += mat.m06;
                this.m07 += mat.m07;
                this.m08 += mat.m08;
                return this;
              };

              _proto.subtract = function subtract(mat) {
                this.m00 -= mat.m00;
                this.m01 -= mat.m01;
                this.m02 -= mat.m02;
                this.m03 -= mat.m03;
                this.m04 -= mat.m04;
                this.m05 -= mat.m05;
                this.m06 -= mat.m06;
                this.m07 -= mat.m07;
                this.m08 -= mat.m08;
                return this;
              };

              _proto.multiply = function multiply(mat) {
                var a00 = this.m00;
                var a01 = this.m01;
                var a02 = this.m02;
                var a10 = this.m03;
                var a11 = this.m04;
                var a12 = this.m05;
                var a20 = this.m06;
                var a21 = this.m07;
                var a22 = this.m08;
                var b00 = mat.m00;
                var b01 = mat.m01;
                var b02 = mat.m02;
                var b10 = mat.m03;
                var b11 = mat.m04;
                var b12 = mat.m05;
                var b20 = mat.m06;
                var b21 = mat.m07;
                var b22 = mat.m08;
                this.m00 = b00 * a00 + b01 * a10 + b02 * a20;
                this.m01 = b00 * a01 + b01 * a11 + b02 * a21;
                this.m02 = b00 * a02 + b01 * a12 + b02 * a22;
                this.m03 = b10 * a00 + b11 * a10 + b12 * a20;
                this.m04 = b10 * a01 + b11 * a11 + b12 * a21;
                this.m05 = b10 * a02 + b11 * a12 + b12 * a22;
                this.m06 = b20 * a00 + b21 * a10 + b22 * a20;
                this.m07 = b20 * a01 + b21 * a11 + b22 * a21;
                this.m08 = b20 * a02 + b21 * a12 + b22 * a22;
                return this;
              };

              _proto.multiplyScalar = function multiplyScalar(scalar) {
                this.m00 *= scalar;
                this.m01 *= scalar;
                this.m02 *= scalar;
                this.m03 *= scalar;
                this.m04 *= scalar;
                this.m05 *= scalar;
                this.m06 *= scalar;
                this.m07 *= scalar;
                this.m08 *= scalar;
                return this;
              };

              _proto.scale = function scale(vec) {
                var x = vec.x;
                var y = vec.y;
                this.m00 = x * this.m00;
                this.m01 = x * this.m01;
                this.m02 = x * this.m02;
                this.m03 = y * this.m03;
                this.m04 = y * this.m04;
                this.m05 = y * this.m05;
                this.m06 = this.m06;
                this.m07 = this.m07;
                this.m08 = this.m08;
                return this;
              };

              _proto.rotate = function rotate(rad) {
                var a00 = this.m00;
                var a01 = this.m01;
                var a02 = this.m02;
                var a10 = this.m03;
                var a11 = this.m04;
                var a12 = this.m05;
                var a20 = this.m06;
                var a21 = this.m07;
                var a22 = this.m08;
                var s = Math.sin(rad);
                var c = Math.cos(rad);
                this.m00 = c * a00 + s * a10;
                this.m01 = c * a01 + s * a11;
                this.m02 = c * a02 + s * a12;
                this.m03 = c * a10 - s * a00;
                this.m04 = c * a11 - s * a01;
                this.m05 = c * a12 - s * a02;
                this.m06 = a20;
                this.m07 = a21;
                this.m08 = a22;
                return this;
              };

              _proto.fromQuat = function fromQuat(q) {
                var x = q.x;
                var y = q.y;
                var z = q.z;
                var w = q.w;
                var x2 = x + x;
                var y2 = y + y;
                var z2 = z + z;
                var xx = x * x2;
                var yx = y * x2;
                var yy = y * y2;
                var zx = z * x2;
                var zy = z * y2;
                var zz = z * z2;
                var wx = w * x2;
                var wy = w * y2;
                var wz = w * z2;
                this.m00 = 1 - yy - zz;
                this.m03 = yx - wz;
                this.m06 = zx + wy;
                this.m01 = yx + wz;
                this.m04 = 1 - xx - zz;
                this.m07 = zy - wx;
                this.m02 = zx - wy;
                this.m05 = zy + wx;
                this.m08 = 1 - xx - yy;
                return this;
              };

              return Mat3;
            }(ValueType));
            Mat3.IDENTITY = Object.freeze(new Mat3());
            var v3_1$1 = new Vec3();
            var v3_2$1 = 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 Quat = exports('Quat', function (_ValueType) {
              _inheritsLoose(Quat, _ValueType);

              Quat.clone = function clone(a) {
                return new Quat(a.x, a.y, a.z, a.w);
              };

              Quat.copy = function copy(out, a) {
                out.x = a.x;
                out.y = a.y;
                out.z = a.z;
                out.w = a.w;
                return out;
              };

              Quat.set = function set(out, x, y, z, w) {
                out.x = x;
                out.y = y;
                out.z = z;
                out.w = w;
                return out;
              };

              Quat.identity = function identity(out) {
                out.x = 0;
                out.y = 0;
                out.z = 0;
                out.w = 1;
                return out;
              };

              Quat.rotationTo = function rotationTo(out, a, b) {
                var dot = Vec3.dot(a, b);

                if (dot < -0.999999) {
                  Vec3.cross(v3_1$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, Math.PI);
                  return out;
                } else if (dot > 0.999999) {
                  out.x = 0;
                  out.y = 0;
                  out.z = 0;
                  out.w = 1;
                  return out;
                } else {
                  Vec3.cross(v3_1$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);
                }
              };

              Quat.getAxisAngle = function getAxisAngle(outAxis, q) {
                var rad = Math.acos(q.w) * 2.0;
                var s = Math.sin(rad / 2.0);

                if (s !== 0.0) {
                  outAxis.x = q.x / s;
                  outAxis.y = q.y / s;
                  outAxis.z = q.z / s;
                } else {
                  outAxis.x = 1;
                  outAxis.y = 0;
                  outAxis.z = 0;
                }

                return rad;
              };

              Quat.multiply = function multiply(out, a, b) {
                var x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;
                var y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;
                var z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;
                var w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;
                out.x = x;
                out.y = y;
                out.z = z;
                out.w = w;
                return out;
              };

              Quat.multiplyScalar = function multiplyScalar(out, a, b) {
                out.x = a.x * b;
                out.y = a.y * b;
                out.z = a.z * b;
                out.w = a.w * b;
                return out;
              };

              Quat.scaleAndAdd = function scaleAndAdd(out, a, b, scale) {
                out.x = a.x + b.x * scale;
                out.y = a.y + b.y * scale;
                out.z = a.z + b.z * scale;
                out.w = a.w + b.w * scale;
                return out;
              };

              Quat.rotateX = function rotateX(out, a, rad) {
                rad *= 0.5;
                var bx = Math.sin(rad);
                var bw = Math.cos(rad);
                var x = a.x,
                    y = a.y,
                    z = a.z,
                    w = a.w;
                out.x = x * bw + w * bx;
                out.y = y * bw + z * bx;
                out.z = z * bw - y * bx;
                out.w = w * bw - x * bx;
                return out;
              };

              Quat.rotateY = function rotateY(out, a, rad) {
                rad *= 0.5;
                var by = Math.sin(rad);
                var bw = Math.cos(rad);
                var x = a.x,
                    y = a.y,
                    z = a.z,
                    w = a.w;
                out.x = x * bw - z * by;
                out.y = y * bw + w * by;
                out.z = z * bw + x * by;
                out.w = w * bw - y * by;
                return out;
              };

              Quat.rotateZ = function rotateZ(out, a, rad) {
                rad *= 0.5;
                var bz = Math.sin(rad);
                var bw = Math.cos(rad);
                var x = a.x,
                    y = a.y,
                    z = a.z,
                    w = a.w;
                out.x = x * bw + y * bz;
                out.y = y * bw - x * bz;
                out.z = z * bw + w * bz;
                out.w = w * bw - z * bz;
                return out;
              };

              Quat.rotateAround = function rotateAround(out, rot, axis, rad) {
                Quat.invert(qt_1, 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;
              };

              Quat.rotateAroundLocal = function rotateAroundLocal(out, rot, axis, rad) {
                Quat.fromAxisAngle(qt_1, axis, rad);
                Quat.multiply(out, rot, qt_1);
                return out;
              };

              Quat.calculateW = function calculateW(out, a) {
                out.x = a.x;
                out.y = a.y;
                out.z = a.z;
                out.w = Math.sqrt(Math.abs(1.0 - a.x * a.x - a.y * a.y - a.z * a.z));
                return out;
              };

              Quat.dot = function dot(a, b) {
                return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
              };

              Quat.lerp = function lerp(out, a, b, t) {
                out.x = a.x + t * (b.x - a.x);
                out.y = a.y + t * (b.y - a.y);
                out.z = a.z + t * (b.z - a.z);
                out.w = a.w + t * (b.w - a.w);
                return out;
              };

              Quat.slerp = function slerp(out, a, b, t) {
                var scale0 = 0;
                var scale1 = 0;
                var bx = b.x;
                var by = b.y;
                var bz = b.z;
                var bw = b.w;
                var cosom = a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;

                if (cosom < 0.0) {
                  cosom = -cosom;
                  bx = -bx;
                  by = -by;
                  bz = -bz;
                  bw = -bw;
                }

                if (1.0 - cosom > 0.000001) {
                  var omega = Math.acos(cosom);
                  var sinom = Math.sin(omega);
                  scale0 = Math.sin((1.0 - t) * omega) / sinom;
                  scale1 = Math.sin(t * omega) / sinom;
                } else {
                  scale0 = 1.0 - t;
                  scale1 = t;
                }

                out.x = scale0 * a.x + scale1 * bx;
                out.y = scale0 * a.y + scale1 * by;
                out.z = scale0 * a.z + scale1 * bz;
                out.w = scale0 * a.w + scale1 * bw;
                return out;
              };

              Quat.sqlerp = function sqlerp(out, a, b, c, d, t) {
                Quat.slerp(qt_1, a, d, t);
                Quat.slerp(qt_2, b, c, t);
                Quat.slerp(out, qt_1, qt_2, 2 * t * (1 - t));
                return out;
              };

              Quat.invert = function invert(out, a) {
                var dot = a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w;
                var invDot = dot ? 1.0 / dot : 0;
                out.x = -a.x * invDot;
                out.y = -a.y * invDot;
                out.z = -a.z * invDot;
                out.w = a.w * invDot;
                return out;
              };

              Quat.conjugate = function conjugate(out, a) {
                out.x = -a.x;
                out.y = -a.y;
                out.z = -a.z;
                out.w = a.w;
                return out;
              };

              Quat.len = function len(a) {
                return Math.sqrt(a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w);
              };

              Quat.lengthSqr = function lengthSqr(a) {
                return a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w;
              };

              Quat.normalize = function normalize(out, a) {
                var len = a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w;

                if (len > 0) {
                  len = 1 / Math.sqrt(len);
                  out.x = a.x * len;
                  out.y = a.y * len;
                  out.z = a.z * len;
                  out.w = a.w * len;
                }

                return out;
              };

              Quat.fromAxes = function fromAxes(out, xAxis, yAxis, zAxis) {
                Mat3.set(m3_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));
              };

              Quat.fromViewUp = function fromViewUp(out, view, up) {
                Mat3.fromViewUp(m3_1, view, up);
                return Quat.normalize(out, Quat.fromMat3(out, m3_1));
              };

              Quat.fromAxisAngle = function fromAxisAngle(out, axis, rad) {
                rad *= 0.5;
                var s = Math.sin(rad);
                out.x = s * axis.x;
                out.y = s * axis.y;
                out.z = s * axis.z;
                out.w = Math.cos(rad);
                return out;
              };

              Quat.fromMat3 = function fromMat3(out, m) {
                var m00 = m.m00,
                    m01 = m.m03,
                    m02 = m.m06,
                    m10 = m.m01,
                    m11 = m.m04,
                    m12 = m.m07,
                    m20 = m.m02,
                    m21 = m.m05,
                    m22 = m.m08;
                var trace = m00 + m11 + m22;

                if (trace > 0) {
                  var s = 0.5 / Math.sqrt(trace + 1.0);
                  out.w = 0.25 / s;
                  out.x = (m21 - m12) * s;
                  out.y = (m02 - m20) * s;
                  out.z = (m10 - m01) * s;
                } else if (m00 > m11 && m00 > m22) {
                  var _s = 2.0 * Math.sqrt(1.0 + m00 - m11 - m22);

                  out.w = (m21 - m12) / _s;
                  out.x = 0.25 * _s;
                  out.y = (m01 + m10) / _s;
                  out.z = (m02 + m20) / _s;
                } else if (m11 > m22) {
                  var _s2 = 2.0 * Math.sqrt(1.0 + m11 - m00 - m22);

                  out.w = (m02 - m20) / _s2;
                  out.x = (m01 + m10) / _s2;
                  out.y = 0.25 * _s2;
                  out.z = (m12 + m21) / _s2;
                } else {
                  var _s3 = 2.0 * Math.sqrt(1.0 + m22 - m00 - m11);

                  out.w = (m10 - m01) / _s3;
                  out.x = (m02 + m20) / _s3;
                  out.y = (m12 + m21) / _s3;
                  out.z = 0.25 * _s3;
                }

                return out;
              };

              Quat.fromEuler = function fromEuler(out, x, y, z) {
                x *= halfToRad;
                y *= halfToRad;
                z *= halfToRad;
                var sx = Math.sin(x);
                var cx = Math.cos(x);
                var sy = Math.sin(y);
                var cy = Math.cos(y);
                var sz = Math.sin(z);
                var cz = Math.cos(z);
                out.x = sx * cy * cz + cx * sy * sz;
                out.y = cx * sy * cz + sx * cy * sz;
                out.z = cx * cy * sz - sx * sy * cz;
                out.w = cx * cy * cz - sx * sy * sz;
                return out;
              };

              Quat.fromAngleZ = function fromAngleZ(out, z) {
                z *= halfToRad;
                out.x = out.y = 0;
                out.z = Math.sin(z);
                out.w = Math.cos(z);
                return out;
              };

              Quat.toAxisX = function toAxisX(out, q) {
                var fy = 2.0 * q.y;
                var fz = 2.0 * q.z;
                out.x = 1.0 - fy * q.y - fz * q.z;
                out.y = fy * q.x + fz * q.w;
                out.z = fz * q.x + fy * q.w;
                return out;
              };

              Quat.toAxisY = function toAxisY(out, q) {
                var fx = 2.0 * q.x;
                var fy = 2.0 * q.y;
                var fz = 2.0 * q.z;
                out.x = fy * q.x - fz * q.w;
                out.y = 1.0 - fx * q.x - fz * q.z;
                out.z = fz * q.y + fx * q.w;
                return out;
              };

              Quat.toAxisZ = function toAxisZ(out, q) {
                var fx = 2.0 * q.x;
                var fy = 2.0 * q.y;
                var fz = 2.0 * q.z;
                out.x = fz * q.x - fy * q.w;
                out.y = fz * q.y - fx * q.w;
                out.z = 1.0 - fx * q.x - fy * q.y;
                return out;
              };

              Quat.toEuler = function toEuler(out, q, outerZ) {
                var x = q.x,
                    y = q.y,
                    z = q.z,
                    w = q.w;
                var bank = 0;
                var heading = 0;
                var attitude = 0;
                var test = x * y + z * w;

                if (test > 0.499999) {
                  bank = 0;
                  heading = toDegree(2 * Math.atan2(x, w));
                  attitude = 90;
                } else if (test < -0.499999) {
                  bank = 0;
                  heading = -toDegree(2 * Math.atan2(x, w));
                  attitude = -90;
                } else {
                  var sqx = x * x;
                  var sqy = y * y;
                  var sqz = z * z;
                  bank = toDegree(Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz));
                  heading = toDegree(Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz));
                  attitude = toDegree(Math.asin(2 * test));

                  if (outerZ) {
                    bank = -180 * Math.sign(bank + 1e-6) + bank;
                    heading = -180 * Math.sign(heading + 1e-6) + heading;
                    attitude = 180 * Math.sign(attitude + 1e-6) - attitude;
                  }
                }

                out.x = bank;
                out.y = heading;
                out.z = attitude;
                return out;
              };

              Quat.toArray = function toArray(out, q, ofs) {
                if (ofs === void 0) {
                  ofs = 0;
                }

                out[ofs + 0] = q.x;
                out[ofs + 1] = q.y;
                out[ofs + 2] = q.z;
                out[ofs + 3] = q.w;
                return out;
              };

              Quat.fromArray = function fromArray(out, arr, ofs) {
                if (ofs === void 0) {
                  ofs = 0;
                }

                out.x = arr[ofs + 0];
                out.y = arr[ofs + 1];
                out.z = arr[ofs + 2];
                out.w = arr[ofs + 3];
                return out;
              };

              Quat.strictEquals = function strictEquals(a, b) {
                return a.x === b.x && a.y === b.y && a.z === b.z && a.w === b.w;
              };

              Quat.equals = function equals(a, b, epsilon) {
                if (epsilon === void 0) {
                  epsilon = EPSILON;
                }

                return Math.abs(a.x - b.x) <= epsilon * Math.max(1.0, Math.abs(a.x), Math.abs(b.x)) && Math.abs(a.y - b.y) <= epsilon * Math.max(1.0, Math.abs(a.y), Math.abs(b.y)) && Math.abs(a.z - b.z) <= epsilon * Math.max(1.0, Math.abs(a.z), Math.abs(b.z)) && Math.abs(a.w - b.w) <= epsilon * Math.max(1.0, Math.abs(a.w), Math.abs(b.w));
              };

              function Quat(x, y, z, w) {
                var _this;

                _this = _ValueType.call(this) || this;

                if (x && typeof x === 'object') {
                  _this.x = x.x;
                  _this.y = x.y;
                  _this.z = x.z;
                  _this.w = x.w;
                } else {
                  _this.x = x || 0;
                  _this.y = y || 0;
                  _this.z = z || 0;
                  _this.w = w !== null && w !== void 0 ? w : 1;
                }

                return _this;
              }

              var _proto = Quat.prototype;

              _proto.clone = function clone() {
                return new Quat(this.x, this.y, this.z, this.w);
              };

              _proto.set = function set(x, y, z, w) {
                if (x && typeof x === 'object') {
                  this.x = x.x;
                  this.y = x.y;
                  this.z = x.z;
                  this.w = x.w;
                } else {
                  this.x = x || 0;
                  this.y = y || 0;
                  this.z = z || 0;
                  this.w = w !== null && w !== void 0 ? w : 1;
                }

                return this;
              };

              _proto.equals = function equals(other, epsilon) {
                if (epsilon === void 0) {
                  epsilon = EPSILON;
                }

                return Math.abs(this.x - other.x) <= epsilon * Math.max(1.0, Math.abs(this.x), Math.abs(other.x)) && Math.abs(this.y - other.y) <= epsilon * Math.max(1.0, Math.abs(this.y), Math.abs(other.y)) && Math.abs(this.z - other.z) <= epsilon * Math.max(1.0, Math.abs(this.z), Math.abs(other.z)) && Math.abs(this.w - other.w) <= epsilon * Math.max(1.0, Math.abs(this.w), Math.abs(other.w));
              };

              _proto.strictEquals = function strictEquals(other) {
                return other && this.x === other.x && this.y === other.y && this.z === other.z && this.w === other.w;
              };

              _proto.getEulerAngles = function getEulerAngles(out) {
                return Quat.toEuler(out, this);
              };

              _proto.lerp = function lerp(to, ratio) {
                this.x += ratio * (to.x - this.x);
                this.y += ratio * (to.y - this.y);
                this.z += ratio * (to.z - this.z);
                this.w += ratio * (to.w - this.w);
                return this;
              };

              _proto.slerp = function slerp(to, ratio) {
                return Quat.slerp(this, this, to, ratio);
              };

              _proto.length = function length() {
                return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
              };

              _proto.lengthSqr = function lengthSqr() {
                return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
              };

              return Quat;
            }(ValueType));
            Quat.IDENTITY = Object.freeze(new Quat());
            var qt_1 = new Quat();
            var qt_2 = new Quat();
            var v3_1$2 = new Vec3();
            var m3_1 = new Mat3();
            var halfToRad = 0.5 * Math.PI / 180.0;
            CCClass.fastDefine('cc.Quat', Quat, {
              x: 0,
              y: 0,
              z: 0,
              w: 1
            });
            legacyCC.Quat = Quat;
            function quat(x, y, z, w) {
              if (x === void 0) {
                x = 0;
              }

              if (y === void 0) {
                y = 0;
              }

              if (z === void 0) {
                z = 0;
              }

              if (w === void 0) {
                w = 1;
              }

              return new Quat(x, y, z, w);
            }
            legacyCC.quat = quat;

            var 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])]);
            var Mat4 = exports('Mat4', function (_ValueType) {
              _inheritsLoose(Mat4, _ValueType);

              Mat4.clone = function clone(a) {
                return new Mat4(a.m00, a.m01, a.m02, a.m03, a.m04, a.m05, a.m06, a.m07, a.m08, a.m09, a.m10, a.m11, a.m12, a.m13, a.m14, a.m15);
              };

              Mat4.copy = function copy(out, a) {
                out.m00 = a.m00;
                out.m01 = a.m01;
                out.m02 = a.m02;
                out.m03 = a.m03;
                out.m04 = a.m04;
                out.m05 = a.m05;
                out.m06 = a.m06;
                out.m07 = a.m07;
                out.m08 = a.m08;
                out.m09 = a.m09;
                out.m10 = a.m10;
                out.m11 = a.m11;
                out.m12 = a.m12;
                out.m13 = a.m13;
                out.m14 = a.m14;
                out.m15 = a.m15;
                return out;
              };

              Mat4.set = function set(out, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {
                out.m00 = m00;
                out.m01 = m01;
                out.m02 = m02;
                out.m03 = m03;
                out.m04 = m10;
                out.m05 = m11;
                out.m06 = m12;
                out.m07 = m13;
                out.m08 = m20;
                out.m09 = m21;
                out.m10 = m22;
                out.m11 = m23;
                out.m12 = m30;
                out.m13 = m31;
                out.m14 = m32;
                out.m15 = m33;
                return out;
              };

              Mat4.identity = function identity(out) {
                out.m00 = 1;
                out.m01 = 0;
                out.m02 = 0;
                out.m03 = 0;
                out.m04 = 0;
                out.m05 = 1;
                out.m06 = 0;
                out.m07 = 0;
                out.m08 = 0;
                out.m09 = 0;
                out.m10 = 1;
                out.m11 = 0;
                out.m12 = 0;
                out.m13 = 0;
                out.m14 = 0;
                out.m15 = 1;
                return out;
              };

              Mat4.transpose = function transpose(out, a) {
                if (out === a) {
                  var a01 = a.m01;
                  var a02 = a.m02;
                  var a03 = a.m03;
                  var a12 = a.m06;
                  var a13 = a.m07;
                  var a23 = a.m11;
                  out.m01 = a.m04;
                  out.m02 = a.m08;
                  out.m03 = a.m12;
                  out.m04 = a01;
                  out.m06 = a.m09;
                  out.m07 = a.m13;
                  out.m08 = a02;
                  out.m09 = a12;
                  out.m11 = a.m14;
                  out.m12 = a03;
                  out.m13 = a13;
                  out.m14 = a23;
                } else {
                  out.m00 = a.m00;
                  out.m01 = a.m04;
                  out.m02 = a.m08;
                  out.m03 = a.m12;
                  out.m04 = a.m01;
                  out.m05 = a.m05;
                  out.m06 = a.m09;
                  out.m07 = a.m13;
                  out.m08 = a.m02;
                  out.m09 = a.m06;
                  out.m10 = a.m10;
                  out.m11 = a.m14;
                  out.m12 = a.m03;
                  out.m13 = a.m07;
                  out.m14 = a.m11;
                  out.m15 = a.m15;
                }

                return out;
              };

              Mat4.invert = function invert(out, a) {
                var a00 = a.m00;
                var a01 = a.m01;
                var a02 = a.m02;
                var a03 = a.m03;
                var a10 = a.m04;
                var a11 = a.m05;
                var a12 = a.m06;
                var a13 = a.m07;
                var a20 = a.m08;
                var a21 = a.m09;
                var a22 = a.m10;
                var a23 = a.m11;
                var a30 = a.m12;
                var a31 = a.m13;
                var a32 = a.m14;
                var a33 = a.m15;
                var b00 = a00 * a11 - a01 * a10;
                var b01 = a00 * a12 - a02 * a10;
                var b02 = a00 * a13 - a03 * a10;
                var b03 = a01 * a12 - a02 * a11;
                var b04 = a01 * a13 - a03 * a11;
                var b05 = a02 * a13 - a03 * a12;
                var b06 = a20 * a31 - a21 * a30;
                var b07 = a20 * a32 - a22 * a30;
                var b08 = a20 * a33 - a23 * a30;
                var b09 = a21 * a32 - a22 * a31;
                var b10 = a21 * a33 - a23 * a31;
                var b11 = a22 * a33 - a23 * a32;
                var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;

                if (det === 0) {
                  out.m00 = 0;
                  out.m01 = 0;
                  out.m02 = 0;
                  out.m03 = 0;
                  out.m04 = 0;
                  out.m05 = 0;
                  out.m06 = 0;
                  out.m07 = 0;
                  out.m08 = 0;
                  out.m09 = 0;
                  out.m10 = 0;
                  out.m11 = 0;
                  out.m12 = 0;
                  out.m13 = 0;
                  out.m14 = 0;
                  out.m15 = 0;
                  return out;
                }

                det = 1.0 / det;
                out.m00 = (a11 * b11 - a12 * b10 + a13 * b09) * det;
                out.m01 = (a02 * b10 - a01 * b11 - a03 * b09) * det;
                out.m02 = (a31 * b05 - a32 * b04 + a33 * b03) * det;
                out.m03 = (a22 * b04 - a21 * b05 - a23 * b03) * det;
                out.m04 = (a12 * b08 - a10 * b11 - a13 * b07) * det;
                out.m05 = (a00 * b11 - a02 * b08 + a03 * b07) * det;
                out.m06 = (a32 * b02 - a30 * b05 - a33 * b01) * det;
                out.m07 = (a20 * b05 - a22 * b02 + a23 * b01) * det;
                out.m08 = (a10 * b10 - a11 * b08 + a13 * b06) * det;
                out.m09 = (a01 * b08 - a00 * b10 - a03 * b06) * det;
                out.m10 = (a30 * b04 - a31 * b02 + a33 * b00) * det;
                out.m11 = (a21 * b02 - a20 * b04 - a23 * b00) * det;
                out.m12 = (a11 * b07 - a10 * b09 - a12 * b06) * det;
                out.m13 = (a00 * b09 - a01 * b07 + a02 * b06) * det;
                out.m14 = (a31 * b01 - a30 * b03 - a32 * b00) * det;
                out.m15 = (a20 * b03 - a21 * b01 + a22 * b00) * det;
                return out;
              };

              Mat4.determinant = function determinant(a) {
                var a00 = a.m00;
                var a01 = a.m01;
                var a02 = a.m02;
                var a03 = a.m03;
                var a10 = a.m04;
                var a11 = a.m05;
                var a12 = a.m06;
                var a13 = a.m07;
                var a20 = a.m08;
                var a21 = a.m09;
                var a22 = a.m10;
                var a23 = a.m11;
                var a30 = a.m12;
                var a31 = a.m13;
                var a32 = a.m14;
                var a33 = a.m15;
                var b00 = a00 * a11 - a01 * a10;
                var b01 = a00 * a12 - a02 * a10;
                var b02 = a00 * a13 - a03 * a10;
                var b03 = a01 * a12 - a02 * a11;
                var b04 = a01 * a13 - a03 * a11;
                var b05 = a02 * a13 - a03 * a12;
                var b06 = a20 * a31 - a21 * a30;
                var b07 = a20 * a32 - a22 * a30;
                var b08 = a20 * a33 - a23 * a30;
                var b09 = a21 * a32 - a22 * a31;
                var b10 = a21 * a33 - a23 * a31;
                var b11 = a22 * a33 - a23 * a32;
                return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
              };

              Mat4.multiply = function multiply(out, a, b) {
                var a00 = a.m00;
                var a01 = a.m01;
                var a02 = a.m02;
                var a03 = a.m03;
                var a10 = a.m04;
                var a11 = a.m05;
                var a12 = a.m06;
                var a13 = a.m07;
                var a20 = a.m08;
                var a21 = a.m09;
                var a22 = a.m10;
                var a23 = a.m11;
                var a30 = a.m12;
                var a31 = a.m13;
                var a32 = a.m14;
                var a33 = a.m15;
                var b0 = b.m00;
                var b1 = b.m01;
                var b2 = b.m02;
                var b3 = b.m03;
                out.m00 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
                out.m01 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
                out.m02 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
                out.m03 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
                b0 = b.m04;
                b1 = b.m05;
                b2 = b.m06;
                b3 = b.m07;
                out.m04 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
                out.m05 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
                out.m06 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
                out.m07 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
                b0 = b.m08;
                b1 = b.m09;
                b2 = b.m10;
                b3 = b.m11;
                out.m08 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
                out.m09 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
                out.m10 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
                out.m11 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
                b0 = b.m12;
                b1 = b.m13;
                b2 = b.m14;
                b3 = b.m15;
                out.m12 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
                out.m13 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
                out.m14 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
                out.m15 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
                return out;
              };

              Mat4.transform = function transform(out, a, v) {
                var x = v.x;
                var y = v.y;
                var z = v.z;

                if (a === out) {
                  out.m12 = a.m00 * x + a.m04 * y + a.m08 * z + a.m12;
                  out.m13 = a.m01 * x + a.m05 * y + a.m09 * z + a.m13;
                  out.m14 = a.m02 * x + a.m06 * y + a.m10 * z + a.m14;
                  out.m15 = a.m03 * x + a.m07 * y + a.m11 * z + a.m15;
                } else {
                  var a00 = a.m00;
                  var a01 = a.m01;
                  var a02 = a.m02;
                  var a03 = a.m03;
                  var a10 = a.m04;
                  var a11 = a.m05;
                  var a12 = a.m06;
                  var a13 = a.m07;
                  var a20 = a.m08;
                  var a21 = a.m09;
                  var a22 = a.m10;
                  var a23 = a.m11;
                  var a30 = a.m12;
                  var a31 = a.m13;
                  var a32 = a.m14;
                  var a33 = a.m15;
                  out.m00 = a00;
                  out.m01 = a01;
                  out.m02 = a02;
                  out.m03 = a03;
                  out.m04 = a10;
                  out.m05 = a11;
                  out.m06 = a12;
                  out.m07 = a13;
                  out.m08 = a20;
                  out.m09 = a21;
                  out.m10 = a22;
                  out.m11 = a23;
                  out.m12 = a00 * x + a10 * y + a20 * z + a.m12;
                  out.m13 = a01 * x + a11 * y + a21 * z + a.m13;
                  out.m14 = a02 * x + a12 * y + a22 * z + a.m14;
                  out.m15 = a03 * x + a13 * y + a23 * z + a.m15;
                }

                return out;
              };

              Mat4.translate = function translate(out, a, v) {
                console.warn('function changed');

                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 += v.x;
                  out.m13 += v.y;
                  out.m14 += v.z;
                  out.m15 = a.m15;
                }

                return out;
              };

              Mat4.scale = function scale(out, a, v) {
                var x = v.x;
                var y = v.y;
                var z = v.z;
                out.m00 = a.m00 * x;
                out.m01 = a.m01 * x;
                out.m02 = a.m02 * x;
                out.m03 = a.m03 * x;
                out.m04 = a.m04 * y;
                out.m05 = a.m05 * y;
                out.m06 = a.m06 * y;
                out.m07 = a.m07 * y;
                out.m08 = a.m08 * z;
                out.m09 = a.m09 * z;
                out.m10 = a.m10 * z;
                out.m11 = a.m11 * z;
                out.m12 = a.m12;
                out.m13 = a.m13;
                out.m14 = a.m14;
                out.m15 = a.m15;
                return out;
              };

              Mat4.rotate = function rotate(out, a, rad, axis) {
                var x = axis.x;
                var y = axis.y;
                var z = axis.z;
                var len = Math.sqrt(x * x + y * y + z * z);

                if (Math.abs(len) < EPSILON) {
                  return null;
                }

                len = 1 / len;
                x *= len;
                y *= len;
                z *= len;
                var s = Math.sin(rad);
                var c = Math.cos(rad);
                var t = 1 - c;
                var a00 = a.m00;
                var a01 = a.m01;
                var a02 = a.m02;
                var a03 = a.m03;
                var a10 = a.m04;
                var a11 = a.m05;
                var a12 = a.m06;
                var a13 = a.m07;
                var a20 = a.m08;
                var a21 = a.m09;
                var a22 = a.m10;
                var a23 = a.m11;
                var b00 = x * x * t + c;
                var b01 = y * x * t + z * s;
                var b02 = z * x * t - y * s;
                var b10 = x * y * t - z * s;
                var b11 = y * y * t + c;
                var b12 = z * y * t + x * s;
                var b20 = x * z * t + y * s;
                var b21 = y * z * t - x * s;
                var b22 = z * z * t + c;
                out.m00 = a00 * b00 + a10 * b01 + a20 * b02;
                out.m01 = a01 * b00 + a11 * b01 + a21 * b02;
                out.m02 = a02 * b00 + a12 * b01 + a22 * b02;
                out.m03 = a03 * b00 + a13 * b01 + a23 * b02;
                out.m04 = a00 * b10 + a10 * b11 + a20 * b12;
                out.m05 = a01 * b10 + a11 * b11 + a21 * b12;
                out.m06 = a02 * b10 + a12 * b11 + a22 * b12;
                out.m07 = a03 * b10 + a13 * b11 + a23 * b12;
                out.m08 = a00 * b20 + a10 * b21 + a20 * b22;
                out.m09 = a01 * b20 + a11 * b21 + a21 * b22;
                out.m10 = a02 * b20 + a12 * b21 + a22 * b22;
                out.m11 = a03 * b20 + a13 * b21 + a23 * b22;

                if (a !== out) {
                  out.m12 = a.m12;
                  out.m13 = a.m13;
                  out.m14 = a.m14;
                  out.m15 = a.m15;
                }

                return out;
              };

              Mat4.rotateX = function rotateX(out, a, rad) {
                var s = Math.sin(rad);
                var c = Math.cos(rad);
                var a10 = a.m04;
                var a11 = a.m05;
                var a12 = a.m06;
                var a13 = a.m07;
                var a20 = a.m08;
                var a21 = a.m09;
                var a22 = a.m10;
                var a23 = a.m11;

                if (a !== out) {
                  out.m00 = a.m00;
                  out.m01 = a.m01;
                  out.m02 = a.m02;
                  out.m03 = a.m03;
                  out.m12 = a.m12;
                  out.m13 = a.m13;
                  out.m14 = a.m14;
                  out.m15 = a.m15;
                }

                out.m04 = a10 * c + a20 * s;
                out.m05 = a11 * c + a21 * s;
                out.m06 = a12 * c + a22 * s;
                out.m07 = a13 * c + a23 * s;
                out.m08 = a20 * c - a10 * s;
                out.m09 = a21 * c - a11 * s;
                out.m10 = a22 * c - a12 * s;
                out.m11 = a23 * c - a13 * s;
                return out;
              };

              Mat4.rotateY = function rotateY(out, a, rad) {
                var s = Math.sin(rad);
                var c = Math.cos(rad);
                var a00 = a.m00;
                var a01 = a.m01;
                var a02 = a.m02;
                var a03 = a.m03;
                var a20 = a.m08;
                var a21 = a.m09;
                var a22 = a.m10;
                var a23 = a.m11;

                if (a !== out) {
                  out.m04 = a.m04;
                  out.m05 = a.m05;
                  out.m06 = a.m06;
                  out.m07 = a.m07;
                  out.m12 = a.m12;
                  out.m13 = a.m13;
                  out.m14 = a.m14;
                  out.m15 = a.m15;
                }

                out.m00 = a00 * c - a20 * s;
                out.m01 = a01 * c - a21 * s;
                out.m02 = a02 * c - a22 * s;
                out.m03 = a03 * c - a23 * s;
                out.m08 = a00 * s + a20 * c;
                out.m09 = a01 * s + a21 * c;
                out.m10 = a02 * s + a22 * c;
                out.m11 = a03 * s + a23 * c;
                return out;
              };

              Mat4.rotateZ = function rotateZ(out, a, rad) {
                var s = Math.sin(rad);
                var c = Math.cos(rad);
                var a00 = a.m00;
                var a01 = a.m01;
                var a02 = a.m02;
                var a03 = a.m03;
                var a10 = a.m04;
                var a11 = a.m05;
                var a12 = a.m06;
                var a13 = a.m07;

                if (a !== out) {
                  out.m08 = a.m08;
                  out.m09 = a.m09;
                  out.m10 = a.m10;
                  out.m11 = a.m11;
                  out.m12 = a.m12;
                  out.m13 = a.m13;
                  out.m14 = a.m14;
                  out.m15 = a.m15;
                }

                out.m00 = a00 * c + a10 * s;
                out.m01 = a01 * c + a11 * s;
                out.m02 = a02 * c + a12 * s;
                out.m03 = a03 * c + a13 * s;
                out.m04 = a10 * c - a00 * s;
                out.m05 = a11 * c - a01 * s;
                out.m06 = a12 * c - a02 * s;
                out.m07 = a13 * c - a03 * s;
                return out;
              };

              Mat4.fromTranslation = function fromTranslation(out, v) {
                out.m00 = 1;
                out.m01 = 0;
                out.m02 = 0;
                out.m03 = 0;
                out.m04 = 0;
                out.m05 = 1;
                out.m06 = 0;
                out.m07 = 0;
                out.m08 = 0;
                out.m09 = 0;
                out.m10 = 1;
                out.m11 = 0;
                out.m12 = v.x;
                out.m13 = v.y;
                out.m14 = v.z;
                out.m15 = 1;
                return out;
              };

              Mat4.fromScaling = function fromScaling(out, v) {
                out.m00 = v.x;
                out.m01 = 0;
                out.m02 = 0;
                out.m03 = 0;
                out.m04 = 0;
                out.m05 = v.y;
                out.m06 = 0;
                out.m07 = 0;
                out.m08 = 0;
                out.m09 = 0;
                out.m10 = v.z;
                out.m11 = 0;
                out.m12 = 0;
                out.m13 = 0;
                out.m14 = 0;
                out.m15 = 1;
                return out;
              };

              Mat4.fromRotation = function fromRotation(out, rad, axis) {
                var x = axis.x;
                var y = axis.y;
                var z = axis.z;
                var len = Math.sqrt(x * x + y * y + z * z);

                if (Math.abs(len) < EPSILON) {
                  return null;
                }

                len = 1 / len;
                x *= len;
                y *= len;
                z *= len;
                var s = Math.sin(rad);
                var c = Math.cos(rad);
                var t = 1 - c;
                out.m00 = x * x * t + c;
                out.m01 = y * x * t + z * s;
                out.m02 = z * x * t - y * s;
                out.m03 = 0;
                out.m04 = x * y * t - z * s;
                out.m05 = y * y * t + c;
                out.m06 = z * y * t + x * s;
                out.m07 = 0;
                out.m08 = x * z * t + y * s;
                out.m09 = y * z * t - x * s;
                out.m10 = z * z * t + c;
                out.m11 = 0;
                out.m12 = 0;
                out.m13 = 0;
                out.m14 = 0;
                out.m15 = 1;
                return out;
              };

              Mat4.fromXRotation = function fromXRotation(out, rad) {
                var s = Math.sin(rad);
                var c = Math.cos(rad);
                out.m00 = 1;
                out.m01 = 0;
                out.m02 = 0;
                out.m03 = 0;
                out.m04 = 0;
                out.m05 = c;
                out.m06 = s;
                out.m07 = 0;
                out.m08 = 0;
                out.m09 = -s;
                out.m10 = c;
                out.m11 = 0;
                out.m12 = 0;
                out.m13 = 0;
                out.m14 = 0;
                out.m15 = 1;
                return out;
              };

              Mat4.fromYRotation = function fromYRotation(out, rad) {
                var s = Math.sin(rad);
                var c = Math.cos(rad);
                out.m00 = c;
                out.m01 = 0;
                out.m02 = -s;
                out.m03 = 0;
                out.m04 = 0;
                out.m05 = 1;
                out.m06 = 0;
                out.m07 = 0;
                out.m08 = s;
                out.m09 = 0;
                out.m10 = c;
                out.m11 = 0;
                out.m12 = 0;
                out.m13 = 0;
                out.m14 = 0;
                out.m15 = 1;
                return out;
              };

              Mat4.fromZRotation = function fromZRotation(out, rad) {
                var s = Math.sin(rad);
                var c = Math.cos(rad);
                out.m00 = c;
                out.m01 = s;
                out.m02 = 0;
                out.m03 = 0;
                out.m04 = -s;
                out.m05 = c;
                out.m06 = 0;
                out.m07 = 0;
                out.m08 = 0;
                out.m09 = 0;
                out.m10 = 1;
                out.m11 = 0;
                out.m12 = 0;
                out.m13 = 0;
                out.m14 = 0;
                out.m15 = 1;
                return out;
              };

              Mat4.fromRT = function fromRT(out, q, v) {
                var x = q.x;
                var y = q.y;
                var z = q.z;
                var w = q.w;
                var x2 = x + x;
                var y2 = y + y;
                var z2 = z + z;
                var xx = x * x2;
                var xy = x * y2;
                var xz = x * z2;
                var yy = y * y2;
                var yz = y * z2;
                var zz = z * z2;
                var wx = w * x2;
                var wy = w * y2;
                var wz = w * z2;
                out.m00 = 1 - (yy + zz);
                out.m01 = xy + wz;
                out.m02 = xz - wy;
                out.m03 = 0;
                out.m04 = xy - wz;
                out.m05 = 1 - (xx + zz);
                out.m06 = yz + wx;
                out.m07 = 0;
                out.m08 = xz + wy;
                out.m09 = yz - wx;
                out.m10 = 1 - (xx + yy);
                out.m11 = 0;
                out.m12 = v.x;
                out.m13 = v.y;
                out.m14 = v.z;
                out.m15 = 1;
                return out;
              };

              Mat4.getTranslation = function getTranslation(out, mat) {
                out.x = mat.m12;
                out.y = mat.m13;
                out.z = mat.m14;
                return out;
              };

              Mat4.getScaling = function getScaling(out, mat) {
                var m00 = m3_1$1.m00 = mat.m00;
                var m01 = m3_1$1.m01 = mat.m01;
                var m02 = m3_1$1.m02 = mat.m02;
                var m04 = m3_1$1.m03 = mat.m04;
                var m05 = m3_1$1.m04 = mat.m05;
                var m06 = m3_1$1.m05 = mat.m06;
                var m08 = m3_1$1.m06 = mat.m08;
                var m09 = m3_1$1.m07 = mat.m09;
                var m10 = m3_1$1.m08 = mat.m10;
                out.x = Math.sqrt(m00 * m00 + m01 * m01 + m02 * m02);
                out.y = Math.sqrt(m04 * m04 + m05 * m05 + m06 * m06);
                out.z = Math.sqrt(m08 * m08 + m09 * m09 + m10 * m10);

                if (Mat3.determinant(m3_1$1) < 0) {
                  out.x *= -1;
                }

                return out;
              };

              Mat4.getRotation = function getRotation(out, mat) {
                var trace = mat.m00 + mat.m05 + mat.m10;
                var S = 0;

                if (trace > 0) {
                  S = Math.sqrt(trace + 1.0) * 2;
                  out.w = 0.25 * S;
                  out.x = (mat.m06 - mat.m09) / S;
                  out.y = (mat.m08 - mat.m02) / S;
                  out.z = (mat.m01 - mat.m04) / S;
                } else if (mat.m00 > mat.m05 && mat.m00 > mat.m10) {
                  S = Math.sqrt(1.0 + mat.m00 - mat.m05 - mat.m10) * 2;
                  out.w = (mat.m06 - mat.m09) / S;
                  out.x = 0.25 * S;
                  out.y = (mat.m01 + mat.m04) / S;
                  out.z = (mat.m08 + mat.m02) / S;
                } else if (mat.m05 > mat.m10) {
                  S = Math.sqrt(1.0 + mat.m05 - mat.m00 - mat.m10) * 2;
                  out.w = (mat.m08 - mat.m02) / S;
                  out.x = (mat.m01 + mat.m04) / S;
                  out.y = 0.25 * S;
                  out.z = (mat.m06 + mat.m09) / S;
                } else {
                  S = Math.sqrt(1.0 + mat.m10 - mat.m00 - mat.m05) * 2;
                  out.w = (mat.m01 - mat.m04) / S;
                  out.x = (mat.m08 + mat.m02) / S;
                  out.y = (mat.m06 + mat.m09) / S;
                  out.z = 0.25 * S;
                }

                return out;
              };

              Mat4.toRTS = function toRTS(m, q, v, s) {
                s.x = Vec3.set(v3_1$3, m.m00, m.m01, m.m02).length();
                m3_1$1.m00 = m.m00 / s.x;
                m3_1$1.m01 = m.m01 / s.x;
                m3_1$1.m02 = m.m02 / s.x;
                s.y = Vec3.set(v3_1$3, m.m04, m.m05, m.m06).length();
                m3_1$1.m03 = m.m04 / s.y;
                m3_1$1.m04 = m.m05 / s.y;
                m3_1$1.m05 = m.m06 / s.y;
                s.z = Vec3.set(v3_1$3, m.m08, m.m09, m.m10).length();
                m3_1$1.m06 = m.m08 / s.z;
                m3_1$1.m07 = m.m09 / s.z;
                m3_1$1.m08 = m.m10 / s.z;
                var det = Mat3.determinant(m3_1$1);

                if (det < 0) {
                  s.x *= -1;
                  m3_1$1.m00 *= -1;
                  m3_1$1.m01 *= -1;
                  m3_1$1.m02 *= -1;
                }

                Quat.fromMat3(q, m3_1$1);
                Vec3.set(v, m.m12, m.m13, m.m14);
              };

              Mat4.fromRTS = function fromRTS(out, q, v, s) {
                var x = q.x;
                var y = q.y;
                var z = q.z;
                var w = q.w;
                var x2 = x + x;
                var y2 = y + y;
                var z2 = z + z;
                var xx = x * x2;
                var xy = x * y2;
                var xz = x * z2;
                var yy = y * y2;
                var yz = y * z2;
                var zz = z * z2;
                var wx = w * x2;
                var wy = w * y2;
                var wz = w * z2;
                var sx = s.x;
                var sy = s.y;
                var sz = s.z;
                out.m00 = (1 - (yy + zz)) * sx;
                out.m01 = (xy + wz) * sx;
                out.m02 = (xz - wy) * sx;
                out.m03 = 0;
                out.m04 = (xy - wz) * sy;
                out.m05 = (1 - (xx + zz)) * sy;
                out.m06 = (yz + wx) * sy;
                out.m07 = 0;
                out.m08 = (xz + wy) * sz;
                out.m09 = (yz - wx) * sz;
                out.m10 = (1 - (xx + yy)) * sz;
                out.m11 = 0;
                out.m12 = v.x;
                out.m13 = v.y;
                out.m14 = v.z;
                out.m15 = 1;
                return out;
              };

              Mat4.fromRTSOrigin = function fromRTSOrigin(out, q, v, s, o) {
                var x = q.x;
                var y = q.y;
                var z = q.z;
                var w = q.w;
                var x2 = x + x;
                var y2 = y + y;
                var z2 = z + z;
                var xx = x * x2;
                var xy = x * y2;
                var xz = x * z2;
                var yy = y * y2;
                var yz = y * z2;
                var zz = z * z2;
                var wx = w * x2;
                var wy = w * y2;
                var wz = w * z2;
                var sx = s.x;
                var sy = s.y;
                var sz = s.z;
                var ox = o.x;
                var oy = o.y;
                var oz = o.z;
                out.m00 = (1 - (yy + zz)) * sx;
                out.m01 = (xy + wz) * sx;
                out.m02 = (xz - wy) * sx;
                out.m03 = 0;
                out.m04 = (xy - wz) * sy;
                out.m05 = (1 - (xx + zz)) * sy;
                out.m06 = (yz + wx) * sy;
                out.m07 = 0;
                out.m08 = (xz + wy) * sz;
                out.m09 = (yz - wx) * sz;
                out.m10 = (1 - (xx + yy)) * sz;
                out.m11 = 0;
                out.m12 = v.x + ox - (out.m00 * ox + out.m04 * oy + out.m08 * oz);
                out.m13 = v.y + oy - (out.m01 * ox + out.m05 * oy + out.m09 * oz);
                out.m14 = v.z + oz - (out.m02 * ox + out.m06 * oy + out.m10 * oz);
                out.m15 = 1;
                return out;
              };

              Mat4.fromQuat = function fromQuat(out, q) {
                var x = q.x;
                var y = q.y;
                var z = q.z;
                var w = q.w;
                var x2 = x + x;
                var y2 = y + y;
                var z2 = z + z;
                var xx = x * x2;
                var yx = y * x2;
                var yy = y * y2;
                var zx = z * x2;
                var zy = z * y2;
                var zz = z * z2;
                var wx = w * x2;
                var wy = w * y2;
                var wz = w * z2;
                out.m00 = 1 - yy - zz;
                out.m01 = yx + wz;
                out.m02 = zx - wy;
                out.m03 = 0;
                out.m04 = yx - wz;
                out.m05 = 1 - xx - zz;
                out.m06 = zy + wx;
                out.m07 = 0;
                out.m08 = zx + wy;
                out.m09 = zy - wx;
                out.m10 = 1 - xx - yy;
                out.m11 = 0;
                out.m12 = 0;
                out.m13 = 0;
                out.m14 = 0;
                out.m15 = 1;
                return out;
              };

              Mat4.frustum = function frustum(out, left, right, bottom, top, near, far) {
                var rl = 1 / (right - left);
                var tb = 1 / (top - bottom);
                var nf = 1 / (near - far);
                out.m00 = near * 2 * rl;
                out.m01 = 0;
                out.m02 = 0;
                out.m03 = 0;
                out.m04 = 0;
                out.m05 = near * 2 * tb;
                out.m06 = 0;
                out.m07 = 0;
                out.m08 = (right + left) * rl;
                out.m09 = (top + bottom) * tb;
                out.m10 = (far + near) * nf;
                out.m11 = -1;
                out.m12 = 0;
                out.m13 = 0;
                out.m14 = far * near * 2 * nf;
                out.m15 = 0;
                return out;
              };

              Mat4.perspective = function perspective(out, fov, aspect, near, far, isFOVY, minClipZ, projectionSignY, orientation) {
                if (isFOVY === void 0) {
                  isFOVY = true;
                }

                if (minClipZ === void 0) {
                  minClipZ = -1;
                }

                if (projectionSignY === void 0) {
                  projectionSignY = 1;
                }

                if (orientation === void 0) {
                  orientation = 0;
                }

                var f = 1.0 / Math.tan(fov / 2);
                var nf = 1 / (near - far);
                var x = isFOVY ? f / aspect : f;
                var y = (isFOVY ? f : f * aspect) * projectionSignY;
                var preTransform = preTransforms[orientation];
                out.m00 = x * preTransform[0];
                out.m01 = x * preTransform[1];
                out.m02 = 0;
                out.m03 = 0;
                out.m04 = y * preTransform[2];
                out.m05 = y * preTransform[3];
                out.m06 = 0;
                out.m07 = 0;
                out.m08 = 0;
                out.m09 = 0;
                out.m10 = (far - minClipZ * near) * nf;
                out.m11 = -1;
                out.m12 = 0;
                out.m13 = 0;
                out.m14 = far * near * nf * (1 - minClipZ);
                out.m15 = 0;
                return out;
              };

              Mat4.ortho = function ortho(out, left, right, bottom, top, near, far, minClipZ, projectionSignY, orientation) {
                if (minClipZ === void 0) {
                  minClipZ = -1;
                }

                if (projectionSignY === void 0) {
                  projectionSignY = 1;
                }

                if (orientation === void 0) {
                  orientation = 0;
                }

                var lr = 1 / (left - right);
                var bt = 1 / (bottom - top) * projectionSignY;
                var nf = 1 / (near - far);
                var x = -2 * lr;
                var y = -2 * bt;
                var dx = (left + right) * lr;
                var dy = (top + bottom) * bt;
                var preTransform = preTransforms[orientation];
                out.m00 = x * preTransform[0];
                out.m01 = x * preTransform[1];
                out.m02 = 0;
                out.m03 = 0;
                out.m04 = y * preTransform[2];
                out.m05 = y * preTransform[3];
                out.m06 = 0;
                out.m07 = 0;
                out.m08 = 0;
                out.m09 = 0;
                out.m10 = nf * (1 - minClipZ);
                out.m11 = 0;
                out.m12 = dx * preTransform[0] + dy * preTransform[2];
                out.m13 = dx * preTransform[1] + dy * preTransform[3];
                out.m14 = (near - minClipZ * far) * nf;
                out.m15 = 1;
                return out;
              };

              Mat4.lookAt = function lookAt(out, eye, center, up) {
                var eyex = eye.x;
                var eyey = eye.y;
                var eyez = eye.z;
                var upx = up.x;
                var upy = up.y;
                var upz = up.z;
                var centerx = center.x;
                var centery = center.y;
                var centerz = center.z;
                var z0 = eyex - centerx;
                var z1 = eyey - centery;
                var z2 = eyez - centerz;
                var len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2);
                z0 *= len;
                z1 *= len;
                z2 *= len;
                var x0 = upy * z2 - upz * z1;
                var x1 = upz * z0 - upx * z2;
                var x2 = upx * z1 - upy * z0;
                len = 1 / Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2);
                x0 *= len;
                x1 *= len;
                x2 *= len;
                var y0 = z1 * x2 - z2 * x1;
                var y1 = z2 * x0 - z0 * x2;
                var y2 = z0 * x1 - z1 * x0;
                out.m00 = x0;
                out.m01 = y0;
                out.m02 = z0;
                out.m03 = 0;
                out.m04 = x1;
                out.m05 = y1;
                out.m06 = z1;
                out.m07 = 0;
                out.m08 = x2;
                out.m09 = y2;
                out.m10 = z2;
                out.m11 = 0;
                out.m12 = -(x0 * eyex + x1 * eyey + x2 * eyez);
                out.m13 = -(y0 * eyex + y1 * eyey + y2 * eyez);
                out.m14 = -(z0 * eyex + z1 * eyey + z2 * eyez);
                out.m15 = 1;
                return out;
              };

              Mat4.inverseTranspose = function inverseTranspose(out, a) {
                var a00 = a.m00;
                var a01 = a.m01;
                var a02 = a.m02;
                var a03 = a.m03;
                var a10 = a.m04;
                var a11 = a.m05;
                var a12 = a.m06;
                var a13 = a.m07;
                var a20 = a.m08;
                var a21 = a.m09;
                var a22 = a.m10;
                var a23 = a.m11;
                var a30 = a.m12;
                var a31 = a.m13;
                var a32 = a.m14;
                var a33 = a.m15;
                var b00 = a00 * a11 - a01 * a10;
                var b01 = a00 * a12 - a02 * a10;
                var b02 = a00 * a13 - a03 * a10;
                var b03 = a01 * a12 - a02 * a11;
                var b04 = a01 * a13 - a03 * a11;
                var b05 = a02 * a13 - a03 * a12;
                var b06 = a20 * a31 - a21 * a30;
                var b07 = a20 * a32 - a22 * a30;
                var b08 = a20 * a33 - a23 * a30;
                var b09 = a21 * a32 - a22 * a31;
                var b10 = a21 * a33 - a23 * a31;
                var b11 = a22 * a33 - a23 * a32;
                var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;

                if (!det) {
                  return null;
                }

                det = 1.0 / det;
                out.m00 = (a11 * b11 - a12 * b10 + a13 * b09) * det;
                out.m01 = (a12 * b08 - a10 * b11 - a13 * b07) * det;
                out.m02 = (a10 * b10 - a11 * b08 + a13 * b06) * det;
                out.m03 = 0;
                out.m04 = (a02 * b10 - a01 * b11 - a03 * b09) * det;
                out.m05 = (a00 * b11 - a02 * b08 + a03 * b07) * det;
                out.m06 = (a01 * b08 - a00 * b10 - a03 * b06) * det;
                out.m07 = 0;
                out.m08 = (a31 * b05 - a32 * b04 + a33 * b03) * det;
                out.m09 = (a32 * b02 - a30 * b05 - a33 * b01) * det;
                out.m10 = (a30 * b04 - a31 * b02 + a33 * b00) * det;
                out.m11 = 0;
                out.m12 = 0;
                out.m13 = 0;
                out.m14 = 0;
                out.m15 = 1;
                return out;
              };

              Mat4.toArray = function toArray(out, m, ofs) {
                if (ofs === void 0) {
                  ofs = 0;
                }

                out[ofs + 0] = m.m00;
                out[ofs + 1] = m.m01;
                out[ofs + 2] = m.m02;
                out[ofs + 3] = m.m03;
                out[ofs + 4] = m.m04;
                out[ofs + 5] = m.m05;
                out[ofs + 6] = m.m06;
                out[ofs + 7] = m.m07;
                out[ofs + 8] = m.m08;
                out[ofs + 9] = m.m09;
                out[ofs + 10] = m.m10;
                out[ofs + 11] = m.m11;
                out[ofs + 12] = m.m12;
                out[ofs + 13] = m.m13;
                out[ofs + 14] = m.m14;
                out[ofs + 15] = m.m15;
                return out;
              };

              Mat4.fromArray = function fromArray(out, arr, ofs) {
                if (ofs === void 0) {
                  ofs = 0;
                }

                out.m00 = arr[ofs + 0];
                out.m01 = arr[ofs + 1];
                out.m02 = arr[ofs + 2];
                out.m03 = arr[ofs + 3];
                out.m04 = arr[ofs + 4];
                out.m05 = arr[ofs + 5];
                out.m06 = arr[ofs + 6];
                out.m07 = arr[ofs + 7];
                out.m08 = arr[ofs + 8];
                out.m09 = arr[ofs + 9];
                out.m10 = arr[ofs + 10];
                out.m11 = arr[ofs + 11];
                out.m12 = arr[ofs + 12];
                out.m13 = arr[ofs + 13];
                out.m14 = arr[ofs + 14];
                out.m15 = arr[ofs + 15];
                return out;
              };

              Mat4.add = function add(out, a, b) {
                out.m00 = a.m00 + b.m00;
                out.m01 = a.m01 + b.m01;
                out.m02 = a.m02 + b.m02;
                out.m03 = a.m03 + b.m03;
                out.m04 = a.m04 + b.m04;
                out.m05 = a.m05 + b.m05;
                out.m06 = a.m06 + b.m06;
                out.m07 = a.m07 + b.m07;
                out.m08 = a.m08 + b.m08;
                out.m09 = a.m09 + b.m09;
                out.m10 = a.m10 + b.m10;
                out.m11 = a.m11 + b.m11;
                out.m12 = a.m12 + b.m12;
                out.m13 = a.m13 + b.m13;
                out.m14 = a.m14 + b.m14;
                out.m15 = a.m15 + b.m15;
                return out;
              };

              Mat4.subtract = function subtract(out, a, b) {
                out.m00 = a.m00 - b.m00;
                out.m01 = a.m01 - b.m01;
                out.m02 = a.m02 - b.m02;
                out.m03 = a.m03 - b.m03;
                out.m04 = a.m04 - b.m04;
                out.m05 = a.m05 - b.m05;
                out.m06 = a.m06 - b.m06;
                out.m07 = a.m07 - b.m07;
                out.m08 = a.m08 - b.m08;
                out.m09 = a.m09 - b.m09;
                out.m10 = a.m10 - b.m10;
                out.m11 = a.m11 - b.m11;
                out.m12 = a.m12 - b.m12;
                out.m13 = a.m13 - b.m13;
                out.m14 = a.m14 - b.m14;
                out.m15 = a.m15 - b.m15;
                return out;
              };

              Mat4.multiplyScalar = function multiplyScalar(out, a, b) {
                out.m00 = a.m00 * b;
                out.m01 = a.m01 * b;
                out.m02 = a.m02 * b;
                out.m03 = a.m03 * b;
                out.m04 = a.m04 * b;
                out.m05 = a.m05 * b;
                out.m06 = a.m06 * b;
                out.m07 = a.m07 * b;
                out.m08 = a.m08 * b;
                out.m09 = a.m09 * b;
                out.m10 = a.m10 * b;
                out.m11 = a.m11 * b;
                out.m12 = a.m12 * b;
                out.m13 = a.m13 * b;
                out.m14 = a.m14 * b;
                out.m15 = a.m15 * b;
                return out;
              };

              Mat4.multiplyScalarAndAdd = function multiplyScalarAndAdd(out, a, b, scale) {
                out.m00 = a.m00 + b.m00 * scale;
                out.m01 = a.m01 + b.m01 * scale;
                out.m02 = a.m02 + b.m02 * scale;
                out.m03 = a.m03 + b.m03 * scale;
                out.m04 = a.m04 + b.m04 * scale;
                out.m05 = a.m05 + b.m05 * scale;
                out.m06 = a.m06 + b.m06 * scale;
                out.m07 = a.m07 + b.m07 * scale;
                out.m08 = a.m08 + b.m08 * scale;
                out.m09 = a.m09 + b.m09 * scale;
                out.m10 = a.m10 + b.m10 * scale;
                out.m11 = a.m11 + b.m11 * scale;
                out.m12 = a.m12 + b.m12 * scale;
                out.m13 = a.m13 + b.m13 * scale;
                out.m14 = a.m14 + b.m14 * scale;
                out.m15 = a.m15 + b.m15 * scale;
                return out;
              };

              Mat4.strictEquals = function strictEquals(a, b) {
                return a.m00 === b.m00 && a.m01 === b.m01 && a.m02 === b.m02 && a.m03 === b.m03 && a.m04 === b.m04 && a.m05 === b.m05 && a.m06 === b.m06 && a.m07 === b.m07 && a.m08 === b.m08 && a.m09 === b.m09 && a.m10 === b.m10 && a.m11 === b.m11 && a.m12 === b.m12 && a.m13 === b.m13 && a.m14 === b.m14 && a.m15 === b.m15;
              };

              Mat4.equals = function equals(a, b, epsilon) {
                if (epsilon === void 0) {
                  epsilon = EPSILON;
                }

                return Math.abs(a.m00 - b.m00) <= epsilon * Math.max(1.0, Math.abs(a.m00), Math.abs(b.m00)) && Math.abs(a.m01 - b.m01) <= epsilon * Math.max(1.0, Math.abs(a.m01), Math.abs(b.m01)) && Math.abs(a.m02 - b.m02) <= epsilon * Math.max(1.0, Math.abs(a.m02), Math.abs(b.m02)) && Math.abs(a.m03 - b.m03) <= epsilon * Math.max(1.0, Math.abs(a.m03), Math.abs(b.m03)) && Math.abs(a.m04 - b.m04) <= epsilon * Math.max(1.0, Math.abs(a.m04), Math.abs(b.m04)) && Math.abs(a.m05 - b.m05) <= epsilon * Math.max(1.0, Math.abs(a.m05), Math.abs(b.m05)) && Math.abs(a.m06 - b.m06) <= epsilon * Math.max(1.0, Math.abs(a.m06), Math.abs(b.m06)) && Math.abs(a.m07 - b.m07) <= epsilon * Math.max(1.0, Math.abs(a.m07), Math.abs(b.m07)) && Math.abs(a.m08 - b.m08) <= epsilon * Math.max(1.0, Math.abs(a.m08), Math.abs(b.m08)) && Math.abs(a.m09 - b.m09) <= epsilon * Math.max(1.0, Math.abs(a.m09), Math.abs(b.m09)) && Math.abs(a.m10 - b.m10) <= epsilon * Math.max(1.0, Math.abs(a.m10), Math.abs(b.m10)) && Math.abs(a.m11 - b.m11) <= epsilon * Math.max(1.0, Math.abs(a.m11), Math.abs(b.m11)) && Math.abs(a.m12 - b.m12) <= epsilon * Math.max(1.0, Math.abs(a.m12), Math.abs(b.m12)) && Math.abs(a.m13 - b.m13) <= epsilon * Math.max(1.0, Math.abs(a.m13), Math.abs(b.m13)) && Math.abs(a.m14 - b.m14) <= epsilon * Math.max(1.0, Math.abs(a.m14), Math.abs(b.m14)) && Math.abs(a.m15 - b.m15) <= epsilon * Math.max(1.0, Math.abs(a.m15), Math.abs(b.m15));
              };

              function Mat4(m00, m01, m02, m03, m04, m05, m06, m07, m08, m09, m10, m11, m12, m13, m14, m15) {
                var _this;

                if (m00 === void 0) {
                  m00 = 1;
                }

                if (m01 === void 0) {
                  m01 = 0;
                }

                if (m02 === void 0) {
                  m02 = 0;
                }

                if (m03 === void 0) {
                  m03 = 0;
                }

                if (m04 === void 0) {
                  m04 = 0;
                }

                if (m05 === void 0) {
                  m05 = 1;
                }

                if (m06 === void 0) {
                  m06 = 0;
                }

                if (m07 === void 0) {
                  m07 = 0;
                }

                if (m08 === void 0) {
                  m08 = 0;
                }

                if (m09 === void 0) {
                  m09 = 0;
                }

                if (m10 === void 0) {
                  m10 = 1;
                }

                if (m11 === void 0) {
                  m11 = 0;
                }

                if (m12 === void 0) {
                  m12 = 0;
                }

                if (m13 === void 0) {
                  m13 = 0;
                }

                if (m14 === void 0) {
                  m14 = 0;
                }

                if (m15 === void 0) {
                  m15 = 1;
                }

                _this = _ValueType.call(this) || this;
                _this.m00 = void 0;
                _this.m01 = void 0;
                _this.m02 = void 0;
                _this.m03 = void 0;
                _this.m04 = void 0;
                _this.m05 = void 0;
                _this.m06 = void 0;
                _this.m07 = void 0;
                _this.m08 = void 0;
                _this.m09 = void 0;
                _this.m10 = void 0;
                _this.m11 = void 0;
                _this.m12 = void 0;
                _this.m13 = void 0;
                _this.m14 = void 0;
                _this.m15 = void 0;

                if (typeof m00 === 'object') {
                  _this.m00 = m00.m00;
                  _this.m01 = m00.m01;
                  _this.m02 = m00.m02;
                  _this.m03 = m00.m03;
                  _this.m04 = m00.m04;
                  _this.m05 = m00.m05;
                  _this.m06 = m00.m06;
                  _this.m07 = m00.m07;
                  _this.m08 = m00.m08;
                  _this.m09 = m00.m09;
                  _this.m10 = m00.m10;
                  _this.m11 = m00.m11;
                  _this.m12 = m00.m12;
                  _this.m13 = m00.m13;
                  _this.m14 = m00.m14;
                  _this.m15 = m00.m15;
                } else {
                  _this.m00 = m00;
                  _this.m01 = m01;
                  _this.m02 = m02;
                  _this.m03 = m03;
                  _this.m04 = m04;
                  _this.m05 = m05;
                  _this.m06 = m06;
                  _this.m07 = m07;
                  _this.m08 = m08;
                  _this.m09 = m09;
                  _this.m10 = m10;
                  _this.m11 = m11;
                  _this.m12 = m12;
                  _this.m13 = m13;
                  _this.m14 = m14;
                  _this.m15 = m15;
                }

                return _this;
              }

              var _proto = Mat4.prototype;

              _proto.clone = function clone() {
                return new Mat4(this.m00, this.m01, this.m02, this.m03, this.m04, this.m05, this.m06, this.m07, this.m08, this.m09, this.m10, this.m11, this.m12, this.m13, this.m14, this.m15);
              };

              _proto.set = function set(m00, m01, m02, m03, m04, m05, m06, m07, m08, m09, m10, m11, m12, m13, m14, m15) {
                if (m00 === void 0) {
                  m00 = 1;
                }

                if (m01 === void 0) {
                  m01 = 0;
                }

                if (m02 === void 0) {
                  m02 = 0;
                }

                if (m03 === void 0) {
                  m03 = 0;
                }

                if (m04 === void 0) {
                  m04 = 0;
                }

                if (m05 === void 0) {
                  m05 = 1;
                }

                if (m06 === void 0) {
                  m06 = 0;
                }

                if (m07 === void 0) {
                  m07 = 0;
                }

                if (m08 === void 0) {
                  m08 = 0;
                }

                if (m09 === void 0) {
                  m09 = 0;
                }

                if (m10 === void 0) {
                  m10 = 1;
                }

                if (m11 === void 0) {
                  m11 = 0;
                }

                if (m12 === void 0) {
                  m12 = 0;
                }

                if (m13 === void 0) {
                  m13 = 0;
                }

                if (m14 === void 0) {
                  m14 = 0;
                }

                if (m15 === void 0) {
                  m15 = 1;
                }

                if (typeof m00 === 'object') {
                  this.m01 = m00.m01;
                  this.m02 = m00.m02;
                  this.m03 = m00.m03;
                  this.m04 = m00.m04;
                  this.m05 = m00.m05;
                  this.m06 = m00.m06;
                  this.m07 = m00.m07;
                  this.m08 = m00.m08;
                  this.m09 = m00.m09;
                  this.m10 = m00.m10;
                  this.m11 = m00.m11;
                  this.m12 = m00.m12;
                  this.m13 = m00.m13;
                  this.m14 = m00.m14;
                  this.m15 = m00.m15;
                  this.m00 = m00.m00;
                } else {
                  this.m01 = m01;
                  this.m02 = m02;
                  this.m03 = m03;
                  this.m04 = m04;
                  this.m05 = m05;
                  this.m06 = m06;
                  this.m07 = m07;
                  this.m08 = m08;
                  this.m09 = m09;
                  this.m10 = m10;
                  this.m11 = m11;
                  this.m12 = m12;
                  this.m13 = m13;
                  this.m14 = m14;
                  this.m15 = m15;
                  this.m00 = m00;
                }

                return this;
              };

              _proto.equals = function equals(other, epsilon) {
                if (epsilon === void 0) {
                  epsilon = EPSILON;
                }

                return Math.abs(this.m00 - other.m00) <= epsilon * Math.max(1.0, Math.abs(this.m00), Math.abs(other.m00)) && Math.abs(this.m01 - other.m01) <= epsilon * Math.max(1.0, Math.abs(this.m01), Math.abs(other.m01)) && Math.abs(this.m02 - other.m02) <= epsilon * Math.max(1.0, Math.abs(this.m02), Math.abs(other.m02)) && Math.abs(this.m03 - other.m03) <= epsilon * Math.max(1.0, Math.abs(this.m03), Math.abs(other.m03)) && Math.abs(this.m04 - other.m04) <= epsilon * Math.max(1.0, Math.abs(this.m04), Math.abs(other.m04)) && Math.abs(this.m05 - other.m05) <= epsilon * Math.max(1.0, Math.abs(this.m05), Math.abs(other.m05)) && Math.abs(this.m06 - other.m06) <= epsilon * Math.max(1.0, Math.abs(this.m06), Math.abs(other.m06)) && Math.abs(this.m07 - other.m07) <= epsilon * Math.max(1.0, Math.abs(this.m07), Math.abs(other.m07)) && Math.abs(this.m08 - other.m08) <= epsilon * Math.max(1.0, Math.abs(this.m08), Math.abs(other.m08)) && Math.abs(this.m09 - other.m09) <= epsilon * Math.max(1.0, Math.abs(this.m09), Math.abs(other.m09)) && Math.abs(this.m10 - other.m10) <= epsilon * Math.max(1.0, Math.abs(this.m10), Math.abs(other.m10)) && Math.abs(this.m11 - other.m11) <= epsilon * Math.max(1.0, Math.abs(this.m11), Math.abs(other.m11)) && Math.abs(this.m12 - other.m12) <= epsilon * Math.max(1.0, Math.abs(this.m12), Math.abs(other.m12)) && Math.abs(this.m13 - other.m13) <= epsilon * Math.max(1.0, Math.abs(this.m13), Math.abs(other.m13)) && Math.abs(this.m14 - other.m14) <= epsilon * Math.max(1.0, Math.abs(this.m14), Math.abs(other.m14)) && Math.abs(this.m15 - other.m15) <= epsilon * Math.max(1.0, Math.abs(this.m15), Math.abs(other.m15));
              };

              _proto.strictEquals = function strictEquals(other) {
                return this.m00 === other.m00 && this.m01 === other.m01 && this.m02 === other.m02 && this.m03 === other.m03 && this.m04 === other.m04 && this.m05 === other.m05 && this.m06 === other.m06 && this.m07 === other.m07 && this.m08 === other.m08 && this.m09 === other.m09 && this.m10 === other.m10 && this.m11 === other.m11 && this.m12 === other.m12 && this.m13 === other.m13 && this.m14 === other.m14 && this.m15 === other.m15;
              };

              _proto.toString = function toString() {
                return "[\n" + this.m00 + ", " + this.m01 + ", " + this.m02 + ", " + this.m03 + ",\n" + this.m04 + ", " + this.m05 + ", " + this.m06 + ", " + this.m07 + ",\n" + this.m08 + ", " + this.m09 + ", " + this.m10 + ", " + this.m11 + ",\n" + this.m12 + ", " + this.m13 + ", " + this.m14 + ", " + this.m15 + "\n" + ']';
              };

              _proto.identity = function identity() {
                this.m00 = 1;
                this.m01 = 0;
                this.m02 = 0;
                this.m03 = 0;
                this.m04 = 0;
                this.m05 = 1;
                this.m06 = 0;
                this.m07 = 0;
                this.m08 = 0;
                this.m09 = 0;
                this.m10 = 1;
                this.m11 = 0;
                this.m12 = 0;
                this.m13 = 0;
                this.m14 = 0;
                this.m15 = 1;
                return this;
              };

              _proto.zero = function zero() {
                this.m00 = 0;
                this.m01 = 0;
                this.m02 = 0;
                this.m03 = 0;
                this.m04 = 0;
                this.m05 = 0;
                this.m06 = 0;
                this.m07 = 0;
                this.m08 = 0;
                this.m09 = 0;
                this.m10 = 0;
                this.m11 = 0;
                this.m12 = 0;
                this.m13 = 0;
                this.m14 = 0;
                this.m15 = 0;
                return this;
              };

              _proto.transpose = function transpose() {
                var a01 = this.m01;
                var a02 = this.m02;
                var a03 = this.m03;
                var a12 = this.m06;
                var a13 = this.m07;
                var a23 = this.m11;
                this.m01 = this.m04;
                this.m02 = this.m08;
                this.m03 = this.m12;
                this.m04 = a01;
                this.m06 = this.m09;
                this.m07 = this.m13;
                this.m08 = a02;
                this.m09 = a12;
                this.m11 = this.m14;
                this.m12 = a03;
                this.m13 = a13;
                this.m14 = a23;
                return this;
              };

              _proto.invert = function invert() {
                var a00 = this.m00;
                var a01 = this.m01;
                var a02 = this.m02;
                var a03 = this.m03;
                var a10 = this.m04;
                var a11 = this.m05;
                var a12 = this.m06;
                var a13 = this.m07;
                var a20 = this.m08;
                var a21 = this.m09;
                var a22 = this.m10;
                var a23 = this.m11;
                var a30 = this.m12;
                var a31 = this.m13;
                var a32 = this.m14;
                var a33 = this.m15;
                var b00 = a00 * a11 - a01 * a10;
                var b01 = a00 * a12 - a02 * a10;
                var b02 = a00 * a13 - a03 * a10;
                var b03 = a01 * a12 - a02 * a11;
                var b04 = a01 * a13 - a03 * a11;
                var b05 = a02 * a13 - a03 * a12;
                var b06 = a20 * a31 - a21 * a30;
                var b07 = a20 * a32 - a22 * a30;
                var b08 = a20 * a33 - a23 * a30;
                var b09 = a21 * a32 - a22 * a31;
                var b10 = a21 * a33 - a23 * a31;
                var b11 = a22 * a33 - a23 * a32;
                var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;

                if (det === 0) {
                  this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
                  return this;
                }

                det = 1.0 / det;
                this.m00 = (a11 * b11 - a12 * b10 + a13 * b09) * det;
                this.m01 = (a02 * b10 - a01 * b11 - a03 * b09) * det;
                this.m02 = (a31 * b05 - a32 * b04 + a33 * b03) * det;
                this.m03 = (a22 * b04 - a21 * b05 - a23 * b03) * det;
                this.m04 = (a12 * b08 - a10 * b11 - a13 * b07) * det;
                this.m05 = (a00 * b11 - a02 * b08 + a03 * b07) * det;
                this.m06 = (a32 * b02 - a30 * b05 - a33 * b01) * det;
                this.m07 = (a20 * b05 - a22 * b02 + a23 * b01) * det;
                this.m08 = (a10 * b10 - a11 * b08 + a13 * b06) * det;
                this.m09 = (a01 * b08 - a00 * b10 - a03 * b06) * det;
                this.m10 = (a30 * b04 - a31 * b02 + a33 * b00) * det;
                this.m11 = (a21 * b02 - a20 * b04 - a23 * b00) * det;
                this.m12 = (a11 * b07 - a10 * b09 - a12 * b06) * det;
                this.m13 = (a00 * b09 - a01 * b07 + a02 * b06) * det;
                this.m14 = (a31 * b01 - a30 * b03 - a32 * b00) * det;
                this.m15 = (a20 * b03 - a21 * b01 + a22 * b00) * det;
                return this;
              };

              _proto.determinant = function determinant() {
                var a00 = this.m00;
                var a01 = this.m01;
                var a02 = this.m02;
                var a03 = this.m03;
                var a10 = this.m04;
                var a11 = this.m05;
                var a12 = this.m06;
                var a13 = this.m07;
                var a20 = this.m08;
                var a21 = this.m09;
                var a22 = this.m10;
                var a23 = this.m11;
                var a30 = this.m12;
                var a31 = this.m13;
                var a32 = this.m14;
                var a33 = this.m15;
                var b00 = a00 * a11 - a01 * a10;
                var b01 = a00 * a12 - a02 * a10;
                var b02 = a00 * a13 - a03 * a10;
                var b03 = a01 * a12 - a02 * a11;
                var b04 = a01 * a13 - a03 * a11;
                var b05 = a02 * a13 - a03 * a12;
                var b06 = a20 * a31 - a21 * a30;
                var b07 = a20 * a32 - a22 * a30;
                var b08 = a20 * a33 - a23 * a30;
                var b09 = a21 * a32 - a22 * a31;
                var b10 = a21 * a33 - a23 * a31;
                var b11 = a22 * a33 - a23 * a32;
                return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
              };

              _proto.add = function add(mat) {
                this.m00 += mat.m00;
                this.m01 += mat.m01;
                this.m02 += mat.m02;
                this.m03 += mat.m03;
                this.m04 += mat.m04;
                this.m05 += mat.m05;
                this.m06 += mat.m06;
                this.m07 += mat.m07;
                this.m08 += mat.m08;
                this.m09 += mat.m09;
                this.m10 += mat.m10;
                this.m11 += mat.m11;
                this.m12 += mat.m12;
                this.m13 += mat.m13;
                this.m14 += mat.m14;
                this.m15 += mat.m15;
                return this;
              };

              _proto.subtract = function subtract(mat) {
                this.m00 -= mat.m00;
                this.m01 -= mat.m01;
                this.m02 -= mat.m02;
                this.m03 -= mat.m03;
                this.m04 -= mat.m04;
                this.m05 -= mat.m05;
                this.m06 -= mat.m06;
                this.m07 -= mat.m07;
                this.m08 -= mat.m08;
                this.m09 -= mat.m09;
                this.m10 -= mat.m10;
                this.m11 -= mat.m11;
                this.m12 -= mat.m12;
                this.m13 -= mat.m13;
                this.m14 -= mat.m14;
                this.m15 -= mat.m15;
                return this;
              };

              _proto.multiply = function multiply(mat) {
                var a00 = this.m00;
                var a01 = this.m01;
                var a02 = this.m02;
                var a03 = this.m03;
                var a10 = this.m04;
                var a11 = this.m05;
                var a12 = this.m06;
                var a13 = this.m07;
                var a20 = this.m08;
                var a21 = this.m09;
                var a22 = this.m10;
                var a23 = this.m11;
                var a30 = this.m12;
                var a31 = this.m13;
                var a32 = this.m14;
                var a33 = this.m15;
                var b0 = mat.m00;
                var b1 = mat.m01;
                var b2 = mat.m02;
                var b3 = mat.m03;
                this.m00 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
                this.m01 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
                this.m02 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
                this.m03 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
                b0 = mat.m04;
                b1 = mat.m05;
                b2 = mat.m06;
                b3 = mat.m07;
                this.m04 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
                this.m05 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
                this.m06 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
                this.m07 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
                b0 = mat.m08;
                b1 = mat.m09;
                b2 = mat.m10;
                b3 = mat.m11;
                this.m08 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
                this.m09 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
                this.m10 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
                this.m11 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
                b0 = mat.m12;
                b1 = mat.m13;
                b2 = mat.m14;
                b3 = mat.m15;
                this.m12 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
                this.m13 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
                this.m14 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
                this.m15 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
                return this;
              };

              _proto.multiplyScalar = function multiplyScalar(scalar) {
                this.m00 *= scalar;
                this.m01 *= scalar;
                this.m02 *= scalar;
                this.m03 *= scalar;
                this.m04 *= scalar;
                this.m05 *= scalar;
                this.m06 *= scalar;
                this.m07 *= scalar;
                this.m08 *= scalar;
                this.m09 *= scalar;
                this.m10 *= scalar;
                this.m11 *= scalar;
                this.m12 *= scalar;
                this.m13 *= scalar;
                this.m14 *= scalar;
                this.m15 *= scalar;
                return this;
              };

              _proto.translate = function translate(vec) {
                console.warn('function changed');
                this.m12 += vec.x;
                this.m13 += vec.y;
                this.m14 += vec.z;
                return this;
              };

              _proto.scale = function scale(vec) {
                var x = vec.x;
                var y = vec.y;
                var z = vec.z;
                this.m00 *= x;
                this.m01 *= x;
                this.m02 *= x;
                this.m03 *= x;
                this.m04 *= y;
                this.m05 *= y;
                this.m06 *= y;
                this.m07 *= y;
                this.m08 *= z;
                this.m09 *= z;
                this.m10 *= z;
                this.m11 *= z;
                return this;
              };

              _proto.rotate = function rotate(rad, axis) {
                var x = axis.x;
                var y = axis.y;
                var z = axis.z;
                var len = Math.sqrt(x * x + y * y + z * z);

                if (Math.abs(len) < EPSILON) {
                  return null;
                }

                len = 1 / len;
                x *= len;
                y *= len;
                z *= len;
                var s = Math.sin(rad);
                var c = Math.cos(rad);
                var t = 1 - c;
                var a00 = this.m00;
                var a01 = this.m01;
                var a02 = this.m02;
                var a03 = this.m03;
                var a10 = this.m04;
                var a11 = this.m05;
                var a12 = this.m06;
                var a13 = this.m07;
                var a20 = this.m08;
                var a21 = this.m09;
                var a22 = this.m10;
                var a23 = this.m11;
                var b00 = x * x * t + c;
                var b01 = y * x * t + z * s;
                var b02 = z * x * t - y * s;
                var b10 = x * y * t - z * s;
                var b11 = y * y * t + c;
                var b12 = z * y * t + x * s;
                var b20 = x * z * t + y * s;
                var b21 = y * z * t - x * s;
                var b22 = z * z * t + c;
                this.m00 = a00 * b00 + a10 * b01 + a20 * b02;
                this.m01 = a01 * b00 + a11 * b01 + a21 * b02;
                this.m02 = a02 * b00 + a12 * b01 + a22 * b02;
                this.m03 = a03 * b00 + a13 * b01 + a23 * b02;
                this.m04 = a00 * b10 + a10 * b11 + a20 * b12;
                this.m05 = a01 * b10 + a11 * b11 + a21 * b12;
                this.m06 = a02 * b10 + a12 * b11 + a22 * b12;
                this.m07 = a03 * b10 + a13 * b11 + a23 * b12;
                this.m08 = a00 * b20 + a10 * b21 + a20 * b22;
                this.m09 = a01 * b20 + a11 * b21 + a21 * b22;
                this.m10 = a02 * b20 + a12 * b21 + a22 * b22;
                this.m11 = a03 * b20 + a13 * b21 + a23 * b22;
                return this;
              };

              _proto.getTranslation = function getTranslation(out) {
                out.x = this.m12;
                out.y = this.m13;
                out.z = this.m14;
                return out;
              };

              _proto.getScale = function getScale(out) {
                var m00 = m3_1$1.m00 = this.m00;
                var m01 = m3_1$1.m01 = this.m01;
                var m02 = m3_1$1.m02 = this.m02;
                var m04 = m3_1$1.m03 = this.m04;
                var m05 = m3_1$1.m04 = this.m05;
                var m06 = m3_1$1.m05 = this.m06;
                var m08 = m3_1$1.m06 = this.m08;
                var m09 = m3_1$1.m07 = this.m09;
                var m10 = m3_1$1.m08 = this.m10;
                out.x = Math.sqrt(m00 * m00 + m01 * m01 + m02 * m02);
                out.y = Math.sqrt(m04 * m04 + m05 * m05 + m06 * m06);
                out.z = Math.sqrt(m08 * m08 + m09 * m09 + m10 * m10);

                if (Mat3.determinant(m3_1$1) < 0) {
                  out.x *= -1;
                }

                return out;
              };

              _proto.getRotation = function getRotation(out) {
                var trace = this.m00 + this.m05 + this.m10;
                var S = 0;

                if (trace > 0) {
                  S = Math.sqrt(trace + 1.0) * 2;
                  out.w = 0.25 * S;
                  out.x = (this.m06 - this.m09) / S;
                  out.y = (this.m08 - this.m02) / S;
                  out.z = (this.m01 - this.m04) / S;
                } else if (this.m00 > this.m05 && this.m00 > this.m10) {
                  S = Math.sqrt(1.0 + this.m00 - this.m05 - this.m10) * 2;
                  out.w = (this.m06 - this.m09) / S;
                  out.x = 0.25 * S;
                  out.y = (this.m01 + this.m04) / S;
                  out.z = (this.m08 + this.m02) / S;
                } else if (this.m05 > this.m10) {
                  S = Math.sqrt(1.0 + this.m05 - this.m00 - this.m10) * 2;
                  out.w = (this.m08 - this.m02) / S;
                  out.x = (this.m01 + this.m04) / S;
                  out.y = 0.25 * S;
                  out.z = (this.m06 + this.m09) / S;
                } else {
                  S = Math.sqrt(1.0 + this.m10 - this.m00 - this.m05) * 2;
                  out.w = (this.m01 - this.m04) / S;
                  out.x = (this.m08 + this.m02) / S;
                  out.y = (this.m06 + this.m09) / S;
                  out.z = 0.25 * S;
                }

                return out;
              };

              _proto.fromRTS = function fromRTS(q, v, s) {
                var x = q.x;
                var y = q.y;
                var z = q.z;
                var w = q.w;
                var x2 = x + x;
                var y2 = y + y;
                var z2 = z + z;
                var xx = x * x2;
                var xy = x * y2;
                var xz = x * z2;
                var yy = y * y2;
                var yz = y * z2;
                var zz = z * z2;
                var wx = w * x2;
                var wy = w * y2;
                var wz = w * z2;
                var sx = s.x;
                var sy = s.y;
                var sz = s.z;
                this.m00 = (1 - (yy + zz)) * sx;
                this.m01 = (xy + wz) * sx;
                this.m02 = (xz - wy) * sx;
                this.m03 = 0;
                this.m04 = (xy - wz) * sy;
                this.m05 = (1 - (xx + zz)) * sy;
                this.m06 = (yz + wx) * sy;
                this.m07 = 0;
                this.m08 = (xz + wy) * sz;
                this.m09 = (yz - wx) * sz;
                this.m10 = (1 - (xx + yy)) * sz;
                this.m11 = 0;
                this.m12 = v.x;
                this.m13 = v.y;
                this.m14 = v.z;
                this.m15 = 1;
                return this;
              };

              _proto.fromQuat = function fromQuat(q) {
                var x = q.x;
                var y = q.y;
                var z = q.z;
                var w = q.w;
                var x2 = x + x;
                var y2 = y + y;
                var z2 = z + z;
                var xx = x * x2;
                var yx = y * x2;
                var yy = y * y2;
                var zx = z * x2;
                var zy = z * y2;
                var zz = z * z2;
                var wx = w * x2;
                var wy = w * y2;
                var wz = w * z2;
                this.m00 = 1 - yy - zz;
                this.m01 = yx + wz;
                this.m02 = zx - wy;
                this.m03 = 0;
                this.m04 = yx - wz;
                this.m05 = 1 - xx - zz;
                this.m06 = zy + wx;
                this.m07 = 0;
                this.m08 = zx + wy;
                this.m09 = zy - wx;
                this.m10 = 1 - xx - yy;
                this.m11 = 0;
                this.m12 = 0;
                this.m13 = 0;
                this.m14 = 0;
                this.m15 = 1;
                return this;
              };

              return Mat4;
            }(ValueType));
            Mat4.IDENTITY = Object.freeze(new Mat4());
            var v3_1$3 = new Vec3();
            var m3_1$1 = new Mat3();
            CCClass.fastDefine('cc.Mat4', Mat4, {
              m00: 1,
              m01: 0,
              m02: 0,
              m03: 0,
              m04: 0,
              m05: 1,
              m06: 0,
              m07: 0,
              m08: 0,
              m09: 0,
              m10: 1,
              m11: 0,
              m12: 0,
              m13: 0,
              m14: 0,
              m15: 1
            });
            legacyCC.Mat4 = Mat4;
            function mat4(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {
              return new Mat4(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33);
            }
            legacyCC.mat4 = mat4;

            var Vec2 = exports('Vec2', function (_ValueType) {
              _inheritsLoose(Vec2, _ValueType);

              Vec2.clone = function clone(a) {
                return new Vec2(a.x, a.y);
              };

              Vec2.copy = function copy(out, a) {
                out.x = a.x;
                out.y = a.y;
                return out;
              };

              Vec2.set = function set(out, x, y) {
                out.x = x;
                out.y = y;
                return out;
              };

              Vec2.add = function add(out, a, b) {
                out.x = a.x + b.x;
                out.y = a.y + b.y;
                return out;
              };

              Vec2.subtract = function subtract(out, a, b) {
                out.x = a.x - b.x;
                out.y = a.y - b.y;
                return out;
              };

              Vec2.multiply = function multiply(out, a, b) {
                out.x = a.x * b.x;
                out.y = a.y * b.y;
                return out;
              };

              Vec2.divide = function divide(out, a, b) {
                out.x = a.x / b.x;
                out.y = a.y / b.y;
                return out;
              };

              Vec2.ceil = function ceil(out, a) {
                out.x = Math.ceil(a.x);
                out.y = Math.ceil(a.y);
                return out;
              };

              Vec2.floor = function floor(out, a) {
                out.x = Math.floor(a.x);
                out.y = Math.floor(a.y);
                return out;
              };

              Vec2.min = function min(out, a, b) {
                out.x = Math.min(a.x, b.x);
                out.y = Math.min(a.y, b.y);
                return out;
              };

              Vec2.max = function max(out, a, b) {
                out.x = Math.max(a.x, b.x);
                out.y = Math.max(a.y, b.y);
                return out;
              };

              Vec2.round = function round(out, a) {
                out.x = Math.round(a.x);
                out.y = Math.round(a.y);
                return out;
              };

              Vec2.multiplyScalar = function multiplyScalar(out, a, b) {
                out.x = a.x * b;
                out.y = a.y * b;
                return out;
              };

              Vec2.scaleAndAdd = function scaleAndAdd(out, a, b, scale) {
                out.x = a.x + b.x * scale;
                out.y = a.y + b.y * scale;
                return out;
              };

              Vec2.distance = function distance(a, b) {
                var x = b.x - a.x;
                var y = b.y - a.y;
                return Math.sqrt(x * x + y * y);
              };

              Vec2.squaredDistance = function squaredDistance(a, b) {
                var x = b.x - a.x;
                var y = b.y - a.y;
                return x * x + y * y;
              };

              Vec2.len = function len(a) {
                var x = a.x;
                var y = a.y;
                return Math.sqrt(x * x + y * y);
              };

              Vec2.lengthSqr = function lengthSqr(a) {
                var x = a.x;
                var y = a.y;
                return x * x + y * y;
              };

              Vec2.negate = function negate(out, a) {
                out.x = -a.x;
                out.y = -a.y;
                return out;
              };

              Vec2.inverse = function inverse(out, a) {
                out.x = 1.0 / a.x;
                out.y = 1.0 / a.y;
                return out;
              };

              Vec2.inverseSafe = function inverseSafe(out, a) {
                var x = a.x;
                var y = a.y;

                if (Math.abs(x) < EPSILON) {
                  out.x = 0;
                } else {
                  out.x = 1.0 / x;
                }

                if (Math.abs(y) < EPSILON) {
                  out.y = 0;
                } else {
                  out.y = 1.0 / y;
                }

                return out;
              };

              Vec2.normalize = function normalize(out, a) {
                var x = a.x;
                var y = a.y;
                var len = x * x + y * y;

                if (len > 0) {
                  len = 1 / Math.sqrt(len);
                  out.x = x * len;
                  out.y = y * len;
                }

                return out;
              };

              Vec2.dot = function dot(a, b) {
                return a.x * b.x + a.y * b.y;
              };

              Vec2.cross = function cross(out, a, b) {
                out.x = out.y = 0;
                out.z = a.x * b.y - a.y * b.x;
                return out;
              };

              Vec2.lerp = function lerp(out, a, b, t) {
                var x = a.x;
                var y = a.y;
                out.x = x + t * (b.x - x);
                out.y = y + t * (b.y - y);
                return out;
              };

              Vec2.random = function random$1(out, scale) {
                scale = scale || 1.0;
                var r = random() * 2.0 * Math.PI;
                out.x = Math.cos(r) * scale;
                out.y = Math.sin(r) * scale;
                return out;
              };

              Vec2.transformMat3 = function transformMat3(out, a, m) {
                var x = a.x;
                var y = a.y;
                out.x = m.m00 * x + m.m03 * y + m.m06;
                out.y = m.m01 * x + m.m04 * y + m.m07;
                return out;
              };

              Vec2.transformMat4 = function transformMat4(out, a, m) {
                var x = a.x;
                var y = a.y;
                out.x = m.m00 * x + m.m04 * y + m.m12;
                out.y = m.m01 * x + m.m05 * y + m.m13;
                return out;
              };

              Vec2.str = function str(a) {
                return "Vec2(" + a.x + ", " + a.y + ")";
              };

              Vec2.toArray = function toArray(out, v, ofs) {
                if (ofs === void 0) {
                  ofs = 0;
                }

                out[ofs + 0] = v.x;
                out[ofs + 1] = v.y;
                return out;
              };

              Vec2.fromArray = function fromArray(out, arr, ofs) {
                if (ofs === void 0) {
                  ofs = 0;
                }

                out.x = arr[ofs + 0];
                out.y = arr[ofs + 1];
                return out;
              };

              Vec2.strictEquals = function strictEquals(a, b) {
                return a.x === b.x && a.y === b.y;
              };

              Vec2.equals = function equals(a, b, epsilon) {
                if (epsilon === void 0) {
                  epsilon = EPSILON;
                }

                return Math.abs(a.x - b.x) <= epsilon * Math.max(1.0, Math.abs(a.x), Math.abs(b.x)) && Math.abs(a.y - b.y) <= epsilon * Math.max(1.0, Math.abs(a.y), Math.abs(b.y));
              };

              Vec2.angle = function angle(a, b) {
                Vec2.normalize(v2_1, a);
                Vec2.normalize(v2_2, b);
                var cosine = Vec2.dot(v2_1, v2_2);

                if (cosine > 1.0) {
                  return 0;
                }

                if (cosine < -1.0) {
                  return Math.PI;
                }

                return Math.acos(cosine);
              };

              function Vec2(x, y) {
                var _this;

                _this = _ValueType.call(this) || this;

                if (x && typeof x === 'object') {
                  _this.x = x.x;
                  _this.y = x.y;
                } else {
                  _this.x = x || 0;
                  _this.y = y || 0;
                }

                return _this;
              }

              var _proto = Vec2.prototype;

              _proto.clone = function clone() {
                return new Vec2(this.x, this.y);
              };

              _proto.set = function set(x, y) {
                if (x && typeof x === 'object') {
                  this.x = x.x;
                  this.y = x.y;
                } else {
                  this.x = x || 0;
                  this.y = y || 0;
                }

                return this;
              };

              _proto.equals = function equals(other, epsilon) {
                if (epsilon === void 0) {
                  epsilon = EPSILON;
                }

                return Math.abs(this.x - other.x) <= epsilon * Math.max(1.0, Math.abs(this.x), Math.abs(other.x)) && Math.abs(this.y - other.y) <= epsilon * Math.max(1.0, Math.abs(this.y), Math.abs(other.y));
              };

              _proto.equals2f = function equals2f(x, y, epsilon) {
                if (epsilon === void 0) {
                  epsilon = EPSILON;
                }

                return Math.abs(this.x - x) <= epsilon * Math.max(1.0, Math.abs(this.x), Math.abs(x)) && Math.abs(this.y - y) <= epsilon * Math.max(1.0, Math.abs(this.y), Math.abs(y));
              };

              _proto.strictEquals = function strictEquals(other) {
                return other && this.x === other.x && this.y === other.y;
              };

              _proto.strictEquals2f = function strictEquals2f(x, y) {
                return this.x === x && this.y === y;
              };

              _proto.toString = function toString() {
                return "(" + this.x.toFixed(2) + ", " + this.y.toFixed(2) + ")";
              };

              _proto.lerp = function lerp(to, ratio) {
                var x = this.x;
                var y = this.y;
                this.x = x + ratio * (to.x - x);
                this.y = y + ratio * (to.y - y);
                return this;
              };

              _proto.clampf = function clampf(minInclusive, maxInclusive) {
                this.x = clamp(this.x, minInclusive.x, maxInclusive.x);
                this.y = clamp(this.y, minInclusive.y, maxInclusive.y);
                return this;
              };

              _proto.add = function add(other) {
                this.x += other.x;
                this.y += other.y;
                return this;
              };

              _proto.add2f = function add2f(x, y) {
                this.x += x;
                this.y += y;
                return this;
              };

              _proto.subtract = function subtract(other) {
                this.x -= other.x;
                this.y -= other.y;
                return this;
              };

              _proto.subtract2f = function subtract2f(x, y) {
                this.x -= x;
                this.y -= y;
                return this;
              };

              _proto.multiplyScalar = function multiplyScalar(scalar) {
                if (typeof scalar === 'object') {
                  console.warn('should use Vec2.multiply for vector * vector operation');
                }

                this.x *= scalar;
                this.y *= scalar;
                return this;
              };

              _proto.multiply = function multiply(other) {
                if (typeof other !== 'object') {
                  console.warn('should use Vec2.scale for vector * scalar operation');
                }

                this.x *= other.x;
                this.y *= other.y;
                return this;
              };

              _proto.multiply2f = function multiply2f(x, y) {
                this.x *= x;
                this.y *= y;
                return this;
              };

              _proto.divide = function divide(other) {
                this.x /= other.x;
                this.y /= other.y;
                return this;
              };

              _proto.divide2f = function divide2f(x, y) {
                this.x /= x;
                this.y /= y;
                return this;
              };

              _proto.negative = function negative() {
                this.x = -this.x;
                this.y = -this.y;
                return this;
              };

              _proto.dot = function dot(other) {
                return this.x * other.x + this.y * other.y;
              };

              _proto.cross = function cross(other) {
                return this.x * other.y - this.y * other.x;
              };

              _proto.length = function length() {
                return Math.sqrt(this.x * this.x + this.y * this.y);
              };

              _proto.lengthSqr = function lengthSqr() {
                return this.x * this.x + this.y * this.y;
              };

              _proto.normalize = function normalize() {
                var x = this.x;
                var y = this.y;
                var len = x * x + y * y;

                if (len > 0) {
                  len = 1 / Math.sqrt(len);
                  this.x *= len;
                  this.y *= len;
                }

                return this;
              };

              _proto.angle = function angle(other) {
                var magSqr1 = this.lengthSqr();
                var magSqr2 = other.lengthSqr();

                if (magSqr1 === 0 || magSqr2 === 0) {
                  console.warn('Can\'t get angle between zero vector');
                  return 0.0;
                }

                var dot = this.dot(other);
                var theta = dot / Math.sqrt(magSqr1 * magSqr2);
                theta = clamp(theta, -1.0, 1.0);
                return Math.acos(theta);
              };

              _proto.signAngle = function signAngle(other) {
                var angle = this.angle(other);
                return this.cross(other) < 0 ? -angle : angle;
              };

              _proto.rotate = function rotate(radians) {
                var x = this.x;
                var y = this.y;
                var sin = Math.sin(radians);
                var cos = Math.cos(radians);
                this.x = cos * x - sin * y;
                this.y = sin * x + cos * y;
                return this;
              };

              _proto.project = function project(other) {
                var scalar = this.dot(other) / other.dot(other);
                this.x = other.x * scalar;
                this.y = other.y * scalar;
                return this;
              };

              _proto.transformMat4 = function transformMat4(matrix) {
                var x = this.x;
                var y = this.y;
                this.x = matrix.m00 * x + matrix.m04 * y + matrix.m12;
                this.y = matrix.m01 * x + matrix.m05 * y + matrix.m13;
                return this;
              };

              return Vec2;
            }(ValueType));
            Vec2.ZERO = Object.freeze(new Vec2(0, 0));
            Vec2.ONE = Object.freeze(new Vec2(1, 1));
            Vec2.NEG_ONE = Object.freeze(new Vec2(-1, -1));
            Vec2.UNIT_X = Object.freeze(new Vec2(1, 0));
            Vec2.UNIT_Y = Object.freeze(new Vec2(0, 1));
            var v2_1 = new Vec2();
            var v2_2 = new Vec2();
            CCClass.fastDefine('cc.Vec2', Vec2, {
              x: 0,
              y: 0
            });
            legacyCC.Vec2 = Vec2;
            function v2(x, y) {
              return new Vec2(x, y);
            }
            legacyCC.v2 = v2;

            var Vec4 = exports('Vec4', function (_ValueType) {
              _inheritsLoose(Vec4, _ValueType);

              Vec4.clone = function clone(a) {
                return new Vec4(a.x, a.y, a.z, a.w);
              };

              Vec4.copy = function copy(out, a) {
                out.x = a.x;
                out.y = a.y;
                out.z = a.z;
                out.w = a.w;
                return out;
              };

              Vec4.set = function set(out, x, y, z, w) {
                out.x = x;
                out.y = y;
                out.z = z;
                out.w = w;
                return out;
              };

              Vec4.add = function add(out, a, b) {
                out.x = a.x + b.x;
                out.y = a.y + b.y;
                out.z = a.z + b.z;
                out.w = a.w + b.w;
                return out;
              };

              Vec4.subtract = function subtract(out, a, b) {
                out.x = a.x - b.x;
                out.y = a.y - b.y;
                out.z = a.z - b.z;
                out.w = a.w - b.w;
                return out;
              };

              Vec4.multiply = function multiply(out, a, b) {
                out.x = a.x * b.x;
                out.y = a.y * b.y;
                out.z = a.z * b.z;
                out.w = a.w * b.w;
                return out;
              };

              Vec4.divide = function divide(out, a, b) {
                out.x = a.x / b.x;
                out.y = a.y / b.y;
                out.z = a.z / b.z;
                out.w = a.w / b.w;
                return out;
              };

              Vec4.ceil = function ceil(out, a) {
                out.x = Math.ceil(a.x);
                out.y = Math.ceil(a.y);
                out.z = Math.ceil(a.z);
                out.w = Math.ceil(a.w);
                return out;
              };

              Vec4.floor = function floor(out, a) {
                out.x = Math.floor(a.x);
                out.y = Math.floor(a.y);
                out.z = Math.floor(a.z);
                out.w = Math.floor(a.w);
                return out;
              };

              Vec4.min = function min(out, a, b) {
                out.x = Math.min(a.x, b.x);
                out.y = Math.min(a.y, b.y);
                out.z = Math.min(a.z, b.z);
                out.w = Math.min(a.w, b.w);
                return out;
              };

              Vec4.max = function max(out, a, b) {
                out.x = Math.max(a.x, b.x);
                out.y = Math.max(a.y, b.y);
                out.z = Math.max(a.z, b.z);
                out.w = Math.max(a.w, b.w);
                return out;
              };

              Vec4.round = function round(out, a) {
                out.x = Math.round(a.x);
                out.y = Math.round(a.y);
                out.z = Math.round(a.z);
                out.w = Math.round(a.w);
                return out;
              };

              Vec4.multiplyScalar = function multiplyScalar(out, a, b) {
                out.x = a.x * b;
                out.y = a.y * b;
                out.z = a.z * b;
                out.w = a.w * b;
                return out;
              };

              Vec4.scaleAndAdd = function scaleAndAdd(out, a, b, scale) {
                out.x = a.x + b.x * scale;
                out.y = a.y + b.y * scale;
                out.z = a.z + b.z * scale;
                out.w = a.w + b.w * scale;
                return out;
              };

              Vec4.distance = function distance(a, b) {
                var x = b.x - a.x;
                var y = b.y - a.y;
                var z = b.z - a.z;
                var w = b.w - a.w;
                return Math.sqrt(x * x + y * y + z * z + w * w);
              };

              Vec4.squaredDistance = function squaredDistance(a, b) {
                var x = b.x - a.x;
                var y = b.y - a.y;
                var z = b.z - a.z;
                var w = b.w - a.w;
                return x * x + y * y + z * z + w * w;
              };

              Vec4.len = function len(a) {
                var x = a.x;
                var y = a.y;
                var z = a.z;
                var w = a.w;
                return Math.sqrt(x * x + y * y + z * z + w * w);
              };

              Vec4.lengthSqr = function lengthSqr(a) {
                var x = a.x;
                var y = a.y;
                var z = a.z;
                var w = a.w;
                return x * x + y * y + z * z + w * w;
              };

              Vec4.negate = function negate(out, a) {
                out.x = -a.x;
                out.y = -a.y;
                out.z = -a.z;
                out.w = -a.w;
                return out;
              };

              Vec4.inverse = function inverse(out, a) {
                out.x = 1.0 / a.x;
                out.y = 1.0 / a.y;
                out.z = 1.0 / a.z;
                out.w = 1.0 / a.w;
                return out;
              };

              Vec4.inverseSafe = function inverseSafe(out, a) {
                var x = a.x;
                var y = a.y;
                var z = a.z;
                var w = a.w;

                if (Math.abs(x) < EPSILON) {
                  out.x = 0;
                } else {
                  out.x = 1.0 / x;
                }

                if (Math.abs(y) < EPSILON) {
                  out.y = 0;
                } else {
                  out.y = 1.0 / y;
                }

                if (Math.abs(z) < EPSILON) {
                  out.z = 0;
                } else {
                  out.z = 1.0 / z;
                }

                if (Math.abs(w) < EPSILON) {
                  out.w = 0;
                } else {
                  out.w = 1.0 / w;
                }

                return out;
              };

              Vec4.normalize = function normalize(out, a) {
                var x = a.x;
                var y = a.y;
                var z = a.z;
                var w = a.w;
                var len = x * x + y * y + z * z + w * w;

                if (len > 0) {
                  len = 1 / Math.sqrt(len);
                  out.x = x * len;
                  out.y = y * len;
                  out.z = z * len;
                  out.w = w * len;
                }

                return out;
              };

              Vec4.dot = function dot(a, b) {
                return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
              };

              Vec4.lerp = function lerp(out, a, b, t) {
                out.x = a.x + t * (b.x - a.x);
                out.y = a.y + t * (b.y - a.y);
                out.z = a.z + t * (b.z - a.z);
                out.w = a.w + t * (b.w - a.w);
                return out;
              };

              Vec4.random = function random$1(out, scale) {
                scale = scale || 1.0;
                var phi = random() * 2.0 * Math.PI;
                var cosTheta = random() * 2 - 1;
                var sinTheta = Math.sqrt(1 - cosTheta * cosTheta);
                out.x = sinTheta * Math.cos(phi) * scale;
                out.y = sinTheta * Math.sin(phi) * scale;
                out.z = cosTheta * scale;
                out.w = 0;
                return out;
              };

              Vec4.transformMat4 = function transformMat4(out, a, m) {
                var x = a.x;
                var y = a.y;
                var z = a.z;
                var w = a.w;
                out.x = m.m00 * x + m.m04 * y + m.m08 * z + m.m12 * w;
                out.y = m.m01 * x + m.m05 * y + m.m09 * z + m.m13 * w;
                out.z = m.m02 * x + m.m06 * y + m.m10 * z + m.m14 * w;
                out.w = m.m03 * x + m.m07 * y + m.m11 * z + m.m15 * w;
                return out;
              };

              Vec4.transformAffine = function transformAffine(out, v, m) {
                var x = v.x;
                var y = v.y;
                var z = v.z;
                var w = v.w;
                out.x = m.m00 * x + m.m01 * y + m.m02 * z + m.m03 * w;
                out.y = m.m04 * x + m.m05 * y + m.m06 * z + m.m07 * w;
                out.x = m.m08 * x + m.m09 * y + m.m10 * z + m.m11 * w;
                out.w = v.w;
                return out;
              };

              Vec4.transformQuat = function transformQuat(out, a, q) {
                var x = a.x,
                    y = a.y,
                    z = a.z;
                var _x = q.x;
                var _y = q.y;
                var _z = q.z;
                var _w = q.w;
                var ix = _w * x + _y * z - _z * y;
                var iy = _w * y + _z * x - _x * z;
                var iz = _w * z + _x * y - _y * x;
                var iw = -_x * x - _y * y - _z * z;
                out.x = ix * _w + iw * -_x + iy * -_z - iz * -_y;
                out.y = iy * _w + iw * -_y + iz * -_x - ix * -_z;
                out.z = iz * _w + iw * -_z + ix * -_y - iy * -_x;
                out.w = a.w;
                return out;
              };

              Vec4.toArray = function toArray(out, v, ofs) {
                if (ofs === void 0) {
                  ofs = 0;
                }

                out[ofs + 0] = v.x;
                out[ofs + 1] = v.y;
                out[ofs + 2] = v.z;
                out[ofs + 3] = v.w;
                return out;
              };

              Vec4.fromArray = function fromArray(out, arr, ofs) {
                if (ofs === void 0) {
                  ofs = 0;
                }

                out.x = arr[ofs + 0];
                out.y = arr[ofs + 1];
                out.z = arr[ofs + 2];
                out.w = arr[ofs + 3];
                return out;
              };

              Vec4.strictEquals = function strictEquals(a, b) {
                return a.x === b.x && a.y === b.y && a.z === b.z && a.w === b.w;
              };

              Vec4.equals = function equals(a, b, epsilon) {
                if (epsilon === void 0) {
                  epsilon = EPSILON;
                }

                return Math.abs(a.x - b.x) <= epsilon * Math.max(1.0, Math.abs(a.x), Math.abs(b.x)) && Math.abs(a.y - b.y) <= epsilon * Math.max(1.0, Math.abs(a.y), Math.abs(b.y)) && Math.abs(a.z - b.z) <= epsilon * Math.max(1.0, Math.abs(a.z), Math.abs(b.z)) && Math.abs(a.w - b.w) <= epsilon * Math.max(1.0, Math.abs(a.w), Math.abs(b.w));
              };

              function Vec4(x, y, z, w) {
                var _this;

                _this = _ValueType.call(this) || this;

                if (x && typeof x === 'object') {
                  _this.x = x.x;
                  _this.y = x.y;
                  _this.z = x.z;
                  _this.w = x.w;
                } else {
                  _this.x = x || 0;
                  _this.y = y || 0;
                  _this.z = z || 0;
                  _this.w = w || 0;
                }

                return _this;
              }

              var _proto = Vec4.prototype;

              _proto.clone = function clone() {
                return new Vec4(this.x, this.y, this.z, this.w);
              };

              _proto.set = function set(x, y, z, w) {
                if (x && typeof x === 'object') {
                  this.x = x.x;
                  this.y = x.y;
                  this.z = x.z;
                  this.w = x.w;
                } else {
                  this.x = x || 0;
                  this.y = y || 0;
                  this.z = z || 0;
                  this.w = w || 0;
                }

                return this;
              };

              _proto.equals = function equals(other, epsilon) {
                if (epsilon === void 0) {
                  epsilon = EPSILON;
                }

                return Math.abs(this.x - other.x) <= epsilon * Math.max(1.0, Math.abs(this.x), Math.abs(other.x)) && Math.abs(this.y - other.y) <= epsilon * Math.max(1.0, Math.abs(this.y), Math.abs(other.y)) && Math.abs(this.z - other.z) <= epsilon * Math.max(1.0, Math.abs(this.z), Math.abs(other.z)) && Math.abs(this.w - other.w) <= epsilon * Math.max(1.0, Math.abs(this.w), Math.abs(other.w));
              };

              _proto.equals4f = function equals4f(x, y, z, w, epsilon) {
                if (epsilon === void 0) {
                  epsilon = EPSILON;
                }

                return Math.abs(this.x - x) <= epsilon * Math.max(1.0, Math.abs(this.x), Math.abs(x)) && Math.abs(this.y - y) <= epsilon * Math.max(1.0, Math.abs(this.y), Math.abs(y)) && Math.abs(this.z - z) <= epsilon * Math.max(1.0, Math.abs(this.z), Math.abs(z)) && Math.abs(this.w - w) <= epsilon * Math.max(1.0, Math.abs(this.w), Math.abs(w));
              };

              _proto.strictEquals = function strictEquals(other) {
                return this.x === other.x && this.y === other.y && this.z === other.z && this.w === other.w;
              };

              _proto.strictEquals4f = function strictEquals4f(x, y, z, w) {
                return this.x === x && this.y === y && this.z === z && this.w === w;
              };

              _proto.lerp = function lerp(to, ratio) {
                var x = this.x;
                var y = this.y;
                var z = this.z;
                var w = this.w;
                this.x = x + ratio * (to.x - x);
                this.y = y + ratio * (to.y - y);
                this.z = z + ratio * (to.z - z);
                this.w = w + ratio * (to.w - w);
                return this;
              };

              _proto.toString = function toString() {
                return "(" + this.x.toFixed(2) + ", " + this.y.toFixed(2) + ", " + this.z.toFixed(2) + ", " + this.w.toFixed(2) + ")";
              };

              _proto.clampf = function clampf(minInclusive, maxInclusive) {
                this.x = clamp(this.x, minInclusive.x, maxInclusive.x);
                this.y = clamp(this.y, minInclusive.y, maxInclusive.y);
                this.z = clamp(this.z, minInclusive.z, maxInclusive.z);
                this.w = clamp(this.w, minInclusive.w, maxInclusive.w);
                return this;
              };

              _proto.add = function add(other) {
                this.x += other.x;
                this.y += other.y;
                this.z += other.z;
                this.w += other.w;
                return this;
              };

              _proto.add4f = function add4f(x, y, z, w) {
                this.x += x;
                this.y += y;
                this.z += z;
                this.w += w;
                return this;
              };

              _proto.subtract = function subtract(other) {
                this.x -= other.x;
                this.y -= other.y;
                this.z -= other.z;
                this.w -= other.w;
                return this;
              };

              _proto.subtract4f = function subtract4f(x, y, z, w) {
                this.x -= x;
                this.y -= y;
                this.z -= z;
                this.w -= w;
                return this;
              };

              _proto.multiplyScalar = function multiplyScalar(scalar) {
                if (typeof scalar === 'object') {
                  console.warn('should use Vec4.multiply for vector * vector operation');
                }

                this.x *= scalar;
                this.y *= scalar;
                this.z *= scalar;
                this.w *= scalar;
                return this;
              };

              _proto.multiply = function multiply(other) {
                if (typeof other !== 'object') {
                  console.warn('should use Vec4.scale for vector * scalar operation');
                }

                this.x *= other.x;
                this.y *= other.y;
                this.z *= other.z;
                this.w *= other.w;
                return this;
              };

              _proto.multiply4f = function multiply4f(x, y, z, w) {
                this.x *= x;
                this.y *= y;
                this.z *= z;
                this.w *= w;
                return this;
              };

              _proto.divide = function divide(other) {
                this.x /= other.x;
                this.y /= other.y;
                this.z /= other.z;
                this.w /= other.w;
                return this;
              };

              _proto.divide4f = function divide4f(x, y, z, w) {
                this.x /= x;
                this.y /= y;
                this.z /= z;
                this.w /= w;
                return this;
              };

              _proto.negative = function negative() {
                this.x = -this.x;
                this.y = -this.y;
                this.z = -this.z;
                this.w = -this.w;
                return this;
              };

              _proto.dot = function dot(vector) {
                return this.x * vector.x + this.y * vector.y + this.z * vector.z + this.w * vector.w;
              };

              _proto.cross = function cross(vector) {
                var ax = this.x,
                    ay = this.y,
                    az = this.z;
                var bx = vector.x,
                    by = vector.y,
                    bz = vector.z;
                this.x = ay * bz - az * by;
                this.y = az * bx - ax * bz;
                this.z = ax * by - ay * bx;
                return this;
              };

              _proto.length = function length() {
                var x = this.x;
                var y = this.y;
                var z = this.z;
                var w = this.w;
                return Math.sqrt(x * x + y * y + z * z + w * w);
              };

              _proto.lengthSqr = function lengthSqr() {
                var x = this.x;
                var y = this.y;
                var z = this.z;
                var w = this.w;
                return x * x + y * y + z * z + w * w;
              };

              _proto.normalize = function normalize() {
                var x = this.x;
                var y = this.y;
                var z = this.z;
                var w = this.w;
                var len = x * x + y * y + z * z + w * w;

                if (len > 0) {
                  len = 1 / Math.sqrt(len);
                  this.x = x * len;
                  this.y = y * len;
                  this.z = z * len;
                  this.w = w * len;
                }

                return this;
              };

              _proto.transformMat4 = function transformMat4(matrix) {
                var x = this.x;
                var y = this.y;
                var z = this.z;
                var w = this.w;
                this.x = matrix.m00 * x + matrix.m04 * y + matrix.m08 * z + matrix.m12 * w;
                this.y = matrix.m01 * x + matrix.m05 * y + matrix.m09 * z + matrix.m13 * w;
                this.z = matrix.m02 * x + matrix.m06 * y + matrix.m10 * z + matrix.m14 * w;
                this.w = matrix.m03 * x + matrix.m07 * y + matrix.m11 * z + matrix.m15 * w;
                return this;
              };

              return Vec4;
            }(ValueType));
            Vec4.ZERO = Object.freeze(new Vec4(0, 0, 0, 0));
            Vec4.ONE = Object.freeze(new Vec4(1, 1, 1, 1));
            Vec4.NEG_ONE = Object.freeze(new Vec4(-1, -1, -1, -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;

            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, 'Color', [{
              name: 'sub',
              newName: 'subtract',
              target: Color,
              targetName: 'Color'
            }, {
              name: 'mul',
              newName: 'multiply',
              target: Color,
              targetName: 'Color'
            }, {
              name: 'div',
              newName: 'divide',
              target: Color,
              targetName: 'Color'
            }, {
              name: 'exactEquals',
              newName: 'strictEquals',
              target: Color,
              targetName: 'Color'
            }, {
              name: 'fromHex',
              newName: 'fromHEX',
              customFunction: function customFunction() {
                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                var 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'
            }]);

            var AffineTransform = exports('AffineTransform', function () {
              AffineTransform.identity = function identity() {
                return new AffineTransform();
              };

              AffineTransform.clone = function clone(affineTransform) {
                return new AffineTransform(affineTransform.a, affineTransform.b, affineTransform.c, affineTransform.d, affineTransform.tx, affineTransform.ty);
              };

              AffineTransform.concat = function concat(out, t1, t2) {
                var a = t1.a;
                var b = t1.b;
                var c = t1.c;
                var d = t1.d;
                var tx = t1.tx;
                var ty = t1.ty;
                out.a = a * t2.a + b * t2.c;
                out.b = a * t2.b + b * t2.d;
                out.c = c * t2.a + d * t2.c;
                out.d = c * t2.b + d * t2.d;
                out.tx = tx * t2.a + ty * t2.c + t2.tx;
                out.ty = tx * t2.b + ty * t2.d + t2.ty;
              };

              AffineTransform.invert = function invert(out, t) {
                var determinant = 1 / (t.a * t.d - t.b * t.c);
                out.a = determinant * t.d;
                out.b = -determinant * t.b;
                out.c = -determinant * t.c;
                out.d = determinant * t.a;
                out.tx = determinant * (t.c * t.ty - t.d * t.tx);
                out.ty = determinant * (t.b * t.tx - t.a * t.ty);
              };

              AffineTransform.fromMat4 = function fromMat4(out, mat) {
                out.a = mat.m00;
                out.b = mat.m01;
                out.c = mat.m04;
                out.d = mat.m05;
                out.tx = mat.m12;
                out.ty = mat.m13;
              };

              AffineTransform.transformVec2 = function transformVec2(out, point, transOrY, t) {
                var x;
                var y;

                if (t === undefined) {
                  t = transOrY;
                  x = point.x;
                  y = point.y;
                } else {
                  x = point;
                  y = transOrY;
                }

                out.x = t.a * x + t.c * y + t.tx;
                out.y = t.b * x + t.d * y + t.ty;
              };

              AffineTransform.transformSize = function transformSize(out, size, t) {
                out.width = t.a * size.width + t.c * size.height;
                out.height = t.b * size.width + t.d * size.height;
              };

              AffineTransform.transformRect = function transformRect(out, rect, t) {
                var or = rect.x + rect.width;
                var ot = rect.y + rect.height;
                var lbx = t.a * rect.x + t.c * rect.y + t.tx;
                var lby = t.b * rect.x + t.d * rect.y + t.ty;
                var rbx = t.a * or + t.c * rect.y + t.tx;
                var rby = t.b * or + t.d * rect.y + t.ty;
                var ltx = t.a * rect.x + t.c * ot + t.tx;
                var lty = t.b * rect.x + t.d * ot + t.ty;
                var rtx = t.a * or + t.c * ot + t.tx;
                var rty = t.b * or + t.d * ot + t.ty;
                var minX = Math.min(lbx, rbx, ltx, rtx);
                var maxX = Math.max(lbx, rbx, ltx, rtx);
                var minY = Math.min(lby, rby, lty, rty);
                var maxY = Math.max(lby, rby, lty, rty);
                out.x = minX;
                out.y = minY;
                out.width = maxX - minX;
                out.height = maxY - minY;
              };

              AffineTransform.transformObb = function transformObb(out_bl, out_tl, out_tr, out_br, rect, anAffineTransform) {
                var tx = anAffineTransform.a * rect.x + anAffineTransform.c * rect.y + anAffineTransform.tx;
                var ty = anAffineTransform.b * rect.x + anAffineTransform.d * rect.y + anAffineTransform.ty;
                var xa = anAffineTransform.a * rect.width;
                var xb = anAffineTransform.b * rect.width;
                var yc = anAffineTransform.c * rect.height;
                var yd = anAffineTransform.d * rect.height;
                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;
              };

              function AffineTransform(a, b, c, d, tx, ty) {
                if (a === void 0) {
                  a = 1;
                }

                if (b === void 0) {
                  b = 0;
                }

                if (c === void 0) {
                  c = 0;
                }

                if (d === void 0) {
                  d = 1;
                }

                if (tx === void 0) {
                  tx = 0;
                }

                if (ty === void 0) {
                  ty = 0;
                }

                this.a = a;
                this.b = b;
                this.c = c;
                this.d = d;
                this.tx = tx;
                this.ty = ty;
              }

              return AffineTransform;
            }());
            legacyCC.AffineTransform = AffineTransform;

            var Size = exports('Size', function (_ValueType) {
              _inheritsLoose(Size, _ValueType);

              Size.lerp = function lerp(out, from, to, ratio) {
                out.width = from.width + (to.width - from.width) * ratio;
                out.height = from.height + (to.height - from.height) * ratio;
                return out;
              };

              function Size(width, height) {
                var _this;

                _this = _ValueType.call(this) || this;

                if (width && typeof width === 'object') {
                  _this.width = width.width;
                  _this.height = width.height;
                } else {
                  _this.width = width || 0;
                  _this.height = height || 0;
                }

                return _this;
              }

              var _proto = Size.prototype;

              _proto.clone = function clone() {
                return new Size(this.width, this.height);
              };

              _proto.set = function set(width, height) {
                if (width && typeof width === 'object') {
                  this.height = width.height;
                  this.width = width.width;
                } else {
                  this.width = width || 0;
                  this.height = height || 0;
                }

                return this;
              };

              _proto.equals = function equals(other) {
                return this.width === other.width && this.height === other.height;
              };

              _proto.lerp = function lerp(to, ratio) {
                this.width += (to.width - this.width) * ratio;
                this.height += (to.height - this.height) * ratio;
                return this;
              };

              _proto.toString = function toString() {
                return "(" + this.width.toFixed(2) + ", " + this.height.toFixed(2) + ")";
              };

              _createClass(Size, [{
                key: "x",
                get: function get() {
                  return this.width;
                },
                set: function set(val) {
                  this.width = val;
                }
              }, {
                key: "y",
                get: function get() {
                  return this.height;
                },
                set: function set(val) {
                  this.height = val;
                }
              }]);

              return Size;
            }(ValueType));
            Size.ZERO = Object.freeze(new Size(0, 0));
            Size.ONE = Object.freeze(new Size(1, 1));
            CCClass.fastDefine('cc.Size', Size, {
              width: 0,
              height: 0
            });
            function size(width, height) {
              if (width === void 0) {
                width = 0;
              }

              if (height === void 0) {
                height = 0;
              }

              return new Size(width, height);
            }
            legacyCC.size = size;
            legacyCC.Size = Size;

            var Rect = exports('Rect', function (_ValueType) {
              _inheritsLoose(Rect, _ValueType);

              Rect.fromMinMax = function fromMinMax(out, v1, v2) {
                var minX = Math.min(v1.x, v2.x);
                var minY = Math.min(v1.y, v2.y);
                var maxX = Math.max(v1.x, v2.x);
                var maxY = Math.max(v1.y, v2.y);
                out.x = minX;
                out.y = minY;
                out.width = maxX - minX;
                out.height = maxY - minY;
                return out;
              };

              Rect.lerp = function lerp(out, from, to, ratio) {
                var x = from.x;
                var y = from.y;
                var w = from.width;
                var h = from.height;
                out.x = x + (to.x - x) * ratio;
                out.y = y + (to.y - y) * ratio;
                out.width = w + (to.width - w) * ratio;
                out.height = h + (to.height - h) * ratio;
                return out;
              };

              Rect.intersection = function intersection(out, one, other) {
                var axMin = one.x;
                var ayMin = one.y;
                var axMax = one.x + one.width;
                var ayMax = one.y + one.height;
                var bxMin = other.x;
                var byMin = other.y;
                var bxMax = other.x + other.width;
                var byMax = other.y + other.height;
                out.x = Math.max(axMin, bxMin);
                out.y = Math.max(ayMin, byMin);
                out.width = Math.min(axMax, bxMax) - out.x;
                out.height = Math.min(ayMax, byMax) - out.y;
                return out;
              };

              Rect.union = function union(out, one, other) {
                var x = one.x;
                var y = one.y;
                var w = one.width;
                var h = one.height;
                var bx = other.x;
                var by = other.y;
                var bw = other.width;
                var bh = other.height;
                out.x = Math.min(x, bx);
                out.y = Math.min(y, by);
                out.width = Math.max(x + w, bx + bw) - out.x;
                out.height = Math.max(y + h, by + bh) - out.y;
                return out;
              };

              function Rect(x, y, width, height) {
                var _this;

                _this = _ValueType.call(this) || this;

                if (x && typeof x === 'object') {
                  _this.y = x.y;
                  _this.width = x.width;
                  _this.height = x.height;
                  _this.x = x.x;
                } else {
                  _this.x = x || 0;
                  _this.y = y || 0;
                  _this.width = width || 0;
                  _this.height = height || 0;
                }

                return _this;
              }

              var _proto = Rect.prototype;

              _proto.clone = function clone() {
                return new Rect(this.x, this.y, this.width, this.height);
              };

              _proto.set = function set(x, y, width, height) {
                if (x && typeof x === 'object') {
                  this.y = x.y;
                  this.width = x.width;
                  this.height = x.height;
                  this.x = x.x;
                } else {
                  this.x = x || 0;
                  this.y = y || 0;
                  this.width = width || 0;
                  this.height = height || 0;
                }

                return this;
              };

              _proto.equals = function equals(other) {
                return this.x === other.x && this.y === other.y && this.width === other.width && this.height === other.height;
              };

              _proto.lerp = function lerp(to, ratio) {
                var x = this.x;
                var y = this.y;
                var w = this.width;
                var h = this.height;
                this.x = x + (to.x - x) * ratio;
                this.y = y + (to.y - y) * ratio;
                this.width = w + (to.width - w) * ratio;
                this.height = h + (to.height - h) * ratio;
                return this;
              };

              _proto.toString = function toString() {
                return "(" + this.x.toFixed(2) + ", " + this.y.toFixed(2) + ", " + this.width.toFixed(2) + ", " + this.height.toFixed(2) + ")";
              };

              _proto.intersects = function intersects(other) {
                var maxax = this.x + this.width;
                var maxay = this.y + this.height;
                var maxbx = other.x + other.width;
                var maxby = other.y + other.height;
                return !(maxax < other.x || maxbx < this.x || maxay < other.y || maxby < this.y);
              };

              _proto.contains = function contains(point) {
                return this.x <= point.x && this.x + this.width >= point.x && this.y <= point.y && this.y + this.height >= point.y;
              };

              _proto.containsRect = function containsRect(other) {
                return this.x <= other.x && this.x + this.width >= other.x + other.width && this.y <= other.y && this.y + this.height >= other.y + other.height;
              };

              _proto.transformMat4 = function transformMat4(mat) {
                var ol = this.x;
                var ob = this.y;
                var or = ol + this.width;
                var ot = ob + this.height;
                var lbx = mat.m00 * ol + mat.m04 * ob + mat.m12;
                var lby = mat.m01 * ol + mat.m05 * ob + mat.m13;
                var rbx = mat.m00 * or + mat.m04 * ob + mat.m12;
                var rby = mat.m01 * or + mat.m05 * ob + mat.m13;
                var ltx = mat.m00 * ol + mat.m04 * ot + mat.m12;
                var lty = mat.m01 * ol + mat.m05 * ot + mat.m13;
                var rtx = mat.m00 * or + mat.m04 * ot + mat.m12;
                var rty = mat.m01 * or + mat.m05 * ot + mat.m13;
                var minX = Math.min(lbx, rbx, ltx, rtx);
                var maxX = Math.max(lbx, rbx, ltx, rtx);
                var minY = Math.min(lby, rby, lty, rty);
                var maxY = Math.max(lby, rby, lty, rty);
                this.x = minX;
                this.y = minY;
                this.width = maxX - minX;
                this.height = maxY - minY;
                return this;
              };

              _proto.transformMat4ToPoints = function transformMat4ToPoints(mat, out_lb, out_lt, out_rt, out_rb) {
                var ol = this.x;
                var ob = this.y;
                var or = ol + this.width;
                var ot = ob + this.height;
                out_lb.x = mat.m00 * ol + mat.m04 * ob + mat.m12;
                out_lb.y = mat.m01 * ol + mat.m05 * ob + mat.m13;
                out_rb.x = mat.m00 * or + mat.m04 * ob + mat.m12;
                out_rb.y = mat.m01 * or + mat.m05 * ob + mat.m13;
                out_lt.x = mat.m00 * ol + mat.m04 * ot + mat.m12;
                out_lt.y = mat.m01 * ol + mat.m05 * ot + mat.m13;
                out_rt.x = mat.m00 * or + mat.m04 * ot + mat.m12;
                out_rt.y = mat.m01 * or + mat.m05 * ot + mat.m13;
              };

              _createClass(Rect, [{
                key: "xMin",
                get: function get() {
                  return this.x;
                },
                set: function set(value) {
                  this.width += this.x - value;
                  this.x = value;
                }
              }, {
                key: "yMin",
                get: function get() {
                  return this.y;
                },
                set: function set(value) {
                  this.height += this.y - value;
                  this.y = value;
                }
              }, {
                key: "xMax",
                get: function get() {
                  return this.x + this.width;
                },
                set: function set(value) {
                  this.width = value - this.x;
                }
              }, {
                key: "yMax",
                get: function get() {
                  return this.y + this.height;
                },
                set: function set(value) {
                  this.height = value - this.y;
                }
              }, {
                key: "center",
                get: function get() {
                  return new Vec2(this.x + this.width * 0.5, this.y + this.height * 0.5);
                },
                set: function set(value) {
                  this.x = value.x - this.width * 0.5;
                  this.y = value.y - this.height * 0.5;
                }
              }, {
                key: "origin",
                get: function get() {
                  return new Vec2(this.x, this.y);
                },
                set: function set(value) {
                  this.x = value.x;
                  this.y = value.y;
                }
              }, {
                key: "size",
                get: function get() {
                  return new Size(this.width, this.height);
                },
                set: function set(value) {
                  this.width = value.width;
                  this.height = value.height;
                }
              }, {
                key: "z",
                get: function get() {
                  return this.width;
                },
                set: function set(val) {
                  this.width = val;
                }
              }, {
                key: "w",
                get: function get() {
                  return this.height;
                },
                set: function set(val) {
                  this.height = val;
                }
              }]);

              return Rect;
            }(ValueType));
            CCClass.fastDefine('cc.Rect', Rect, {
              x: 0,
              y: 0,
              width: 0,
              height: 0
            });
            legacyCC.Rect = Rect;
            function rect(x, y, width, height) {
              if (x === void 0) {
                x = 0;
              }

              if (y === void 0) {
                y = 0;
              }

              if (width === void 0) {
                width = 0;
              }

              if (height === void 0) {
                height = 0;
              }

              return new Rect(x, y, width, height);
            }
            legacyCC.rect = rect;

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

            var Pool$1 = exports('Pool', function () {
              function Pool(ctor, elementsPerBatch) {
                this._ctor = void 0;
                this._elementsPerBatch = void 0;
                this._nextAvail = void 0;
                this._freepool = [];
                this._ctor = ctor;
                this._elementsPerBatch = Math.max(elementsPerBatch, 1);
                this._nextAvail = this._elementsPerBatch - 1;

                for (var i = 0; i < this._elementsPerBatch; ++i) {
                  this._freepool.push(ctor());
                }
              }

              var _proto = Pool.prototype;

              _proto.alloc = function alloc() {
                if (this._nextAvail < 0) {
                  var elementsPerBatch = this._elementsPerBatch;

                  for (var i = 0; i < elementsPerBatch; i++) {
                    this._freepool.push(this._ctor());
                  }

                  this._nextAvail = elementsPerBatch - 1;
                }

                var ret = this._freepool[this._nextAvail--];
                this._freepool.length--;
                return ret;
              };

              _proto.free = function free(obj) {
                this._freepool.push(obj);

                this._nextAvail++;
              };

              _proto.freeArray = function freeArray(objs) {
                Array.prototype.push.apply(this._freepool, objs);
                this._nextAvail += objs.length;
              };

              _proto.destroy = function destroy(dtor) {
                if (dtor) {
                  for (var i = 0; i <= this._nextAvail; i++) {
                    dtor(this._freepool[i]);
                  }
                }

                this._freepool.length = 0;
                this._nextAvail = -1;
              };

              return Pool;
            }());

            var RecyclePool = exports('RecyclePool', function () {
              function RecyclePool(fn, size) {
                this._fn = void 0;
                this._count = 0;
                this._data = void 0;
                this._fn = fn;
                this._data = new Array(size);

                for (var i = 0; i < size; ++i) {
                  this._data[i] = fn();
                }
              }

              var _proto = RecyclePool.prototype;

              _proto.reset = function reset() {
                this._count = 0;
              };

              _proto.resize = function resize(size) {
                if (size > this._data.length) {
                  for (var i = this._data.length; i < size; ++i) {
                    this._data[i] = this._fn();
                  }
                }
              };

              _proto.add = function add() {
                if (this._count >= this._data.length) {
                  this.resize(this._data.length * 2);
                }

                return this._data[this._count++];
              };

              _proto.removeAt = function removeAt(idx) {
                if (idx >= this._count) {
                  return;
                }

                var last = this._count - 1;
                var tmp = this._data[idx];
                this._data[idx] = this._data[last];
                this._data[last] = tmp;
                this._count -= 1;
              };

              _createClass(RecyclePool, [{
                key: "length",
                get: function get() {
                  return this._count;
                }
              }, {
                key: "data",
                get: function get() {
                  return this._data;
                }
              }]);

              return RecyclePool;
            }());

            var CachedArray = exports('CachedArray', function () {
              function CachedArray(length, compareFn) {
                this.array = void 0;
                this.length = 0;
                this._compareFn = void 0;
                this.array = new Array(length);
                this.length = 0;

                if (compareFn !== undefined) {
                  this._compareFn = compareFn;
                } else {
                  this._compareFn = function (a, b) {
                    return a - b;
                  };
                }
              }

              var _proto = CachedArray.prototype;

              _proto.push = function push(item) {
                this.array[this.length++] = item;
              };

              _proto.pop = function pop() {
                return this.array[--this.length];
              };

              _proto.get = function get(idx) {
                return this.array[idx];
              };

              _proto.clear = function clear() {
                this.length = 0;
              };

              _proto.destroy = function destroy() {
                this.length = 0;
                this.array.length = 0;
              };

              _proto.sort = function sort() {
                this.array.length = this.length;
                this.array.sort(this._compareFn);
              };

              _proto.concat = function concat(array) {
                for (var i = 0; i < array.length; ++i) {
                  this.array[this.length++] = array[i];
                }
              };

              _proto.fastRemove = function fastRemove(idx) {
                if (idx >= this.length || idx < 0) {
                  return;
                }

                var last = --this.length;
                this.array[idx] = this.array[last];
              };

              _proto.indexOf = function indexOf(val) {
                return this.array.indexOf(val);
              };

              return CachedArray;
            }());

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

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

            var _CCClass$fastDefine;
            var Destroyed = 1 << 0;
            var ToDestroy = 1 << 2;
            var DontSave = 1 << 3;
            var EditorOnly = 1 << 4;
            var Dirty = 1 << 5;
            var DontDestroy = 1 << 6;
            var Destroying = 1 << 7;
            var Deactivating = 1 << 8;
            var LockedInEditor = 1 << 9;
            var HideInHierarchy = 1 << 10;
            var IsOnEnableCalled = 1 << 11;
            var IsEditorOnEnableCalled = 1 << 12;
            var IsPreloadStarted = 1 << 13;
            var IsOnLoadCalled = 1 << 14;
            var IsOnLoadStarted = 1 << 15;
            var IsStartCalled = 1 << 16;
            var IsRotationLocked = 1 << 17;
            var IsScaleLocked = 1 << 18;
            var IsAnchorLocked = 1 << 19;
            var IsSizeLocked = 1 << 20;
            var IsPositionLocked = 1 << 21;
            var PersistentMask = ~(ToDestroy | Dirty | Destroying | DontDestroy | Deactivating | IsPreloadStarted | IsOnLoadStarted | IsOnLoadCalled | IsStartCalled | IsOnEnableCalled | IsEditorOnEnableCalled | IsRotationLocked | IsScaleLocked | IsAnchorLocked | IsSizeLocked | IsPositionLocked);
            var AllHideMasks = DontSave | EditorOnly | LockedInEditor | HideInHierarchy;
            var objectsToDestroy = [];

            function compileDestruct(obj, ctor) {
              var shouldSkipId = obj instanceof legacyCC._BaseNode || obj instanceof legacyCC.Component;
              var idToSkip = shouldSkipId ? '_id' : null;
              var key;
              var propsToReset = {};

              for (key in obj) {
                if (obj.hasOwnProperty(key)) {
                  if (key === idToSkip) {
                    continue;
                  }

                  switch (typeof obj[key]) {
                    case 'string':
                      propsToReset[key] = '';
                      break;

                    case 'object':
                    case 'function':
                      propsToReset[key] = null;
                      break;
                  }
                }
              }

              if (CCClass._isCCClass(ctor)) {
                var attrs = legacyCC.Class.Attr.getClassAttrs(ctor);
                var propList = ctor.__props__;

                for (var i = 0; i < propList.length; i++) {
                  key = propList[i];
                  var attrKey = key + legacyCC.Class.Attr.DELIMETER + "default";

                  if (attrKey in attrs) {
                    if (shouldSkipId && key === '_id') {
                      continue;
                    }

                    switch (typeof attrs[attrKey]) {
                      case 'string':
                        propsToReset[key] = '';
                        break;

                      case 'object':
                      case 'function':
                        propsToReset[key] = null;
                        break;

                      case 'undefined':
                        propsToReset[key] = undefined;
                        break;
                    }
                  }
                }
              }

              {
                var func = '';

                for (key in propsToReset) {
                  var statement = void 0;

                  if (CCClass.IDENTIFIER_RE.test(key)) {
                    statement = "o." + key + "=";
                  } else {
                    statement = "o[" + CCClass.escapeForJS(key) + "]=";
                  }

                  var val = propsToReset[key];

                  if (val === '') {
                    val = '""';
                  }

                  func += statement + val + ";\n";
                }

                return Function('o', func);
              }
            }

            var CCObject = exports('CCObject', function () {
              CCObject._deferredDestroy = function _deferredDestroy() {
                var deleteCount = objectsToDestroy.length;

                for (var i = 0; i < deleteCount; ++i) {
                  var obj = objectsToDestroy[i];

                  if (!(obj._objFlags & Destroyed)) {
                    obj._destroyImmediate();
                  }
                }

                if (deleteCount === objectsToDestroy.length) {
                  objectsToDestroy.length = 0;
                } else {
                  objectsToDestroy.splice(0, deleteCount);
                }
              };

              function CCObject(name) {
                if (name === void 0) {
                  name = '';
                }

                this._objFlags = void 0;
                this._name = void 0;
                this._name = name;
                this._objFlags = 0;
              }

              var _proto = CCObject.prototype;

              _proto.destroy = function destroy() {
                if (this._objFlags & Destroyed) {
                  warnID(5000);
                  return false;
                }

                if (this._objFlags & ToDestroy) {
                  return false;
                }

                this._objFlags |= ToDestroy;
                objectsToDestroy.push(this);

                return true;
              };

              _proto._destruct = function _destruct() {
                var ctor = this.constructor;
                var destruct = ctor.__destruct__;

                if (!destruct) {
                  destruct = compileDestruct(this, ctor);
                  value(ctor, '__destruct__', destruct, true);
                }

                destruct(this);
              };

              _proto._destroyImmediate = function _destroyImmediate() {
                if (this._objFlags & Destroyed) {
                  errorID(5000);
                  return;
                }

                if (this._onPreDestroy) {
                  this._onPreDestroy();
                }

                {
                  this._destruct();
                }

                this._objFlags |= Destroyed;
              };

              _createClass(CCObject, [{
                key: "name",
                get: function get() {
                  return this._name;
                },
                set: function set(value) {
                  this._name = value;
                }
              }, {
                key: "hideFlags",
                get: function get() {
                  return this._objFlags & CCObject.Flags.AllHideMasks;
                },
                set: function set(hideFlags) {
                  var flags = hideFlags & CCObject.Flags.AllHideMasks;
                  this._objFlags = this._objFlags & ~CCObject.Flags.AllHideMasks | flags;
                }
              }, {
                key: "isValid",
                get: function get() {
                  return !(this._objFlags & Destroyed);
                }
              }]);

              return CCObject;
            }());

            var prototype = CCObject.prototype;

            prototype._deserialize = null;
            prototype._onPreDestroy = null;
            CCClass.fastDefine('cc.Object', CCObject, (_CCClass$fastDefine = {
              _name: '',
              _objFlags: 0
            }, _CCClass$fastDefine[editorExtrasTag] = {}, _CCClass$fastDefine));
            CCClass.Attr.setClassAttr(CCObject, editorExtrasTag, 'editorOnly', true);
            value(CCObject, 'Flags', {
              Destroyed: Destroyed,
              DontSave: DontSave,
              EditorOnly: EditorOnly,
              Dirty: Dirty,
              DontDestroy: DontDestroy,
              PersistentMask: PersistentMask,
              Destroying: Destroying,
              Deactivating: Deactivating,
              LockedInEditor: LockedInEditor,
              HideInHierarchy: HideInHierarchy,
              AllHideMasks: AllHideMasks,
              IsPreloadStarted: IsPreloadStarted,
              IsOnLoadStarted: IsOnLoadStarted,
              IsOnLoadCalled: IsOnLoadCalled,
              IsOnEnableCalled: IsOnEnableCalled,
              IsStartCalled: IsStartCalled,
              IsEditorOnEnableCalled: IsEditorOnEnableCalled,
              IsPositionLocked: IsPositionLocked,
              IsRotationLocked: IsRotationLocked,
              IsScaleLocked: IsScaleLocked,
              IsAnchorLocked: IsAnchorLocked,
              IsSizeLocked: IsSizeLocked
            });
            function isValid(value, strictMode) {
              if (typeof value === 'object') {
                return !!value && !(value._objFlags & (strictMode ? Destroyed | ToDestroy : Destroyed));
              } else {
                return typeof value !== 'undefined';
              }
            }
            legacyCC.isValid = isValid;

            legacyCC.Object = CCObject;

            var fastRemoveAt$1 = array.fastRemoveAt;

            function empty() {}

            var CallbackInfo = function () {
              function CallbackInfo() {
                this.callback = empty;
                this.target = undefined;
                this.once = false;
              }

              var _proto = CallbackInfo.prototype;

              _proto.set = function set(callback, target, once) {
                this.callback = callback || empty;
                this.target = target;
                this.once = !!once;
              };

              _proto.reset = function reset() {
                this.target = undefined;
                this.callback = empty;
                this.once = false;
              };

              _proto.check = function check() {
                if (this.target instanceof CCObject && !isValid(this.target, true)) {
                  return false;
                } else {
                  return true;
                }
              };

              return CallbackInfo;
            }();

            var callbackInfoPool = new Pool$1(function () {
              return new CallbackInfo();
            }, 32);
            var CallbackList = function () {
              function CallbackList() {
                this.callbackInfos = [];
                this.isInvoking = false;
                this.containCanceled = false;
              }

              var _proto2 = CallbackList.prototype;

              _proto2.removeByCallback = function removeByCallback(cb) {
                for (var i = 0; i < this.callbackInfos.length; ++i) {
                  var info = this.callbackInfos[i];

                  if (info && info.callback === cb) {
                    info.reset();
                    callbackInfoPool.free(info);
                    fastRemoveAt$1(this.callbackInfos, i);
                    --i;
                  }
                }
              };

              _proto2.removeByTarget = function removeByTarget(target) {
                for (var i = 0; i < this.callbackInfos.length; ++i) {
                  var info = this.callbackInfos[i];

                  if (info && info.target === target) {
                    info.reset();
                    callbackInfoPool.free(info);
                    fastRemoveAt$1(this.callbackInfos, i);
                    --i;
                  }
                }
              };

              _proto2.cancel = function cancel(index) {
                var info = this.callbackInfos[index];

                if (info) {
                  info.reset();

                  if (this.isInvoking) {
                    this.callbackInfos[index] = null;
                  } else {
                    fastRemoveAt$1(this.callbackInfos, index);
                  }

                  callbackInfoPool.free(info);
                }

                this.containCanceled = true;
              };

              _proto2.cancelAll = function cancelAll() {
                for (var i = 0; i < this.callbackInfos.length; i++) {
                  var info = this.callbackInfos[i];

                  if (info) {
                    info.reset();
                    callbackInfoPool.free(info);
                    this.callbackInfos[i] = null;
                  }
                }

                this.containCanceled = true;
              };

              _proto2.purgeCanceled = function purgeCanceled() {
                for (var i = this.callbackInfos.length - 1; i >= 0; --i) {
                  var info = this.callbackInfos[i];

                  if (!info) {
                    fastRemoveAt$1(this.callbackInfos, i);
                  }
                }

                this.containCanceled = false;
              };

              _proto2.clear = function clear() {
                this.cancelAll();
                this.callbackInfos.length = 0;
                this.isInvoking = false;
                this.containCanceled = false;
              };

              return CallbackList;
            }();
            var MAX_SIZE = 16;
            var callbackListPool = new Pool$1(function () {
              return new CallbackList();
            }, MAX_SIZE);
            var CallbacksInvoker = function () {
              function CallbacksInvoker() {
                this._callbackTable = createMap(true);
              }

              var _proto3 = CallbacksInvoker.prototype;

              _proto3.on = function on(key, callback, target, once) {
                if (!this.hasEventListener(key, callback, target)) {
                  var list = this._callbackTable[key];

                  if (!list) {
                    list = this._callbackTable[key] = callbackListPool.alloc();
                  }

                  var info = callbackInfoPool.alloc();
                  info.set(callback, target, once);
                  list.callbackInfos.push(info);
                }

                return callback;
              };

              _proto3.hasEventListener = function hasEventListener(key, callback, target) {
                var list = this._callbackTable && this._callbackTable[key];

                if (!list) {
                  return false;
                }

                var infos = list.callbackInfos;

                if (!callback) {
                  if (list.isInvoking) {
                    for (var i = 0; i < infos.length; ++i) {
                      if (infos[i]) {
                        return true;
                      }
                    }

                    return false;
                  } else {
                    return infos.length > 0;
                  }
                }

                for (var _i = 0; _i < infos.length; ++_i) {
                  var info = infos[_i];

                  if (info && info.check() && info.callback === callback && info.target === target) {
                    return true;
                  }
                }

                return false;
              };

              _proto3.removeAll = function removeAll(keyOrTarget) {
                if (typeof keyOrTarget === 'string') {
                  var list = this._callbackTable && this._callbackTable[keyOrTarget];

                  if (list) {
                    if (list.isInvoking) {
                      list.cancelAll();
                    } else {
                      list.clear();
                      callbackListPool.free(list);
                      delete this._callbackTable[keyOrTarget];
                    }
                  }
                } else if (keyOrTarget) {
                  for (var key in this._callbackTable) {
                    var _list = this._callbackTable[key];

                    if (_list.isInvoking) {
                      var infos = _list.callbackInfos;

                      for (var i = 0; i < infos.length; ++i) {
                        var info = infos[i];

                        if (info && info.target === keyOrTarget) {
                          _list.cancel(i);
                        }
                      }
                    } else {
                      _list.removeByTarget(keyOrTarget);
                    }
                  }
                }
              };

              _proto3.off = function off(key, callback, target) {
                var list = this._callbackTable && this._callbackTable[key];

                if (list) {
                  var infos = list.callbackInfos;

                  if (callback) {
                    for (var i = 0; i < infos.length; ++i) {
                      var info = infos[i];

                      if (info && info.callback === callback && info.target === target) {
                        list.cancel(i);
                        break;
                      }
                    }
                  } else {
                    this.removeAll(key);
                  }
                }
              };

              _proto3.emit = function emit(key, arg0, arg1, arg2, arg3, arg4) {
                var list = this._callbackTable && this._callbackTable[key];

                if (list) {
                  var rootInvoker = !list.isInvoking;
                  list.isInvoking = true;
                  var infos = list.callbackInfos;

                  for (var i = 0, len = infos.length; i < len; ++i) {
                    var info = infos[i];

                    if (info) {
                      var callback = info.callback;
                      var target = info.target;

                      if (info.once) {
                        this.off(key, callback, target);
                      }

                      if (!info.check()) {
                        this.off(key, callback, target);
                      } else if (target) {
                        callback.call(target, arg0, arg1, arg2, arg3, arg4);
                      } else {
                        callback(arg0, arg1, arg2, arg3, arg4);
                      }
                    }
                  }

                  if (rootInvoker) {
                    list.isInvoking = false;

                    if (list.containCanceled) {
                      list.purgeCanceled();
                    }
                  }
                }
              };

              _proto3.clear = function clear() {
                for (var key in this._callbackTable) {
                  var list = this._callbackTable[key];

                  if (list) {
                    list.clear();
                    callbackListPool.free(list);
                    delete this._callbackTable[key];
                  }
                }
              };

              return CallbacksInvoker;
            }();

            function Eventify(base) {
              var Eventified = function (_ref) {
                _inheritsLoose(Eventified, _ref);

                function Eventified() {
                  var _this;

                  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                    args[_key] = arguments[_key];
                  }

                  _this = _ref.call.apply(_ref, [this].concat(args)) || this;
                  _this._callbackTable = createMap(true);
                  return _this;
                }

                var _proto = Eventified.prototype;

                _proto.once = function once(type, callback, target) {
                  return this.on(type, callback, target, true);
                };

                _proto.targetOff = function targetOff(typeOrTarget) {
                  this.removeAll(typeOrTarget);
                };

                return Eventified;
              }(base);

              var callbacksInvokerPrototype = CallbacksInvoker.prototype;
              var propertyKeys = Object.getOwnPropertyNames(callbacksInvokerPrototype).concat(Object.getOwnPropertySymbols(callbacksInvokerPrototype));

              for (var iPropertyKey = 0; iPropertyKey < propertyKeys.length; ++iPropertyKey) {
                var propertyKey = propertyKeys[iPropertyKey];

                if (!(propertyKey in Eventified.prototype)) {
                  var propertyDescriptor = Object.getOwnPropertyDescriptor(callbacksInvokerPrototype, propertyKey);

                  if (propertyDescriptor) {
                    Object.defineProperty(Eventified.prototype, propertyKey, propertyDescriptor);
                  }
                }
              }

              return Eventified;
            }

            var Empty = function Empty() {};

            var EventTarget = exports('EventTarget', Eventify(Empty));
            legacyCC.EventTarget = EventTarget;

            var BrowserType;

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

            var AppEvent;

            (function (AppEvent) {
              AppEvent["HIDE"] = "hide";
              AppEvent["SHOW"] = "show";
              AppEvent["RESIZE"] = "resize";
              AppEvent["ORIENTATION_CHANGE"] = "orientation_change";
            })(AppEvent || (AppEvent = {}));

            var Language;

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

            var NetworkType;

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

            var OS;

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

            var LEFT = 1 << 2;
            var RIGHT = 1 << 3;
            var Orientation;

            (function (Orientation) {
              Orientation[Orientation["PORTRAIT"] = 1] = "PORTRAIT";
              Orientation[Orientation["PORTRAIT_UPSIDE_DOWN"] = 2] = "PORTRAIT_UPSIDE_DOWN";
              Orientation[Orientation["LANDSCAPE_LEFT"] = LEFT] = "LANDSCAPE_LEFT";
              Orientation[Orientation["LANDSCAPE_RIGHT"] = RIGHT] = "LANDSCAPE_RIGHT";
              Orientation[Orientation["LANDSCAPE"] = LEFT | RIGHT] = "LANDSCAPE";
            })(Orientation || (Orientation = {}));

            var Platform;

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

            var System = function () {
              function System() {
                var _nav$getBattery,
                    _this = this;

                this.networkType = void 0;
                this.isNative = void 0;
                this.isBrowser = void 0;
                this.isMobile = void 0;
                this.isLittleEndian = void 0;
                this.platform = void 0;
                this.language = void 0;
                this.nativeLanguage = void 0;
                this.os = void 0;
                this.osVersion = void 0;
                this.osMainVersion = void 0;
                this.browserType = void 0;
                this.browserVersion = void 0;
                this.pixelRatio = void 0;
                this.supportCapability = void 0;
                this._eventTarget = new EventTarget();
                this._html = void 0;
                this._battery = void 0;
                var nav = window.navigator;
                var ua = nav.userAgent.toLowerCase();
                this._html = document.getElementsByTagName('html')[0];
                (_nav$getBattery = nav.getBattery) === null || _nav$getBattery === void 0 ? void 0 : _nav$getBattery.call(nav).then(function (battery) {
                  _this._battery = battery;
                });
                this.networkType = NetworkType.LAN;
                this.isNative = false;
                this.isBrowser = true;

                {
                  this.isMobile = /mobile|android|iphone|ipad/.test(ua);
                  this.platform = this.isMobile ? Platform.MOBILE_BROWSER : Platform.DESKTOP_BROWSER;
                }

                this.isLittleEndian = function () {
                  var buffer = new ArrayBuffer(2);
                  new DataView(buffer).setInt16(0, 256, true);
                  return new Int16Array(buffer)[0] === 256;
                }();

                var currLanguage = nav.language;
                this.nativeLanguage = currLanguage.toLowerCase();
                currLanguage = currLanguage || nav.browserLanguage;
                currLanguage = currLanguage ? currLanguage.split('-')[0] : Language.ENGLISH;
                this.language = currLanguage;
                var isAndroid = false;
                var iOS = false;
                var osVersion = '';
                var osMajorVersion = 0;
                var uaResult = /android\s*(\d+(?:\.\d+)*)/i.exec(ua) || /android\s*(\d+(?:\.\d+)*)/i.exec(nav.platform);

                if (uaResult) {
                  isAndroid = true;
                  osVersion = uaResult[1] || '';
                  osMajorVersion = parseInt(osVersion) || 0;
                }

                uaResult = /(iPad|iPhone|iPod).*OS ((\d+_?){2,3})/i.exec(ua);

                if (uaResult) {
                  iOS = true;
                  osVersion = uaResult[2] || '';
                  osMajorVersion = parseInt(osVersion) || 0;
                } else if (/(iPhone|iPad|iPod)/.exec(nav.platform) || nav.platform === 'MacIntel' && nav.maxTouchPoints && nav.maxTouchPoints > 1) {
                  iOS = true;
                  osVersion = '';
                  osMajorVersion = 0;
                }

                var osName = OS.UNKNOWN;

                if (nav.appVersion.indexOf('Win') !== -1) {
                  osName = OS.WINDOWS;
                } else if (iOS) {
                  osName = OS.IOS;
                } else if (nav.appVersion.indexOf('Mac') !== -1) {
                  osName = OS.OSX;
                } else if (nav.appVersion.indexOf('X11') !== -1 && nav.appVersion.indexOf('Linux') === -1) {
                  osName = OS.LINUX;
                } else if (isAndroid) {
                  osName = OS.ANDROID;
                } else if (nav.appVersion.indexOf('Linux') !== -1 || ua.indexOf('ubuntu') !== -1) {
                  osName = OS.LINUX;
                }

                this.os = osName;
                this.osVersion = osVersion;
                this.osMainVersion = osMajorVersion;
                this.browserType = BrowserType.UNKNOWN;
                var typeReg0 = /wechat|weixin|micromessenger/i;
                var typeReg1 = /mqqbrowser|micromessenger|qqbrowser|sogou|qzone|liebao|maxthon|ucbs|360 aphone|360browser|baiduboxapp|baidubrowser|maxthon|mxbrowser|miuibrowser/i;
                var typeReg2 = /qq|qqbrowser|ucbrowser|ubrowser|edge|HuaweiBrowser/i;
                var typeReg3 = /chrome|safari|firefox|trident|opera|opr\/|oupeng/i;
                var browserTypes = typeReg0.exec(ua) || typeReg1.exec(ua) || typeReg2.exec(ua) || typeReg3.exec(ua);
                var browserType = browserTypes ? browserTypes[0].toLowerCase() : OS.UNKNOWN;

                if (browserType === 'safari' && isAndroid) {
                  browserType = BrowserType.ANDROID;
                } else if (browserType === 'qq' && /android.*applewebkit/i.test(ua)) {
                  browserType = BrowserType.ANDROID;
                }

                var typeMap = {
                  micromessenger: BrowserType.WECHAT,
                  wechat: BrowserType.WECHAT,
                  weixin: BrowserType.WECHAT,
                  trident: BrowserType.IE,
                  edge: BrowserType.EDGE,
                  '360 aphone': BrowserType.BROWSER_360,
                  mxbrowser: BrowserType.MAXTHON,
                  'opr/': BrowserType.OPERA,
                  ubrowser: BrowserType.UC,
                  huaweibrowser: BrowserType.HUAWEI
                };
                this.browserType = typeMap[browserType] || browserType;
                this.browserVersion = '';
                var versionReg1 = /(mqqbrowser|micromessenger|qqbrowser|sogou|qzone|liebao|maxthon|uc|ucbs|360 aphone|360|baiduboxapp|baidu|maxthon|mxbrowser|miui(?:.hybrid)?)(mobile)?(browser)?\/?([\d.]+)/i;
                var versionReg2 = /(qq|chrome|safari|firefox|trident|opera|opr\/|oupeng)(mobile)?(browser)?\/?([\d.]+)/i;
                var tmp = versionReg1.exec(ua);

                if (!tmp) {
                  tmp = versionReg2.exec(ua);
                }

                this.browserVersion = tmp ? tmp[4] : '';
                this.pixelRatio = window.devicePixelRatio || 1;

                var _tmpCanvas1 = document.createElement('canvas');

                var supportCanvas =  !!_tmpCanvas1.getContext('2d');
                var supportWebGL = false;

                if (window.WebGLRenderingContext) {
                  supportWebGL = true;
                }

                var supportWebp;

                try {
                  supportWebp = TEST ? false : _tmpCanvas1.toDataURL('image/webp').startsWith('data:image/webp');
                } catch (e) {
                  supportWebp = false;
                }

                var supportImageBitmap = false;

                if ( typeof createImageBitmap !== 'undefined' && typeof Blob !== 'undefined') {
                  _tmpCanvas1.width = _tmpCanvas1.height = 2;
                  createImageBitmap(_tmpCanvas1, {}).then(function (imageBitmap) {
                    supportImageBitmap = true;
                    imageBitmap === null || imageBitmap === void 0 ? void 0 : imageBitmap.close();
                  })["catch"](function (err) {});
                }

                this.supportCapability = {
                  webp: supportWebp,
                  gl: supportWebGL,
                  canvas: supportCanvas,
                  imageBitmap: supportImageBitmap
                };

                this._registerEvent();
              }

              var _proto = System.prototype;

              _proto._registerEvent = function _registerEvent() {
                var _this2 = this;

                window.addEventListener('resize', function () {
                  _this2._eventTarget.emit(AppEvent.RESIZE);
                });
                window.addEventListener('orientationchange', function () {
                  _this2._eventTarget.emit(AppEvent.ORIENTATION_CHANGE);
                });

                this._registerVisibilityEvent();
              };

              _proto._registerVisibilityEvent = function _registerVisibilityEvent() {
                var _this3 = this;

                var hiddenPropName;

                if (typeof document.hidden !== 'undefined') {
                  hiddenPropName = 'hidden';
                } else if (typeof document.mozHidden !== 'undefined') {
                  hiddenPropName = 'mozHidden';
                } else if (typeof document.msHidden !== 'undefined') {
                  hiddenPropName = 'msHidden';
                } else if (typeof document.webkitHidden !== 'undefined') {
                  hiddenPropName = 'webkitHidden';
                } else {
                  hiddenPropName = 'hidden';
                }

                var hidden = false;

                var onHidden = function onHidden() {
                  if (!hidden) {
                    hidden = true;

                    _this3._eventTarget.emit(AppEvent.HIDE);
                  }
                };

                var onShown = function onShown(arg0, arg1, arg2, arg3, arg4) {
                  if (hidden) {
                    hidden = false;

                    _this3._eventTarget.emit(AppEvent.SHOW, arg0, arg1, arg2, arg3, arg4);
                  }
                };

                if (hiddenPropName) {
                  var changeList = ['visibilitychange', 'mozvisibilitychange', 'msvisibilitychange', 'webkitvisibilitychange', 'qbrowserVisibilityChange'];

                  for (var i = 0; i < changeList.length; i++) {
                    document.addEventListener(changeList[i], function (event) {
                      var visible = document[hiddenPropName];
                      visible = visible || event.hidden;

                      if (visible) {
                        onHidden();
                      } else {
                        onShown();
                      }
                    });
                  }
                } else {
                  window.addEventListener('blur', onHidden);
                  window.addEventListener('focus', onShown);
                }

                if (window.navigator.userAgent.indexOf('MicroMessenger') > -1) {
                  window.onfocus = onShown;
                }

                if ('onpageshow' in window && 'onpagehide' in window) {
                  window.addEventListener('pagehide', onHidden);
                  window.addEventListener('pageshow', onShown);
                  document.addEventListener('pagehide', onHidden);
                  document.addEventListener('pageshow', onShown);
                }
              };

              _proto.getViewSize = function getViewSize() {
                var element = document.getElementById('GameDiv');

                if (this.isMobile || !element || element === this._html) {
                  return new Size(window.innerWidth, window.innerHeight);
                } else {
                  return new Size(element.clientWidth, element.clientHeight);
                }
              };

              _proto.getOrientation = function getOrientation() {
                throw new Error('TODO');
              };

              _proto.getSafeAreaEdge = function getSafeAreaEdge() {
                return {
                  top: 0,
                  bottom: 0,
                  left: 0,
                  right: 0
                };
              };

              _proto.getBatteryLevel = function getBatteryLevel() {
                if (this._battery) {
                  return this._battery.level;
                } else {
                  {
                    console.warn('getBatteryLevel is not supported');
                  }

                  return 1;
                }
              };

              _proto.triggerGC = function triggerGC() {
                {
                  console.warn('triggerGC is not supported.');
                }
              };

              _proto.openURL = function openURL(url) {
                window.open(url);
              };

              _proto.now = function now() {
                if (Date.now) {
                  return Date.now();
                }

                return +new Date();
              };

              _proto.restartJSVM = function restartJSVM() {
                {
                  console.warn('restartJSVM is not supported.');
                }
              };

              _proto.onHide = function onHide(cb) {
                this._eventTarget.on(AppEvent.HIDE, cb);
              };

              _proto.onShow = function onShow(cb) {
                this._eventTarget.on(AppEvent.SHOW, cb);
              };

              _proto.onViewResize = function onViewResize(cb) {
                this._eventTarget.on(AppEvent.RESIZE, cb);
              };

              _proto.onOrientationChange = function onOrientationChange(cb) {
                this._eventTarget.on(AppEvent.ORIENTATION_CHANGE, cb);
              };

              _proto.offHide = function offHide(cb) {
                this._eventTarget.off(AppEvent.HIDE, cb);
              };

              _proto.offShow = function offShow(cb) {
                this._eventTarget.off(AppEvent.SHOW, cb);
              };

              _proto.offViewResize = function offViewResize(cb) {
                this._eventTarget.off(AppEvent.RESIZE, cb);
              };

              _proto.offOrientationChange = function offOrientationChange(cb) {
                this._eventTarget.off(AppEvent.ORIENTATION_CHANGE, cb);
              };

              return System;
            }();

            var system = new System();

            var EXTNAME_RE = /(\.[^\.\/\?\\]*)(\?.*)?$/;
            var DIRNAME_RE = /((.*)(\/|\\|\\\\))?(.*?\..*$)?/;
            var NORMALIZE_RE = /[^\.\/]+\/\.\.\//;
            function join() {
              var result = '';

              for (var _len = arguments.length, segments = new Array(_len), _key = 0; _key < _len; _key++) {
                segments[_key] = arguments[_key];
              }

              for (var _i = 0, _segments = segments; _i < _segments.length; _i++) {
                var segment = _segments[_i];
                result = (result + (result === '' ? '' : '/') + segment).replace(/(\/|\\\\)$/, '');
              }

              return result;
            }
            function extname(path) {
              var temp = EXTNAME_RE.exec(path);
              return temp ? temp[1] : '';
            }
            function mainFileName(fileName) {
              if (fileName) {
                var idx = fileName.lastIndexOf('.');

                if (idx !== -1) {
                  return fileName.substring(0, idx);
                }
              }

              return fileName;
            }
            function basename(path, extName) {
              var index = path.indexOf('?');

              if (index > 0) {
                path = path.substring(0, index);
              }

              var reg = /(\/|\\)([^\/\\]+)$/g;
              var result = reg.exec(path.replace(/(\/|\\)$/, ''));

              if (!result) {
                return path;
              }

              var baseName = result[2];

              if (extName && path.substring(path.length - extName.length).toLowerCase() === extName.toLowerCase()) {
                return baseName.substring(0, baseName.length - extName.length);
              }

              return baseName;
            }
            function dirname(path) {
              var temp = DIRNAME_RE.exec(path);
              return temp ? temp[2] : '';
            }
            function changeExtname(path, extName) {
              extName = extName || '';
              var index = path.indexOf('?');
              var tempStr = '';

              if (index > 0) {
                tempStr = path.substring(index);
                path = path.substring(0, index);
              }

              index = path.lastIndexOf('.');

              if (index < 0) {
                return path + extName + tempStr;
              }

              return path.substring(0, index) + extName + tempStr;
            }
            function changeBasename(path, baseName, isSameExt) {
              if (baseName.indexOf('.') === 0) {
                return changeExtname(path, baseName);
              }

              var index = path.indexOf('?');
              var tempStr = '';
              var ext = isSameExt ? 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) + baseName + ext + tempStr;
            }
            function _normalize(url) {
              var oldUrl = url = String(url);

              do {
                oldUrl = url;
                url = url.replace(NORMALIZE_RE, '');
              } while (oldUrl.length !== url.length);

              return url;
            }
            function stripSep(path) {
              return path.replace(/[\/\\]$/, '');
            }
            function getSeperator() {
              return system.os === OS.WINDOWS ? '\\' : '/';
            }

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

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

              get sep() {
                return getSeperator();
              }

            };

            var _stageOffset = 0;
            var _name2stageID = {};
            var config = {
              addStage: function addStage(name) {
                if (_name2stageID[name] !== undefined) {
                  return;
                }

                var stageID = 1 << _stageOffset;
                _name2stageID[name] = stageID;
                _stageOffset += 1;
              },
              stageID: function stageID(name) {
                var id = _name2stageID[name];

                if (id === undefined) {
                  return -1;
                }

                return id;
              },
              stageIDs: function stageIDs(nameList) {
                var key = 0;

                for (var _iterator = _createForOfIteratorHelperLoose(nameList), _step; !(_step = _iterator()).done;) {
                  var name = _step.value;
                  var id = _name2stageID[name];

                  if (id !== undefined) {
                    key |= id;
                  }
                }

                return key;
              }
            };

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

              var _proto = NativeBufferPool.prototype;

              _proto.allocateNewChunk = function allocateNewChunk() {
                return new ArrayBuffer(this._chunkSize);
              };

              return NativeBufferPool;
            }();
            var NativeObjectPool = function () {
              function NativeObjectPool(dataType, array) {}

              var _proto2 = NativeObjectPool.prototype;

              _proto2.bind = function bind(index, obj) {};

              return NativeObjectPool;
            }();
            var NativeBufferAllocator = function () {
              function NativeBufferAllocator(poolType) {}

              var _proto3 = NativeBufferAllocator.prototype;

              _proto3.alloc = function alloc(index, bytes) {
                return new ArrayBuffer(bytes);
              };

              _proto3.free = function free(index) {};

              return NativeBufferAllocator;
            }();

            var _passViewDataType, _subModelViewDataType, _modelViewDataType, _batchView2DDataType, _aabbViewDataType, _sceneViewDataType, _cameraViewDataType, _nodeViewDataType, _rootViewDataType, _renderWindowDataType, _frustumViewDataType, _ambientViewDataType, _skyboxDataType, _fogViewDataType, _shadowsViewDataType, _pipelineSceneDataTyp, _lightViewDataType, _sphereViewDataType, _flatBufferViewDataTy, _subMeshViewDataType, _rasterizerStateViewD, _depthStencilStateVie, _blendTargetViewDataT, _blendStateViewDataTy;

            var contains$2 = function contains(a, t) {
              for (var i = 0; i < a.length; ++i) {
                if (a[i] === t) return true;
              }

              return false;
            };

            var BufferDataType;

            (function (BufferDataType) {
              BufferDataType[BufferDataType["UINT32"] = 0] = "UINT32";
              BufferDataType[BufferDataType["FLOAT32"] = 1] = "FLOAT32";
              BufferDataType[BufferDataType["NEVER"] = 2] = "NEVER";
            })(BufferDataType || (BufferDataType = {}));

            var BufferPool = function () {
              function BufferPool(poolType, dataType, enumType, entryBits) {
                if (entryBits === void 0) {
                  entryBits = 8;
                }

                this._dataType = void 0;
                this._elementCount = void 0;
                this._entryBits = void 0;
                this._stride = void 0;
                this._entriesPerChunk = void 0;
                this._entryMask = void 0;
                this._chunkMask = void 0;
                this._poolFlag = void 0;
                this._arrayBuffers = [];
                this._freelists = [];
                this._uint32BufferViews = [];
                this._float32BufferViews = [];
                this._hasUint32 = false;
                this._hasFloat32 = false;
                this._nativePool = void 0;
                this._elementCount = enumType.COUNT;
                this._entryBits = entryBits;
                this._dataType = dataType;
                var bytesPerElement = 4;
                this._stride = bytesPerElement * this._elementCount;
                this._entriesPerChunk = 1 << entryBits;
                this._entryMask = this._entriesPerChunk - 1;
                this._poolFlag = 1 << 30;
                this._chunkMask = ~(this._entryMask | this._poolFlag);
                this._nativePool = new NativeBufferPool(poolType, entryBits, this._stride);
                var type = BufferDataType.NEVER;
                var hasFloat32 = false;
                var hasUint32 = false;

                for (var e in dataType) {
                  hasFloat32 = this._hasFloat32;
                  hasUint32 = this._hasUint32;

                  if (hasUint32 && hasFloat32) {
                    break;
                  }

                  type = dataType[e];

                  if (!hasFloat32 && type === BufferDataType.FLOAT32) {
                    this._hasFloat32 = true;
                  } else if (!hasUint32 && type === BufferDataType.UINT32) {
                    this._hasUint32 = true;
                  }
                }
              }

              var _proto = BufferPool.prototype;

              _proto.alloc = function alloc() {
                var i = 0;

                for (; i < this._freelists.length; i++) {
                  var list = this._freelists[i];

                  if (list.length) {
                    var j = list[list.length - 1];
                    list.length--;
                    return (i << this._entryBits) + j + this._poolFlag;
                  }
                }

                var buffer = this._nativePool.allocateNewChunk();

                var float32BufferViews = [];
                var uint32BufferViews = [];
                var freelist = [];
                var hasFloat32 = this._hasFloat32;
                var hasUint32 = this._hasUint32;

                for (var _j = 0; _j < this._entriesPerChunk; _j++) {
                  if (hasFloat32) {
                    float32BufferViews.push(new Float32Array(buffer, this._stride * _j, this._elementCount));
                  }

                  if (hasUint32) {
                    uint32BufferViews.push(new Uint32Array(buffer, this._stride * _j, this._elementCount));
                  }

                  if (_j) {
                    freelist.push(_j);
                  }
                }

                this._arrayBuffers.push(buffer);

                if (hasUint32) {
                  this._uint32BufferViews.push(uint32BufferViews);
                }

                if (hasFloat32) {
                  this._float32BufferViews.push(float32BufferViews);
                }

                this._freelists.push(freelist);

                return (i << this._entryBits) + this._poolFlag;
              };

              _proto.get = function get(handle, element) {
                var chunk = (this._chunkMask & handle) >> this._entryBits;
                var entry = this._entryMask & handle;
                var bufferViews = this._dataType[element] === BufferDataType.UINT32 ? this._uint32BufferViews : this._float32BufferViews;

                if ( (!handle || chunk < 0 || chunk >= bufferViews.length || entry < 0 || entry >= this._entriesPerChunk || contains$2(this._freelists[chunk], entry))) {
                  console.warn('invalid buffer pool handle');
                  return 0;
                }

                return bufferViews[chunk][entry][element];
              };

              _proto.set = function set(handle, element, value) {
                var chunk = (this._chunkMask & handle) >> this._entryBits;
                var entry = this._entryMask & handle;
                var bufferViews = this._dataType[element] === BufferDataType.UINT32 ? this._uint32BufferViews : this._float32BufferViews;

                if ( (!handle || chunk < 0 || chunk >= bufferViews.length || entry < 0 || entry >= this._entriesPerChunk || contains$2(this._freelists[chunk], entry))) {
                  console.warn('invalid buffer pool handle');
                  return;
                }

                bufferViews[chunk][entry][element] = value;
              };

              _proto.setVec2 = function setVec2(handle, element, vec2) {
                {
                  return;
                }
              };

              _proto.setVec3 = function setVec3(handle, element, vec3) {
                {
                  return;
                }
              };

              _proto.getVec3 = function getVec3(handle, element, vec3) {
                {
                  return;
                }
              };

              _proto.setVec4 = function setVec4(handle, element, vec4) {
                {
                  return;
                }
              };

              _proto.getVec4 = function getVec4(handle, element, vec4) {
                {
                  return;
                }
              };

              _proto.setMat4 = function setMat4(handle, element, mat4) {
                {
                  return;
                }
              };

              _proto.free = function free(handle) {
                var chunk = (this._chunkMask & handle) >> this._entryBits;
                var entry = this._entryMask & handle;

                if ( (!handle || chunk < 0 || chunk >= this._freelists.length || entry < 0 || entry >= this._entriesPerChunk || contains$2(this._freelists[chunk], entry))) {
                  console.warn('invalid buffer pool handle');
                  return;
                }

                var bufferViews = this._hasUint32 ? this._uint32BufferViews : this._float32BufferViews;
                bufferViews[chunk][entry].fill(0);

                this._freelists[chunk].push(entry);
              };

              return BufferPool;
            }();

            var ObjectPool = function () {
              function ObjectPool(poolType, ctor, dtor) {
                this._ctor = void 0;
                this._dtor = void 0;
                this._indexMask = void 0;
                this._poolFlag = void 0;
                this._array = [];
                this._freelist = [];
                this._nativePool = void 0;
                this._ctor = ctor;

                if (dtor) {
                  this._dtor = dtor;
                }

                this._poolFlag = 1 << 29;
                this._indexMask = ~this._poolFlag;
                this._nativePool = new NativeObjectPool(poolType, this._array);
              }

              var _proto2 = ObjectPool.prototype;

              _proto2.alloc = function alloc() {
                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                var freelist = this._freelist;
                var i = -1;

                if (freelist.length) {
                  i = freelist[freelist.length - 1];
                  freelist.length--;
                  this._array[i] = this._ctor(arguments, this._array[i]);
                } else {
                  i = this._array.length;

                  var _obj = this._ctor(arguments);

                  if (!_obj) {
                    return 0;
                  }

                  this._array.push(_obj);
                }
                return i + this._poolFlag;
              };

              _proto2.get = function get(handle) {
                var index = this._indexMask & handle;

                if ( (!handle || index < 0 || index >= this._array.length || contains$2(this._freelist, index))) {
                  console.warn('invalid object pool handle');
                  return null;
                }

                return this._array[index];
              };

              _proto2.free = function free(handle) {
                var index = this._indexMask & handle;

                if ( (!handle || index < 0 || index >= this._array.length || contains$2(this._freelist, index))) {
                  console.warn('invalid object pool handle');
                  return;
                }

                if (this._dtor) {
                  this._array[index] = this._dtor(this._array[index]);
                }

                this._freelist.push(index);
              };

              return ObjectPool;
            }();

            var BufferAllocator = function () {
              function BufferAllocator(poolType) {
                this._nativeBufferAllocator = void 0;
                this._buffers = new Map();
                this._nextBufferIdx = 0;
                this._poolFlag = void 0;
                this._bufferIdxMask = void 0;
                this._freelist = [];
                this._poolFlag = 1 << 30;
                this._bufferIdxMask = ~this._poolFlag;
                this._nativeBufferAllocator = new NativeBufferAllocator(poolType);
              }

              var _proto3 = BufferAllocator.prototype;

              _proto3.alloc = function alloc(size) {
                var freelist = this._freelist;
                var bufferIdx = -1;

                if (freelist.length) {
                  bufferIdx = freelist[freelist.length - 1];
                  freelist.length--;
                } else {
                  bufferIdx = this._nextBufferIdx++;
                }

                var buffer = this._nativeBufferAllocator.alloc(bufferIdx, size);

                this._buffers.set(bufferIdx, buffer);

                return bufferIdx | this._poolFlag;
              };

              _proto3.free = function free(handle) {
                var bufferIdx = this._bufferIdxMask & handle;

                if (!this._buffers.get(bufferIdx)) {
                  {
                    console.warn('invalid buffer allocator handle');
                  }

                  return;
                }

                this._nativeBufferAllocator.free(bufferIdx);

                this._buffers["delete"](bufferIdx);

                this._freelist.push(bufferIdx);
              };

              _proto3.getBuffer = function getBuffer(handle) {
                var bufferIdx = this._bufferIdxMask & handle;

                var buffer = this._buffers.get(bufferIdx);

                if (!buffer) {
                  {
                    console.warn('invalid array pool index or invalid array handle');
                  }

                  return null;
                }

                return buffer;
              };

              return BufferAllocator;
            }();

            var TypedArrayPool = function (_BufferAllocator) {
              _inheritsLoose(TypedArrayPool, _BufferAllocator);

              function TypedArrayPool(poolType, viewCtor, size, step) {
                var _this;

                _this = _BufferAllocator.call(this, poolType) || this;
                _this._viewCtor = void 0;
                _this._size = void 0;
                _this._step = void 0;
                _this._viewCtor = viewCtor;
                _this._size = size * viewCtor.BYTES_PER_ELEMENT;
                _this._step = step || size;
                return _this;
              }

              var _proto4 = TypedArrayPool.prototype;

              _proto4.alloc = function alloc() {
                var bufferIdx = this._nextBufferIdx++;

                var buffer = this._nativeBufferAllocator.alloc(bufferIdx, this._size);

                this._buffers.set(bufferIdx, new this._viewCtor(buffer));

                return bufferIdx | this._poolFlag;
              };

              _proto4.getBuffer = function getBuffer(handle) {
                return null;
              };

              _proto4.assign = function assign(handle, targetIdx, value) {
                var bufferIdx = this._bufferIdxMask & handle;

                var array = this._buffers.get(bufferIdx);

                if (!array) {
                  {
                    console.warn('invalid array pool handle');
                  }

                  return;
                }

                var index = targetIdx + 1;

                if (index >= array.length) {
                  var newSize = array.length;

                  while (index >= newSize) {
                    newSize += this._step;
                  }

                  newSize *= this._viewCtor.BYTES_PER_ELEMENT;
                  var newArray = new this._viewCtor(this._nativeBufferAllocator.alloc(bufferIdx, newSize));
                  newArray.set(array);
                  array = newArray;

                  this._buffers.set(bufferIdx, array);
                }

                array[index] = value;
                var len = array[0];
                array[0] = index > len ? index : len;
              };

              _proto4.erase = function erase(handle, index) {
                var bufferIdx = this._bufferIdxMask & handle;

                var array = this._buffers.get(bufferIdx);

                if (!array || index >= array[0]) {
                  {
                    console.warn('invalid array pool index or invalid array handle');
                  }

                  return;
                }

                for (var i = index + 1; i < array[0]; ++i) {
                  array[i] = array[i + 1];
                }

                --array[0];
              };

              _proto4.push = function push(handle, value) {
                var bufferIdx = this._bufferIdxMask & handle;

                var array = this._buffers.get(bufferIdx);

                if (!array) {
                  {
                    console.warn('invalid array pool handle');
                  }

                  return;
                }

                this.assign(handle, array[0], value);
              };

              _proto4.pop = function pop(handle) {
                var bufferIdx = this._bufferIdxMask & handle;

                var array = this._buffers.get(bufferIdx);

                if (!array) {
                  {
                    console.warn('invalid array pool handle');
                  }

                  return;
                }

                if (array[0] !== 0) --array[0];
              };

              _proto4.clear = function clear(handle) {
                var bufferIdx = this._bufferIdxMask & handle;

                var array = this._buffers.get(bufferIdx);

                if (!array) {
                  {
                    console.warn('invalid array pool handle');
                  }

                  return;
                }

                array[0] = 0;
              };

              _proto4.get = function get(handle, index) {
                var bufferIdx = this._bufferIdxMask & handle;

                var array = this._buffers.get(bufferIdx);

                if (!array || index >= array[0]) {
                  {
                    console.warn('invalid array pool handle');
                  }

                  return 0;
                }

                return array[index + 1];
              };

              _proto4.length = function length(handle) {
                var bufferIdx = this._bufferIdxMask & handle;

                var array = this._buffers.get(bufferIdx);

                if (!array) {
                  {
                    console.warn('invalid array pool handle');
                  }

                  return 0;
                }

                return array[0];
              };

              return TypedArrayPool;
            }(BufferAllocator);

            function freeHandleArray(arrayHandle, arrayPool, elementPool, freeArrayItself) {
              if (freeArrayItself === void 0) {
                freeArrayItself = true;
              }

              var count = arrayPool.length(arrayHandle);

              for (var i = 0; i < count; i++) {
                var element = arrayPool.get(arrayHandle, i);

                if (element) {
                  elementPool.free(element);
                }
              }

              if (freeArrayItself) {
                arrayPool.free(arrayHandle);
              } else {
                arrayPool.clear(arrayHandle);
              }
            }
            var PoolType;

            (function (PoolType) {
              PoolType[PoolType["ATTRIBUTE"] = 0] = "ATTRIBUTE";
              PoolType[PoolType["DESCRIPTOR_SETS"] = 1] = "DESCRIPTOR_SETS";
              PoolType[PoolType["SHADER"] = 2] = "SHADER";
              PoolType[PoolType["INPUT_ASSEMBLER"] = 3] = "INPUT_ASSEMBLER";
              PoolType[PoolType["PIPELINE_LAYOUT"] = 4] = "PIPELINE_LAYOUT";
              PoolType[PoolType["FRAMEBUFFER"] = 5] = "FRAMEBUFFER";
              PoolType[PoolType["PASS"] = 100] = "PASS";
              PoolType[PoolType["SUB_MODEL"] = 101] = "SUB_MODEL";
              PoolType[PoolType["MODEL"] = 102] = "MODEL";
              PoolType[PoolType["SCENE"] = 103] = "SCENE";
              PoolType[PoolType["CAMERA"] = 104] = "CAMERA";
              PoolType[PoolType["NODE"] = 105] = "NODE";
              PoolType[PoolType["ROOT"] = 106] = "ROOT";
              PoolType[PoolType["AABB"] = 107] = "AABB";
              PoolType[PoolType["RENDER_WINDOW"] = 108] = "RENDER_WINDOW";
              PoolType[PoolType["FRUSTUM"] = 109] = "FRUSTUM";
              PoolType[PoolType["AMBIENT"] = 110] = "AMBIENT";
              PoolType[PoolType["FOG"] = 111] = "FOG";
              PoolType[PoolType["SKYBOX"] = 112] = "SKYBOX";
              PoolType[PoolType["SHADOW"] = 113] = "SHADOW";
              PoolType[PoolType["LIGHT"] = 114] = "LIGHT";
              PoolType[PoolType["SPHERE"] = 115] = "SPHERE";
              PoolType[PoolType["INSTANCED_ATTRIBUTE"] = 116] = "INSTANCED_ATTRIBUTE";
              PoolType[PoolType["FLAT_BUFFER"] = 117] = "FLAT_BUFFER";
              PoolType[PoolType["SUB_MESH"] = 118] = "SUB_MESH";
              PoolType[PoolType["RASTERIZER_STATE"] = 119] = "RASTERIZER_STATE";
              PoolType[PoolType["DEPTH_STENCIL_STATE"] = 120] = "DEPTH_STENCIL_STATE";
              PoolType[PoolType["BLEND_TARGET"] = 121] = "BLEND_TARGET";
              PoolType[PoolType["BLEND_STATE"] = 122] = "BLEND_STATE";
              PoolType[PoolType["BATCH_2D"] = 123] = "BATCH_2D";
              PoolType[PoolType["PIPELINE_SCENE_DATA"] = 124] = "PIPELINE_SCENE_DATA";
              PoolType[PoolType["SUB_MODEL_ARRAY"] = 200] = "SUB_MODEL_ARRAY";
              PoolType[PoolType["MODEL_ARRAY"] = 201] = "MODEL_ARRAY";
              PoolType[PoolType["ATTRIBUTE_ARRAY"] = 202] = "ATTRIBUTE_ARRAY";
              PoolType[PoolType["FLAT_BUFFER_ARRAY"] = 203] = "FLAT_BUFFER_ARRAY";
              PoolType[PoolType["INSTANCED_BUFFER_ARRAY"] = 204] = "INSTANCED_BUFFER_ARRAY";
              PoolType[PoolType["LIGHT_ARRAY"] = 205] = "LIGHT_ARRAY";
              PoolType[PoolType["BLEND_TARGET_ARRAY"] = 206] = "BLEND_TARGET_ARRAY";
              PoolType[PoolType["BATCH_ARRAY_2D"] = 207] = "BATCH_ARRAY_2D";
              PoolType[PoolType["RAW_BUFFER"] = 300] = "RAW_BUFFER";
              PoolType[PoolType["RAW_OBJECT"] = 400] = "RAW_OBJECT";
            })(PoolType || (PoolType = {}));

            var NULL_HANDLE = 0;
            var ShaderPool = new ObjectPool(PoolType.SHADER, function (args, obj) {
              return obj ? (obj.initialize(args[1]), obj) : args[0].createShader(args[1]);
            }, function (obj) {
              return obj && obj.destroy(), obj;
            });
            var DSPool = new ObjectPool(PoolType.DESCRIPTOR_SETS, function (args, obj) {
              return obj ? (obj.initialize(args[1]), obj) : args[0].createDescriptorSet(args[1]);
            }, function (obj) {
              return obj && obj.destroy(), obj;
            });
            var IAPool = new ObjectPool(PoolType.INPUT_ASSEMBLER, function (args, obj) {
              return obj ? (obj.initialize(args[1]), obj) : args[0].createInputAssembler(args[1]);
            }, function (obj) {
              return obj && obj.destroy(), obj;
            });
            var PipelineLayoutPool = new ObjectPool(PoolType.PIPELINE_LAYOUT, function (args, obj) {
              return obj ? (obj.initialize(args[1]), obj) : args[0].createPipelineLayout(args[1]);
            }, function (obj) {
              return obj && obj.destroy(), obj;
            });
            var FramebufferPool = new ObjectPool(PoolType.FRAMEBUFFER, function (args, obj) {
              return obj ? (obj.initialize(args[1]), obj) : args[0].createFramebuffer(args[1]);
            }, function (obj) {
              return obj && obj.destroy(), obj;
            });
            var SubModelArrayPool = new TypedArrayPool(PoolType.SUB_MODEL_ARRAY, Uint32Array, 8, 4);
            var ModelArrayPool = new TypedArrayPool(PoolType.MODEL_ARRAY, Uint32Array, 32, 16);
            var AttributeArrayPool = new TypedArrayPool(PoolType.ATTRIBUTE_ARRAY, Uint32Array, 8, 4);
            var FlatBufferArrayPool = new TypedArrayPool(PoolType.FLAT_BUFFER_ARRAY, Uint32Array, 8, 4);
            var LightArrayPool = new TypedArrayPool(PoolType.LIGHT_ARRAY, Uint32Array, 8, 4);
            var BlendTargetArrayPool = new TypedArrayPool(PoolType.BLEND_TARGET_ARRAY, Uint32Array, 8, 4);
            var UIBatchArrayPool = new TypedArrayPool(PoolType.BATCH_ARRAY_2D, Uint32Array, 32, 16);
            var RawBufferPool = new BufferAllocator(PoolType.RAW_BUFFER);
            var RawObjectPool = new ObjectPool(PoolType.RAW_OBJECT, function (args) {
              return args[0] || {};
            }, function (_) {
              return undefined;
            });
            var PassView;

            (function (PassView) {
              PassView[PassView["PRIORITY"] = 0] = "PRIORITY";
              PassView[PassView["STAGE"] = 1] = "STAGE";
              PassView[PassView["PHASE"] = 2] = "PHASE";
              PassView[PassView["BATCHING_SCHEME"] = 3] = "BATCHING_SCHEME";
              PassView[PassView["PRIMITIVE"] = 4] = "PRIMITIVE";
              PassView[PassView["DYNAMIC_STATES"] = 5] = "DYNAMIC_STATES";
              PassView[PassView["HASH"] = 6] = "HASH";
              PassView[PassView["RASTERIZER_STATE"] = 7] = "RASTERIZER_STATE";
              PassView[PassView["DEPTH_STENCIL_STATE"] = 8] = "DEPTH_STENCIL_STATE";
              PassView[PassView["BLEND_STATE"] = 9] = "BLEND_STATE";
              PassView[PassView["DESCRIPTOR_SET"] = 10] = "DESCRIPTOR_SET";
              PassView[PassView["PIPELINE_LAYOUT"] = 11] = "PIPELINE_LAYOUT";
              PassView[PassView["COUNT"] = 12] = "COUNT";
            })(PassView || (PassView = {}));

            var passViewDataType = (_passViewDataType = {}, _passViewDataType[PassView.PRIORITY] = BufferDataType.UINT32, _passViewDataType[PassView.STAGE] = BufferDataType.UINT32, _passViewDataType[PassView.PHASE] = BufferDataType.UINT32, _passViewDataType[PassView.BATCHING_SCHEME] = BufferDataType.UINT32, _passViewDataType[PassView.PRIMITIVE] = BufferDataType.UINT32, _passViewDataType[PassView.DYNAMIC_STATES] = BufferDataType.UINT32, _passViewDataType[PassView.HASH] = BufferDataType.UINT32, _passViewDataType[PassView.RASTERIZER_STATE] = BufferDataType.UINT32, _passViewDataType[PassView.DEPTH_STENCIL_STATE] = BufferDataType.UINT32, _passViewDataType[PassView.BLEND_STATE] = BufferDataType.UINT32, _passViewDataType[PassView.DESCRIPTOR_SET] = BufferDataType.UINT32, _passViewDataType[PassView.PIPELINE_LAYOUT] = BufferDataType.UINT32, _passViewDataType[PassView.COUNT] = BufferDataType.NEVER, _passViewDataType);
            var PassPool = new BufferPool(PoolType.PASS, passViewDataType, PassView);
            var SubModelView;

            (function (SubModelView) {
              SubModelView[SubModelView["PRIORITY"] = 0] = "PRIORITY";
              SubModelView[SubModelView["PASS_COUNT"] = 1] = "PASS_COUNT";
              SubModelView[SubModelView["PASS_0"] = 2] = "PASS_0";
              SubModelView[SubModelView["PASS_1"] = 3] = "PASS_1";
              SubModelView[SubModelView["PASS_2"] = 4] = "PASS_2";
              SubModelView[SubModelView["PASS_3"] = 5] = "PASS_3";
              SubModelView[SubModelView["PASS_4"] = 6] = "PASS_4";
              SubModelView[SubModelView["PASS_5"] = 7] = "PASS_5";
              SubModelView[SubModelView["PASS_6"] = 8] = "PASS_6";
              SubModelView[SubModelView["PASS_7"] = 9] = "PASS_7";
              SubModelView[SubModelView["SHADER_0"] = 10] = "SHADER_0";
              SubModelView[SubModelView["SHADER_1"] = 11] = "SHADER_1";
              SubModelView[SubModelView["SHADER_2"] = 12] = "SHADER_2";
              SubModelView[SubModelView["SHADER_3"] = 13] = "SHADER_3";
              SubModelView[SubModelView["SHADER_4"] = 14] = "SHADER_4";
              SubModelView[SubModelView["SHADER_5"] = 15] = "SHADER_5";
              SubModelView[SubModelView["SHADER_6"] = 16] = "SHADER_6";
              SubModelView[SubModelView["SHADER_7"] = 17] = "SHADER_7";
              SubModelView[SubModelView["PLANAR_SHADER"] = 18] = "PLANAR_SHADER";
              SubModelView[SubModelView["PLANAR_INSTANCE_SHADER"] = 19] = "PLANAR_INSTANCE_SHADER";
              SubModelView[SubModelView["DESCRIPTOR_SET"] = 20] = "DESCRIPTOR_SET";
              SubModelView[SubModelView["INPUT_ASSEMBLER"] = 21] = "INPUT_ASSEMBLER";
              SubModelView[SubModelView["SUB_MESH"] = 22] = "SUB_MESH";
              SubModelView[SubModelView["COUNT"] = 23] = "COUNT";
            })(SubModelView || (SubModelView = {}));

            var subModelViewDataType = (_subModelViewDataType = {}, _subModelViewDataType[SubModelView.PRIORITY] = BufferDataType.UINT32, _subModelViewDataType[SubModelView.PASS_COUNT] = BufferDataType.UINT32, _subModelViewDataType[SubModelView.PASS_0] = BufferDataType.UINT32, _subModelViewDataType[SubModelView.PASS_1] = BufferDataType.UINT32, _subModelViewDataType[SubModelView.PASS_2] = BufferDataType.UINT32, _subModelViewDataType[SubModelView.PASS_3] = BufferDataType.UINT32, _subModelViewDataType[SubModelView.PASS_4] = BufferDataType.UINT32, _subModelViewDataType[SubModelView.PASS_5] = BufferDataType.UINT32, _subModelViewDataType[SubModelView.PASS_6] = BufferDataType.UINT32, _subModelViewDataType[SubModelView.PASS_7] = BufferDataType.UINT32, _subModelViewDataType[SubModelView.SHADER_0] = BufferDataType.UINT32, _subModelViewDataType[SubModelView.SHADER_1] = BufferDataType.UINT32, _subModelViewDataType[SubModelView.SHADER_2] = BufferDataType.UINT32, _subModelViewDataType[SubModelView.SHADER_3] = BufferDataType.UINT32, _subModelViewDataType[SubModelView.SHADER_4] = BufferDataType.UINT32, _subModelViewDataType[SubModelView.SHADER_5] = BufferDataType.UINT32, _subModelViewDataType[SubModelView.SHADER_6] = BufferDataType.UINT32, _subModelViewDataType[SubModelView.SHADER_7] = BufferDataType.UINT32, _subModelViewDataType[SubModelView.PLANAR_SHADER] = BufferDataType.UINT32, _subModelViewDataType[SubModelView.PLANAR_INSTANCE_SHADER] = BufferDataType.UINT32, _subModelViewDataType[SubModelView.DESCRIPTOR_SET] = BufferDataType.UINT32, _subModelViewDataType[SubModelView.INPUT_ASSEMBLER] = BufferDataType.UINT32, _subModelViewDataType[SubModelView.SUB_MESH] = BufferDataType.UINT32, _subModelViewDataType[SubModelView.COUNT] = BufferDataType.NEVER, _subModelViewDataType);
            var SubModelPool = new BufferPool(PoolType.SUB_MODEL, subModelViewDataType, SubModelView);
            var ModelView;

            (function (ModelView) {
              ModelView[ModelView["ENABLED"] = 0] = "ENABLED";
              ModelView[ModelView["VIS_FLAGS"] = 1] = "VIS_FLAGS";
              ModelView[ModelView["CAST_SHADOW"] = 2] = "CAST_SHADOW";
              ModelView[ModelView["RECEIVE_SHADOW"] = 3] = "RECEIVE_SHADOW";
              ModelView[ModelView["WORLD_BOUNDS"] = 4] = "WORLD_BOUNDS";
              ModelView[ModelView["NODE"] = 5] = "NODE";
              ModelView[ModelView["TRANSFORM"] = 6] = "TRANSFORM";
              ModelView[ModelView["SUB_MODEL_ARRAY"] = 7] = "SUB_MODEL_ARRAY";
              ModelView[ModelView["INSTANCED_BUFFER"] = 8] = "INSTANCED_BUFFER";
              ModelView[ModelView["INSTANCED_ATTR_ARRAY"] = 9] = "INSTANCED_ATTR_ARRAY";
              ModelView[ModelView["COUNT"] = 10] = "COUNT";
            })(ModelView || (ModelView = {}));

            var modelViewDataType = (_modelViewDataType = {}, _modelViewDataType[ModelView.ENABLED] = BufferDataType.UINT32, _modelViewDataType[ModelView.VIS_FLAGS] = BufferDataType.UINT32, _modelViewDataType[ModelView.CAST_SHADOW] = BufferDataType.UINT32, _modelViewDataType[ModelView.RECEIVE_SHADOW] = BufferDataType.UINT32, _modelViewDataType[ModelView.WORLD_BOUNDS] = BufferDataType.UINT32, _modelViewDataType[ModelView.NODE] = BufferDataType.UINT32, _modelViewDataType[ModelView.TRANSFORM] = BufferDataType.UINT32, _modelViewDataType[ModelView.SUB_MODEL_ARRAY] = BufferDataType.UINT32, _modelViewDataType[ModelView.INSTANCED_BUFFER] = BufferDataType.UINT32, _modelViewDataType[ModelView.INSTANCED_ATTR_ARRAY] = BufferDataType.UINT32, _modelViewDataType[ModelView.COUNT] = BufferDataType.NEVER, _modelViewDataType);
            var ModelPool = new BufferPool(PoolType.MODEL, modelViewDataType, ModelView);
            var BatchView2D;

            (function (BatchView2D) {
              BatchView2D[BatchView2D["VIS_FLAGS"] = 0] = "VIS_FLAGS";
              BatchView2D[BatchView2D["PASS_COUNT"] = 1] = "PASS_COUNT";
              BatchView2D[BatchView2D["PASS_0"] = 2] = "PASS_0";
              BatchView2D[BatchView2D["PASS_1"] = 3] = "PASS_1";
              BatchView2D[BatchView2D["PASS_2"] = 4] = "PASS_2";
              BatchView2D[BatchView2D["PASS_3"] = 5] = "PASS_3";
              BatchView2D[BatchView2D["SHADER_0"] = 6] = "SHADER_0";
              BatchView2D[BatchView2D["SHADER_1"] = 7] = "SHADER_1";
              BatchView2D[BatchView2D["SHADER_2"] = 8] = "SHADER_2";
              BatchView2D[BatchView2D["SHADER_3"] = 9] = "SHADER_3";
              BatchView2D[BatchView2D["DESCRIPTOR_SET"] = 10] = "DESCRIPTOR_SET";
              BatchView2D[BatchView2D["INPUT_ASSEMBLER"] = 11] = "INPUT_ASSEMBLER";
              BatchView2D[BatchView2D["COUNT"] = 12] = "COUNT";
            })(BatchView2D || (BatchView2D = {}));

            var batchView2DDataType = (_batchView2DDataType = {}, _batchView2DDataType[BatchView2D.VIS_FLAGS] = BufferDataType.UINT32, _batchView2DDataType[BatchView2D.PASS_COUNT] = BufferDataType.UINT32, _batchView2DDataType[BatchView2D.PASS_0] = BufferDataType.UINT32, _batchView2DDataType[BatchView2D.PASS_1] = BufferDataType.UINT32, _batchView2DDataType[BatchView2D.PASS_2] = BufferDataType.UINT32, _batchView2DDataType[BatchView2D.PASS_3] = BufferDataType.UINT32, _batchView2DDataType[BatchView2D.SHADER_0] = BufferDataType.UINT32, _batchView2DDataType[BatchView2D.SHADER_1] = BufferDataType.UINT32, _batchView2DDataType[BatchView2D.SHADER_2] = BufferDataType.UINT32, _batchView2DDataType[BatchView2D.SHADER_3] = BufferDataType.UINT32, _batchView2DDataType[BatchView2D.DESCRIPTOR_SET] = BufferDataType.UINT32, _batchView2DDataType[BatchView2D.INPUT_ASSEMBLER] = BufferDataType.UINT32, _batchView2DDataType[BatchView2D.COUNT] = BufferDataType.NEVER, _batchView2DDataType);
            var BatchPool2D = new BufferPool(PoolType.BATCH_2D, batchView2DDataType, BatchView2D);
            var AABBView;

            (function (AABBView) {
              AABBView[AABBView["CENTER"] = 0] = "CENTER";
              AABBView[AABBView["HALF_EXTENSION"] = 3] = "HALF_EXTENSION";
              AABBView[AABBView["COUNT"] = 6] = "COUNT";
            })(AABBView || (AABBView = {}));

            var aabbViewDataType = (_aabbViewDataType = {}, _aabbViewDataType[AABBView.CENTER] = BufferDataType.FLOAT32, _aabbViewDataType[AABBView.HALF_EXTENSION] = BufferDataType.FLOAT32, _aabbViewDataType[AABBView.COUNT] = BufferDataType.NEVER, _aabbViewDataType);
            var AABBPool = new BufferPool(PoolType.AABB, aabbViewDataType, AABBView);
            var SceneView;

            (function (SceneView) {
              SceneView[SceneView["MAIN_LIGHT"] = 0] = "MAIN_LIGHT";
              SceneView[SceneView["MODEL_ARRAY"] = 1] = "MODEL_ARRAY";
              SceneView[SceneView["SPHERE_LIGHT_ARRAY"] = 2] = "SPHERE_LIGHT_ARRAY";
              SceneView[SceneView["SPOT_LIGHT_ARRAY"] = 3] = "SPOT_LIGHT_ARRAY";
              SceneView[SceneView["BATCH_ARRAY_2D"] = 4] = "BATCH_ARRAY_2D";
              SceneView[SceneView["COUNT"] = 5] = "COUNT";
            })(SceneView || (SceneView = {}));

            var sceneViewDataType = (_sceneViewDataType = {}, _sceneViewDataType[SceneView.MAIN_LIGHT] = BufferDataType.UINT32, _sceneViewDataType[SceneView.MODEL_ARRAY] = BufferDataType.UINT32, _sceneViewDataType[SceneView.SPHERE_LIGHT_ARRAY] = BufferDataType.UINT32, _sceneViewDataType[SceneView.SPOT_LIGHT_ARRAY] = BufferDataType.UINT32, _sceneViewDataType[SceneView.BATCH_ARRAY_2D] = BufferDataType.UINT32, _sceneViewDataType[SceneView.COUNT] = BufferDataType.NEVER, _sceneViewDataType);
            var ScenePool = new BufferPool(PoolType.SCENE, sceneViewDataType, SceneView);
            var CameraView;

            (function (CameraView) {
              CameraView[CameraView["WIDTH"] = 0] = "WIDTH";
              CameraView[CameraView["HEIGHT"] = 1] = "HEIGHT";
              CameraView[CameraView["EXPOSURE"] = 2] = "EXPOSURE";
              CameraView[CameraView["CLEAR_FLAGS"] = 3] = "CLEAR_FLAGS";
              CameraView[CameraView["CLEAR_DEPTH"] = 4] = "CLEAR_DEPTH";
              CameraView[CameraView["CLEAR_STENCIL"] = 5] = "CLEAR_STENCIL";
              CameraView[CameraView["VISIBILITY"] = 6] = "VISIBILITY";
              CameraView[CameraView["NODE"] = 7] = "NODE";
              CameraView[CameraView["SCENE"] = 8] = "SCENE";
              CameraView[CameraView["FRUSTUM"] = 9] = "FRUSTUM";
              CameraView[CameraView["WINDOW"] = 10] = "WINDOW";
              CameraView[CameraView["FORWARD"] = 11] = "FORWARD";
              CameraView[CameraView["POSITION"] = 14] = "POSITION";
              CameraView[CameraView["VIEW_PORT"] = 17] = "VIEW_PORT";
              CameraView[CameraView["CLEAR_COLOR"] = 21] = "CLEAR_COLOR";
              CameraView[CameraView["MAT_VIEW"] = 25] = "MAT_VIEW";
              CameraView[CameraView["MAT_VIEW_PROJ"] = 41] = "MAT_VIEW_PROJ";
              CameraView[CameraView["MAT_VIEW_PROJ_INV"] = 57] = "MAT_VIEW_PROJ_INV";
              CameraView[CameraView["MAT_PROJ"] = 73] = "MAT_PROJ";
              CameraView[CameraView["MAT_PROJ_INV"] = 89] = "MAT_PROJ_INV";
              CameraView[CameraView["MAT_VIEW_PROJ_OFFSCREEN"] = 105] = "MAT_VIEW_PROJ_OFFSCREEN";
              CameraView[CameraView["MAT_VIEW_PROJ_INV_OFFSCREEN"] = 121] = "MAT_VIEW_PROJ_INV_OFFSCREEN";
              CameraView[CameraView["MAT_PROJ_OFFSCREEN"] = 137] = "MAT_PROJ_OFFSCREEN";
              CameraView[CameraView["MAT_PROJ_INV_OFFSCREEN"] = 153] = "MAT_PROJ_INV_OFFSCREEN";
              CameraView[CameraView["COUNT"] = 169] = "COUNT";
            })(CameraView || (CameraView = {}));

            var cameraViewDataType = (_cameraViewDataType = {}, _cameraViewDataType[CameraView.WIDTH] = BufferDataType.UINT32, _cameraViewDataType[CameraView.HEIGHT] = BufferDataType.UINT32, _cameraViewDataType[CameraView.EXPOSURE] = BufferDataType.FLOAT32, _cameraViewDataType[CameraView.CLEAR_FLAGS] = BufferDataType.UINT32, _cameraViewDataType[CameraView.CLEAR_DEPTH] = BufferDataType.FLOAT32, _cameraViewDataType[CameraView.CLEAR_STENCIL] = BufferDataType.UINT32, _cameraViewDataType[CameraView.VISIBILITY] = BufferDataType.UINT32, _cameraViewDataType[CameraView.NODE] = BufferDataType.UINT32, _cameraViewDataType[CameraView.SCENE] = BufferDataType.UINT32, _cameraViewDataType[CameraView.FRUSTUM] = BufferDataType.UINT32, _cameraViewDataType[CameraView.WINDOW] = BufferDataType.UINT32, _cameraViewDataType[CameraView.FORWARD] = BufferDataType.FLOAT32, _cameraViewDataType[CameraView.POSITION] = BufferDataType.FLOAT32, _cameraViewDataType[CameraView.VIEW_PORT] = BufferDataType.FLOAT32, _cameraViewDataType[CameraView.CLEAR_COLOR] = BufferDataType.FLOAT32, _cameraViewDataType[CameraView.MAT_VIEW] = BufferDataType.FLOAT32, _cameraViewDataType[CameraView.MAT_VIEW_PROJ] = BufferDataType.FLOAT32, _cameraViewDataType[CameraView.MAT_VIEW_PROJ_INV] = BufferDataType.FLOAT32, _cameraViewDataType[CameraView.MAT_PROJ] = BufferDataType.FLOAT32, _cameraViewDataType[CameraView.MAT_PROJ_INV] = BufferDataType.FLOAT32, _cameraViewDataType[CameraView.MAT_VIEW_PROJ_OFFSCREEN] = BufferDataType.FLOAT32, _cameraViewDataType[CameraView.MAT_VIEW_PROJ_INV_OFFSCREEN] = BufferDataType.FLOAT32, _cameraViewDataType[CameraView.MAT_PROJ_OFFSCREEN] = BufferDataType.FLOAT32, _cameraViewDataType[CameraView.MAT_PROJ_INV_OFFSCREEN] = BufferDataType.FLOAT32, _cameraViewDataType[CameraView.COUNT] = BufferDataType.NEVER, _cameraViewDataType);
            var CameraPool = new BufferPool(PoolType.CAMERA, cameraViewDataType, CameraView);
            var NodeView;

            (function (NodeView) {
              NodeView[NodeView["HAS_CHANGED_FLAGS"] = 0] = "HAS_CHANGED_FLAGS";
              NodeView[NodeView["LAYER"] = 1] = "LAYER";
              NodeView[NodeView["WORLD_SCALE"] = 2] = "WORLD_SCALE";
              NodeView[NodeView["WORLD_POSITION"] = 5] = "WORLD_POSITION";
              NodeView[NodeView["WORLD_ROTATION"] = 8] = "WORLD_ROTATION";
              NodeView[NodeView["WORLD_MATRIX"] = 12] = "WORLD_MATRIX";
              NodeView[NodeView["COUNT"] = 28] = "COUNT";
            })(NodeView || (NodeView = {}));

            var nodeViewDataType = (_nodeViewDataType = {}, _nodeViewDataType[NodeView.HAS_CHANGED_FLAGS] = BufferDataType.UINT32, _nodeViewDataType[NodeView.LAYER] = BufferDataType.UINT32, _nodeViewDataType[NodeView.WORLD_SCALE] = BufferDataType.FLOAT32, _nodeViewDataType[NodeView.WORLD_POSITION] = BufferDataType.FLOAT32, _nodeViewDataType[NodeView.WORLD_ROTATION] = BufferDataType.FLOAT32, _nodeViewDataType[NodeView.WORLD_MATRIX] = BufferDataType.FLOAT32, _nodeViewDataType[NodeView.COUNT] = BufferDataType.NEVER, _nodeViewDataType);

            {
              delete NodeView[NodeView.COUNT];
              NodeView[NodeView.COUNT = NodeView.LAYER + 1] = 'COUNT';
            }

            var NodePool = new BufferPool(PoolType.NODE, nodeViewDataType, NodeView);
            var RootView;

            (function (RootView) {
              RootView[RootView["CUMULATIVE_TIME"] = 0] = "CUMULATIVE_TIME";
              RootView[RootView["FRAME_TIME"] = 1] = "FRAME_TIME";
              RootView[RootView["COUNT"] = 2] = "COUNT";
            })(RootView || (RootView = {}));

            var rootViewDataType = (_rootViewDataType = {}, _rootViewDataType[RootView.CUMULATIVE_TIME] = BufferDataType.FLOAT32, _rootViewDataType[RootView.FRAME_TIME] = BufferDataType.FLOAT32, _rootViewDataType[RootView.COUNT] = BufferDataType.NEVER, _rootViewDataType);
            var RootPool = new BufferPool(PoolType.ROOT, rootViewDataType, RootView, 1);
            var RenderWindowView;

            (function (RenderWindowView) {
              RenderWindowView[RenderWindowView["HAS_ON_SCREEN_ATTACHMENTS"] = 0] = "HAS_ON_SCREEN_ATTACHMENTS";
              RenderWindowView[RenderWindowView["HAS_OFF_SCREEN_ATTACHMENTS"] = 1] = "HAS_OFF_SCREEN_ATTACHMENTS";
              RenderWindowView[RenderWindowView["FRAMEBUFFER"] = 2] = "FRAMEBUFFER";
              RenderWindowView[RenderWindowView["COUNT"] = 3] = "COUNT";
            })(RenderWindowView || (RenderWindowView = {}));

            var renderWindowDataType = (_renderWindowDataType = {}, _renderWindowDataType[RenderWindowView.HAS_ON_SCREEN_ATTACHMENTS] = BufferDataType.UINT32, _renderWindowDataType[RenderWindowView.HAS_OFF_SCREEN_ATTACHMENTS] = BufferDataType.UINT32, _renderWindowDataType[RenderWindowView.FRAMEBUFFER] = BufferDataType.UINT32, _renderWindowDataType[RenderWindowView.COUNT] = BufferDataType.NEVER, _renderWindowDataType);
            var RenderWindowPool = new BufferPool(PoolType.RENDER_WINDOW, renderWindowDataType, RenderWindowView, 2);
            var FrustumView;

            (function (FrustumView) {
              FrustumView[FrustumView["VERTICES"] = 0] = "VERTICES";
              FrustumView[FrustumView["PLANES"] = 24] = "PLANES";
              FrustumView[FrustumView["COUNT"] = 48] = "COUNT";
            })(FrustumView || (FrustumView = {}));

            var frustumViewDataType = (_frustumViewDataType = {}, _frustumViewDataType[FrustumView.VERTICES] = BufferDataType.FLOAT32, _frustumViewDataType[FrustumView.PLANES] = BufferDataType.FLOAT32, _frustumViewDataType[FrustumView.COUNT] = BufferDataType.NEVER, _frustumViewDataType);
            var FrustumPool = new BufferPool(PoolType.FRUSTUM, frustumViewDataType, FrustumView);
            var AmbientView;

            (function (AmbientView) {
              AmbientView[AmbientView["ENABLE"] = 0] = "ENABLE";
              AmbientView[AmbientView["ILLUM"] = 1] = "ILLUM";
              AmbientView[AmbientView["SKY_COLOR"] = 2] = "SKY_COLOR";
              AmbientView[AmbientView["GROUND_ALBEDO"] = 6] = "GROUND_ALBEDO";
              AmbientView[AmbientView["COUNT"] = 10] = "COUNT";
            })(AmbientView || (AmbientView = {}));

            var ambientViewDataType = (_ambientViewDataType = {}, _ambientViewDataType[AmbientView.ENABLE] = BufferDataType.UINT32, _ambientViewDataType[AmbientView.ILLUM] = BufferDataType.FLOAT32, _ambientViewDataType[AmbientView.SKY_COLOR] = BufferDataType.FLOAT32, _ambientViewDataType[AmbientView.GROUND_ALBEDO] = BufferDataType.FLOAT32, _ambientViewDataType[AmbientView.COUNT] = BufferDataType.NEVER, _ambientViewDataType);

            {
              delete AmbientView[AmbientView.COUNT];
              AmbientView[AmbientView.COUNT = AmbientView.ILLUM + 1] = 'COUNT';
            }

            var AmbientPool = new BufferPool(PoolType.AMBIENT, ambientViewDataType, AmbientView, 1);
            var SkyboxView;

            (function (SkyboxView) {
              SkyboxView[SkyboxView["ENABLE"] = 0] = "ENABLE";
              SkyboxView[SkyboxView["IS_RGBE"] = 1] = "IS_RGBE";
              SkyboxView[SkyboxView["USE_IBL"] = 2] = "USE_IBL";
              SkyboxView[SkyboxView["MODEL"] = 3] = "MODEL";
              SkyboxView[SkyboxView["COUNT"] = 4] = "COUNT";
            })(SkyboxView || (SkyboxView = {}));

            var skyboxDataType = (_skyboxDataType = {}, _skyboxDataType[SkyboxView.ENABLE] = BufferDataType.UINT32, _skyboxDataType[SkyboxView.IS_RGBE] = BufferDataType.UINT32, _skyboxDataType[SkyboxView.USE_IBL] = BufferDataType.UINT32, _skyboxDataType[SkyboxView.MODEL] = BufferDataType.UINT32, _skyboxDataType[SkyboxView.COUNT] = BufferDataType.NEVER, _skyboxDataType);
            var SkyboxPool = new BufferPool(PoolType.SKYBOX, skyboxDataType, SkyboxView, 1);
            var FogView;

            (function (FogView) {
              FogView[FogView["ENABLE"] = 0] = "ENABLE";
              FogView[FogView["TYPE"] = 1] = "TYPE";
              FogView[FogView["DENSITY"] = 2] = "DENSITY";
              FogView[FogView["START"] = 3] = "START";
              FogView[FogView["END"] = 4] = "END";
              FogView[FogView["ATTEN"] = 5] = "ATTEN";
              FogView[FogView["TOP"] = 6] = "TOP";
              FogView[FogView["RANGE"] = 7] = "RANGE";
              FogView[FogView["COLOR"] = 8] = "COLOR";
              FogView[FogView["COUNT"] = 12] = "COUNT";
            })(FogView || (FogView = {}));

            var fogViewDataType = (_fogViewDataType = {}, _fogViewDataType[FogView.ENABLE] = BufferDataType.UINT32, _fogViewDataType[FogView.TYPE] = BufferDataType.UINT32, _fogViewDataType[FogView.DENSITY] = BufferDataType.FLOAT32, _fogViewDataType[FogView.START] = BufferDataType.FLOAT32, _fogViewDataType[FogView.END] = BufferDataType.FLOAT32, _fogViewDataType[FogView.ATTEN] = BufferDataType.FLOAT32, _fogViewDataType[FogView.TOP] = BufferDataType.FLOAT32, _fogViewDataType[FogView.RANGE] = BufferDataType.FLOAT32, _fogViewDataType[FogView.COLOR] = BufferDataType.FLOAT32, _fogViewDataType[FogView.COUNT] = BufferDataType.NEVER, _fogViewDataType);

            {
              delete FogView[FogView.COUNT];
              FogView[FogView.COUNT = FogView.RANGE + 1] = 'COUNT';
            }

            var FogPool = new BufferPool(PoolType.FOG, fogViewDataType, FogView);
            var ShadowsView;

            (function (ShadowsView) {
              ShadowsView[ShadowsView["ENABLE"] = 0] = "ENABLE";
              ShadowsView[ShadowsView["DIRTY"] = 1] = "DIRTY";
              ShadowsView[ShadowsView["TYPE"] = 2] = "TYPE";
              ShadowsView[ShadowsView["DISTANCE"] = 3] = "DISTANCE";
              ShadowsView[ShadowsView["INSTANCE_PASS"] = 4] = "INSTANCE_PASS";
              ShadowsView[ShadowsView["PLANAR_PASS"] = 5] = "PLANAR_PASS";
              ShadowsView[ShadowsView["NEAR"] = 6] = "NEAR";
              ShadowsView[ShadowsView["FAR"] = 7] = "FAR";
              ShadowsView[ShadowsView["ASPECT"] = 8] = "ASPECT";
              ShadowsView[ShadowsView["PCF_TYPE"] = 9] = "PCF_TYPE";
              ShadowsView[ShadowsView["SHADOW_MAP_DIRTY"] = 10] = "SHADOW_MAP_DIRTY";
              ShadowsView[ShadowsView["BIAS"] = 11] = "BIAS";
              ShadowsView[ShadowsView["PACKING"] = 12] = "PACKING";
              ShadowsView[ShadowsView["LINEAR"] = 13] = "LINEAR";
              ShadowsView[ShadowsView["SELF_SHADOW"] = 14] = "SELF_SHADOW";
              ShadowsView[ShadowsView["NORMAL_BIAS"] = 15] = "NORMAL_BIAS";
              ShadowsView[ShadowsView["ORTHO_SIZE"] = 16] = "ORTHO_SIZE";
              ShadowsView[ShadowsView["AUTO_ADAPT"] = 17] = "AUTO_ADAPT";
              ShadowsView[ShadowsView["COLOR"] = 18] = "COLOR";
              ShadowsView[ShadowsView["SIZE"] = 22] = "SIZE";
              ShadowsView[ShadowsView["NORMAL"] = 24] = "NORMAL";
              ShadowsView[ShadowsView["MAT_LIGHT"] = 27] = "MAT_LIGHT";
              ShadowsView[ShadowsView["COUNT"] = 43] = "COUNT";
            })(ShadowsView || (ShadowsView = {}));

            var shadowsViewDataType = (_shadowsViewDataType = {}, _shadowsViewDataType[ShadowsView.ENABLE] = BufferDataType.UINT32, _shadowsViewDataType[ShadowsView.DIRTY] = BufferDataType.UINT32, _shadowsViewDataType[ShadowsView.TYPE] = BufferDataType.UINT32, _shadowsViewDataType[ShadowsView.DISTANCE] = BufferDataType.FLOAT32, _shadowsViewDataType[ShadowsView.INSTANCE_PASS] = BufferDataType.UINT32, _shadowsViewDataType[ShadowsView.PLANAR_PASS] = BufferDataType.UINT32, _shadowsViewDataType[ShadowsView.NEAR] = BufferDataType.FLOAT32, _shadowsViewDataType[ShadowsView.FAR] = BufferDataType.FLOAT32, _shadowsViewDataType[ShadowsView.ASPECT] = BufferDataType.FLOAT32, _shadowsViewDataType[ShadowsView.PCF_TYPE] = BufferDataType.UINT32, _shadowsViewDataType[ShadowsView.SHADOW_MAP_DIRTY] = BufferDataType.UINT32, _shadowsViewDataType[ShadowsView.BIAS] = BufferDataType.FLOAT32, _shadowsViewDataType[ShadowsView.PACKING] = BufferDataType.UINT32, _shadowsViewDataType[ShadowsView.LINEAR] = BufferDataType.UINT32, _shadowsViewDataType[ShadowsView.SELF_SHADOW] = BufferDataType.UINT32, _shadowsViewDataType[ShadowsView.NORMAL_BIAS] = BufferDataType.FLOAT32, _shadowsViewDataType[ShadowsView.ORTHO_SIZE] = BufferDataType.FLOAT32, _shadowsViewDataType[ShadowsView.AUTO_ADAPT] = BufferDataType.UINT32, _shadowsViewDataType[ShadowsView.COLOR] = BufferDataType.FLOAT32, _shadowsViewDataType[ShadowsView.SIZE] = BufferDataType.FLOAT32, _shadowsViewDataType[ShadowsView.NORMAL] = BufferDataType.FLOAT32, _shadowsViewDataType[ShadowsView.MAT_LIGHT] = BufferDataType.FLOAT32, _shadowsViewDataType[ShadowsView.COUNT] = BufferDataType.NEVER, _shadowsViewDataType);

            {
              delete ShadowsView[ShadowsView.COUNT];
              ShadowsView[ShadowsView.COUNT = ShadowsView.AUTO_ADAPT + 1] = 'COUNT';
            }

            var ShadowsPool = new BufferPool(PoolType.SHADOW, shadowsViewDataType, ShadowsView, 1);
            var PipelineSceneDataView;

            (function (PipelineSceneDataView) {
              PipelineSceneDataView[PipelineSceneDataView["SHADOW"] = 0] = "SHADOW";
              PipelineSceneDataView[PipelineSceneDataView["SKYBOX"] = 1] = "SKYBOX";
              PipelineSceneDataView[PipelineSceneDataView["AMBIENT"] = 2] = "AMBIENT";
              PipelineSceneDataView[PipelineSceneDataView["FOG"] = 3] = "FOG";
              PipelineSceneDataView[PipelineSceneDataView["IS_HDR"] = 4] = "IS_HDR";
              PipelineSceneDataView[PipelineSceneDataView["SHADING_SCALE"] = 5] = "SHADING_SCALE";
              PipelineSceneDataView[PipelineSceneDataView["FP_SCALE"] = 6] = "FP_SCALE";
              PipelineSceneDataView[PipelineSceneDataView["DEFERRED_LIGHT_PASS"] = 7] = "DEFERRED_LIGHT_PASS";
              PipelineSceneDataView[PipelineSceneDataView["DEFERRED_LIGHT_PASS_SHADER"] = 8] = "DEFERRED_LIGHT_PASS_SHADER";
              PipelineSceneDataView[PipelineSceneDataView["DEFERRED_POST_PASS"] = 9] = "DEFERRED_POST_PASS";
              PipelineSceneDataView[PipelineSceneDataView["DEFERRED_POST_PASS_SHADER"] = 10] = "DEFERRED_POST_PASS_SHADER";
              PipelineSceneDataView[PipelineSceneDataView["COUNT"] = 11] = "COUNT";
            })(PipelineSceneDataView || (PipelineSceneDataView = {}));

            var pipelineSceneDataType = (_pipelineSceneDataTyp = {}, _pipelineSceneDataTyp[PipelineSceneDataView.SHADOW] = BufferDataType.UINT32, _pipelineSceneDataTyp[PipelineSceneDataView.SKYBOX] = BufferDataType.UINT32, _pipelineSceneDataTyp[PipelineSceneDataView.AMBIENT] = BufferDataType.UINT32, _pipelineSceneDataTyp[PipelineSceneDataView.FOG] = BufferDataType.UINT32, _pipelineSceneDataTyp[PipelineSceneDataView.IS_HDR] = BufferDataType.UINT32, _pipelineSceneDataTyp[PipelineSceneDataView.SHADING_SCALE] = BufferDataType.UINT32, _pipelineSceneDataTyp[PipelineSceneDataView.FP_SCALE] = BufferDataType.UINT32, _pipelineSceneDataTyp[PipelineSceneDataView.DEFERRED_LIGHT_PASS] = BufferDataType.UINT32, _pipelineSceneDataTyp[PipelineSceneDataView.DEFERRED_LIGHT_PASS_SHADER] = BufferDataType.UINT32, _pipelineSceneDataTyp[PipelineSceneDataView.DEFERRED_POST_PASS] = BufferDataType.UINT32, _pipelineSceneDataTyp[PipelineSceneDataView.DEFERRED_POST_PASS_SHADER] = BufferDataType.UINT32, _pipelineSceneDataTyp[PipelineSceneDataView.COUNT] = BufferDataType.NEVER, _pipelineSceneDataTyp);
            var PipelineSceneDataPool = new BufferPool(PoolType.PIPELINE_SCENE_DATA, pipelineSceneDataType, PipelineSceneDataView, 1);
            var LightView;

            (function (LightView) {
              LightView[LightView["USE_COLOR_TEMPERATURE"] = 0] = "USE_COLOR_TEMPERATURE";
              LightView[LightView["ILLUMINANCE"] = 1] = "ILLUMINANCE";
              LightView[LightView["NODE"] = 2] = "NODE";
              LightView[LightView["RANGE"] = 3] = "RANGE";
              LightView[LightView["TYPE"] = 4] = "TYPE";
              LightView[LightView["AABB"] = 5] = "AABB";
              LightView[LightView["FRUSTUM"] = 6] = "FRUSTUM";
              LightView[LightView["SIZE"] = 7] = "SIZE";
              LightView[LightView["SPOT_ANGLE"] = 8] = "SPOT_ANGLE";
              LightView[LightView["ASPECT"] = 9] = "ASPECT";
              LightView[LightView["DIRECTION"] = 10] = "DIRECTION";
              LightView[LightView["COLOR"] = 13] = "COLOR";
              LightView[LightView["COLOR_TEMPERATURE_RGB"] = 16] = "COLOR_TEMPERATURE_RGB";
              LightView[LightView["POSITION"] = 19] = "POSITION";
              LightView[LightView["COUNT"] = 22] = "COUNT";
            })(LightView || (LightView = {}));

            var lightViewDataType = (_lightViewDataType = {}, _lightViewDataType[LightView.USE_COLOR_TEMPERATURE] = BufferDataType.UINT32, _lightViewDataType[LightView.ILLUMINANCE] = BufferDataType.FLOAT32, _lightViewDataType[LightView.NODE] = BufferDataType.UINT32, _lightViewDataType[LightView.RANGE] = BufferDataType.FLOAT32, _lightViewDataType[LightView.TYPE] = BufferDataType.UINT32, _lightViewDataType[LightView.AABB] = BufferDataType.UINT32, _lightViewDataType[LightView.FRUSTUM] = BufferDataType.UINT32, _lightViewDataType[LightView.SIZE] = BufferDataType.FLOAT32, _lightViewDataType[LightView.SPOT_ANGLE] = BufferDataType.FLOAT32, _lightViewDataType[LightView.ASPECT] = BufferDataType.FLOAT32, _lightViewDataType[LightView.DIRECTION] = BufferDataType.FLOAT32, _lightViewDataType[LightView.COLOR] = BufferDataType.FLOAT32, _lightViewDataType[LightView.COLOR_TEMPERATURE_RGB] = BufferDataType.FLOAT32, _lightViewDataType[LightView.POSITION] = BufferDataType.FLOAT32, _lightViewDataType[LightView.COUNT] = BufferDataType.NEVER, _lightViewDataType);
            var LightPool = new BufferPool(PoolType.LIGHT, lightViewDataType, LightView, 3);
            var SphereView;

            (function (SphereView) {
              SphereView[SphereView["RADIUS"] = 0] = "RADIUS";
              SphereView[SphereView["CENTER"] = 1] = "CENTER";
              SphereView[SphereView["COUNT"] = 4] = "COUNT";
            })(SphereView || (SphereView = {}));

            var sphereViewDataType = (_sphereViewDataType = {}, _sphereViewDataType[SphereView.RADIUS] = BufferDataType.FLOAT32, _sphereViewDataType[SphereView.CENTER] = BufferDataType.FLOAT32, _sphereViewDataType[SphereView.COUNT] = BufferDataType.NEVER, _sphereViewDataType);

            {
              delete SphereView[SphereView.COUNT];
              SphereView[SphereView.COUNT = SphereView.RADIUS + 1] = 'COUNT';
            }

            var SpherePool = new BufferPool(PoolType.SPHERE, sphereViewDataType, SphereView, 3);
            var FlatBufferView;

            (function (FlatBufferView) {
              FlatBufferView[FlatBufferView["STRIDE"] = 0] = "STRIDE";
              FlatBufferView[FlatBufferView["AMOUNT"] = 1] = "AMOUNT";
              FlatBufferView[FlatBufferView["BUFFER"] = 2] = "BUFFER";
              FlatBufferView[FlatBufferView["COUNT"] = 3] = "COUNT";
            })(FlatBufferView || (FlatBufferView = {}));

            var flatBufferViewDataType = (_flatBufferViewDataTy = {}, _flatBufferViewDataTy[FlatBufferView.STRIDE] = BufferDataType.UINT32, _flatBufferViewDataTy[FlatBufferView.AMOUNT] = BufferDataType.UINT32, _flatBufferViewDataTy[FlatBufferView.BUFFER] = BufferDataType.UINT32, _flatBufferViewDataTy[FlatBufferView.COUNT] = BufferDataType.NEVER, _flatBufferViewDataTy);
            var FlatBufferPool = new BufferPool(PoolType.FLAT_BUFFER, flatBufferViewDataType, FlatBufferView, 3);
            var SubMeshView;

            (function (SubMeshView) {
              SubMeshView[SubMeshView["FLAT_BUFFER_ARRAY"] = 0] = "FLAT_BUFFER_ARRAY";
              SubMeshView[SubMeshView["COUNT"] = 1] = "COUNT";
            })(SubMeshView || (SubMeshView = {}));

            var subMeshViewDataType = (_subMeshViewDataType = {}, _subMeshViewDataType[SubMeshView.FLAT_BUFFER_ARRAY] = BufferDataType.UINT32, _subMeshViewDataType[SubMeshView.COUNT] = BufferDataType.NEVER, _subMeshViewDataType);
            var SubMeshPool = new BufferPool(PoolType.SUB_MESH, subMeshViewDataType, SubMeshView, 3);
            var RasterizerStateView;

            (function (RasterizerStateView) {
              RasterizerStateView[RasterizerStateView["IS_DISCARD"] = 0] = "IS_DISCARD";
              RasterizerStateView[RasterizerStateView["POLYGO_MODEL"] = 1] = "POLYGO_MODEL";
              RasterizerStateView[RasterizerStateView["SHADE_MODEL"] = 2] = "SHADE_MODEL";
              RasterizerStateView[RasterizerStateView["CULL_MODE"] = 3] = "CULL_MODE";
              RasterizerStateView[RasterizerStateView["IS_FRONT_FACE_CCW"] = 4] = "IS_FRONT_FACE_CCW";
              RasterizerStateView[RasterizerStateView["DEPTH_BIAS_ENABLED"] = 5] = "DEPTH_BIAS_ENABLED";
              RasterizerStateView[RasterizerStateView["DEPTH_BIAS"] = 6] = "DEPTH_BIAS";
              RasterizerStateView[RasterizerStateView["DEPTH_BIAS_CLAMP"] = 7] = "DEPTH_BIAS_CLAMP";
              RasterizerStateView[RasterizerStateView["DEPTH_BIAS_SLOP"] = 8] = "DEPTH_BIAS_SLOP";
              RasterizerStateView[RasterizerStateView["IS_DEPTH_CLIP"] = 9] = "IS_DEPTH_CLIP";
              RasterizerStateView[RasterizerStateView["IS_MULTI_SAMPLE"] = 10] = "IS_MULTI_SAMPLE";
              RasterizerStateView[RasterizerStateView["LINE_WIDTH"] = 11] = "LINE_WIDTH";
              RasterizerStateView[RasterizerStateView["COUNT"] = 12] = "COUNT";
            })(RasterizerStateView || (RasterizerStateView = {}));

            var rasterizerStateViewDataType = (_rasterizerStateViewD = {}, _rasterizerStateViewD[RasterizerStateView.IS_DISCARD] = BufferDataType.UINT32, _rasterizerStateViewD[RasterizerStateView.POLYGO_MODEL] = BufferDataType.UINT32, _rasterizerStateViewD[RasterizerStateView.SHADE_MODEL] = BufferDataType.UINT32, _rasterizerStateViewD[RasterizerStateView.CULL_MODE] = BufferDataType.UINT32, _rasterizerStateViewD[RasterizerStateView.IS_FRONT_FACE_CCW] = BufferDataType.UINT32, _rasterizerStateViewD[RasterizerStateView.DEPTH_BIAS_ENABLED] = BufferDataType.UINT32, _rasterizerStateViewD[RasterizerStateView.DEPTH_BIAS] = BufferDataType.FLOAT32, _rasterizerStateViewD[RasterizerStateView.DEPTH_BIAS_CLAMP] = BufferDataType.FLOAT32, _rasterizerStateViewD[RasterizerStateView.DEPTH_BIAS_SLOP] = BufferDataType.FLOAT32, _rasterizerStateViewD[RasterizerStateView.IS_DEPTH_CLIP] = BufferDataType.UINT32, _rasterizerStateViewD[RasterizerStateView.IS_MULTI_SAMPLE] = BufferDataType.UINT32, _rasterizerStateViewD[RasterizerStateView.LINE_WIDTH] = BufferDataType.FLOAT32, _rasterizerStateViewD[RasterizerStateView.COUNT] = BufferDataType.NEVER, _rasterizerStateViewD);
            var RasterizerStatePool = new BufferPool(PoolType.RASTERIZER_STATE, rasterizerStateViewDataType, RasterizerStateView, 9);
            var DepthStencilStateView;

            (function (DepthStencilStateView) {
              DepthStencilStateView[DepthStencilStateView["DEPTH_TEST"] = 0] = "DEPTH_TEST";
              DepthStencilStateView[DepthStencilStateView["DEPTH_WRITE"] = 1] = "DEPTH_WRITE";
              DepthStencilStateView[DepthStencilStateView["DEPTH_FUNC"] = 2] = "DEPTH_FUNC";
              DepthStencilStateView[DepthStencilStateView["STENCIL_TEST_FRONT"] = 3] = "STENCIL_TEST_FRONT";
              DepthStencilStateView[DepthStencilStateView["STENCIL_FUNC_FRONT"] = 4] = "STENCIL_FUNC_FRONT";
              DepthStencilStateView[DepthStencilStateView["STENCIL_READ_MASK_FRONT"] = 5] = "STENCIL_READ_MASK_FRONT";
              DepthStencilStateView[DepthStencilStateView["STENCIL_WRITE_MASK_FRONT"] = 6] = "STENCIL_WRITE_MASK_FRONT";
              DepthStencilStateView[DepthStencilStateView["STENCIL_FAIL_OP_FRONT"] = 7] = "STENCIL_FAIL_OP_FRONT";
              DepthStencilStateView[DepthStencilStateView["STENCIL_Z_FAIL_OP_FRONT"] = 8] = "STENCIL_Z_FAIL_OP_FRONT";
              DepthStencilStateView[DepthStencilStateView["STENCIL_PASS_OP_FRONT"] = 9] = "STENCIL_PASS_OP_FRONT";
              DepthStencilStateView[DepthStencilStateView["STENCIL_REF_FRONT"] = 10] = "STENCIL_REF_FRONT";
              DepthStencilStateView[DepthStencilStateView["STENCIL_TEST_BACK"] = 11] = "STENCIL_TEST_BACK";
              DepthStencilStateView[DepthStencilStateView["STENCIL_FUNC_BACK"] = 12] = "STENCIL_FUNC_BACK";
              DepthStencilStateView[DepthStencilStateView["STENCIL_READ_MADK_BACK"] = 13] = "STENCIL_READ_MADK_BACK";
              DepthStencilStateView[DepthStencilStateView["STENCIL_WRITE_MASK_BACK"] = 14] = "STENCIL_WRITE_MASK_BACK";
              DepthStencilStateView[DepthStencilStateView["STENCIL_FAIL_OP_BACK"] = 15] = "STENCIL_FAIL_OP_BACK";
              DepthStencilStateView[DepthStencilStateView["STENCIL_Z_FAIL_OP_BACK"] = 16] = "STENCIL_Z_FAIL_OP_BACK";
              DepthStencilStateView[DepthStencilStateView["STENCIL_PASS_OP_BACK"] = 17] = "STENCIL_PASS_OP_BACK";
              DepthStencilStateView[DepthStencilStateView["STENCIL_REF_BACK"] = 18] = "STENCIL_REF_BACK";
              DepthStencilStateView[DepthStencilStateView["COUNT"] = 19] = "COUNT";
            })(DepthStencilStateView || (DepthStencilStateView = {}));

            var depthStencilStateViewDataType = (_depthStencilStateVie = {}, _depthStencilStateVie[DepthStencilStateView.DEPTH_TEST] = BufferDataType.UINT32, _depthStencilStateVie[DepthStencilStateView.DEPTH_WRITE] = BufferDataType.UINT32, _depthStencilStateVie[DepthStencilStateView.DEPTH_FUNC] = BufferDataType.UINT32, _depthStencilStateVie[DepthStencilStateView.STENCIL_TEST_FRONT] = BufferDataType.UINT32, _depthStencilStateVie[DepthStencilStateView.STENCIL_FUNC_FRONT] = BufferDataType.UINT32, _depthStencilStateVie[DepthStencilStateView.STENCIL_READ_MASK_FRONT] = BufferDataType.UINT32, _depthStencilStateVie[DepthStencilStateView.STENCIL_WRITE_MASK_FRONT] = BufferDataType.UINT32, _depthStencilStateVie[DepthStencilStateView.STENCIL_FAIL_OP_FRONT] = BufferDataType.UINT32, _depthStencilStateVie[DepthStencilStateView.STENCIL_Z_FAIL_OP_FRONT] = BufferDataType.UINT32, _depthStencilStateVie[DepthStencilStateView.STENCIL_PASS_OP_FRONT] = BufferDataType.UINT32, _depthStencilStateVie[DepthStencilStateView.STENCIL_REF_FRONT] = BufferDataType.UINT32, _depthStencilStateVie[DepthStencilStateView.STENCIL_TEST_BACK] = BufferDataType.UINT32, _depthStencilStateVie[DepthStencilStateView.STENCIL_FUNC_BACK] = BufferDataType.UINT32, _depthStencilStateVie[DepthStencilStateView.STENCIL_READ_MADK_BACK] = BufferDataType.UINT32, _depthStencilStateVie[DepthStencilStateView.STENCIL_WRITE_MASK_BACK] = BufferDataType.UINT32, _depthStencilStateVie[DepthStencilStateView.STENCIL_FAIL_OP_BACK] = BufferDataType.UINT32, _depthStencilStateVie[DepthStencilStateView.STENCIL_Z_FAIL_OP_BACK] = BufferDataType.UINT32, _depthStencilStateVie[DepthStencilStateView.STENCIL_PASS_OP_BACK] = BufferDataType.UINT32, _depthStencilStateVie[DepthStencilStateView.STENCIL_REF_BACK] = BufferDataType.UINT32, _depthStencilStateVie[DepthStencilStateView.COUNT] = BufferDataType.NEVER, _depthStencilStateVie);
            var DepthStencilStatePool = new BufferPool(PoolType.DEPTH_STENCIL_STATE, depthStencilStateViewDataType, DepthStencilStateView, 9);
            var BlendTargetView;

            (function (BlendTargetView) {
              BlendTargetView[BlendTargetView["BLEND"] = 0] = "BLEND";
              BlendTargetView[BlendTargetView["BLEND_SRC"] = 1] = "BLEND_SRC";
              BlendTargetView[BlendTargetView["BLEND_DST"] = 2] = "BLEND_DST";
              BlendTargetView[BlendTargetView["BLEND_EQ"] = 3] = "BLEND_EQ";
              BlendTargetView[BlendTargetView["BLEND_SRC_ALPHA"] = 4] = "BLEND_SRC_ALPHA";
              BlendTargetView[BlendTargetView["BLEND_DST_ALPHA"] = 5] = "BLEND_DST_ALPHA";
              BlendTargetView[BlendTargetView["BLEND_ALPHA_EQ"] = 6] = "BLEND_ALPHA_EQ";
              BlendTargetView[BlendTargetView["BLEND_COLOR_MASK"] = 7] = "BLEND_COLOR_MASK";
              BlendTargetView[BlendTargetView["COUNT"] = 8] = "COUNT";
            })(BlendTargetView || (BlendTargetView = {}));

            var blendTargetViewDataType = (_blendTargetViewDataT = {}, _blendTargetViewDataT[BlendTargetView.BLEND] = BufferDataType.UINT32, _blendTargetViewDataT[BlendTargetView.BLEND_SRC] = BufferDataType.UINT32, _blendTargetViewDataT[BlendTargetView.BLEND_DST] = BufferDataType.UINT32, _blendTargetViewDataT[BlendTargetView.BLEND_EQ] = BufferDataType.UINT32, _blendTargetViewDataT[BlendTargetView.BLEND_SRC_ALPHA] = BufferDataType.UINT32, _blendTargetViewDataT[BlendTargetView.BLEND_DST_ALPHA] = BufferDataType.UINT32, _blendTargetViewDataT[BlendTargetView.BLEND_ALPHA_EQ] = BufferDataType.UINT32, _blendTargetViewDataT[BlendTargetView.BLEND_COLOR_MASK] = BufferDataType.UINT32, _blendTargetViewDataT[BlendTargetView.COUNT] = BufferDataType.NEVER, _blendTargetViewDataT);
            var BlendTargetPool = new BufferPool(PoolType.BLEND_TARGET, depthStencilStateViewDataType, BlendTargetView, 9);
            var BlendStateView;

            (function (BlendStateView) {
              BlendStateView[BlendStateView["IS_A2C"] = 0] = "IS_A2C";
              BlendStateView[BlendStateView["IS_INDEPEND"] = 1] = "IS_INDEPEND";
              BlendStateView[BlendStateView["BLEND_COLOR"] = 2] = "BLEND_COLOR";
              BlendStateView[BlendStateView["BLEND_TARGET"] = 6] = "BLEND_TARGET";
              BlendStateView[BlendStateView["COUNT"] = 7] = "COUNT";
            })(BlendStateView || (BlendStateView = {}));

            var blendStateViewDataType = (_blendStateViewDataTy = {}, _blendStateViewDataTy[BlendStateView.IS_A2C] = BufferDataType.UINT32, _blendStateViewDataTy[BlendStateView.IS_INDEPEND] = BufferDataType.UINT32, _blendStateViewDataTy[BlendStateView.BLEND_COLOR] = BufferDataType.FLOAT32, _blendStateViewDataTy[BlendStateView.BLEND_TARGET] = BufferDataType.UINT32, _blendStateViewDataTy[BlendStateView.COUNT] = BufferDataType.NEVER, _blendStateViewDataTy);
            var BlendStatePool = new BufferPool(PoolType.BLEND_STATE, blendStateViewDataType, BlendStateView, 9);

            var Ambient = function () {
              function Ambient() {
                this._skyColor = new Color(51, 128, 204, 1.0);
                this._groundAlbedo = new Color(51, 51, 51, 255);
                this._albedoArray = Float32Array.from([0.2, 0.2, 0.2, 1.0]);
                this._colorArray = Float32Array.from([0.2, 0.5, 0.8, 1.0]);
                this._handle = NULL_HANDLE;
                this._handle = AmbientPool.alloc();
              }

              var _proto = Ambient.prototype;

              _proto.initialize = function initialize(ambientInfo) {
                this._skyColor.set(ambientInfo.skyColor);

                this._groundAlbedo.set(ambientInfo.groundAlbedo);

                Color.toArray(this._colorArray, this._skyColor);
                Vec3.toArray(this._albedoArray, this._groundAlbedo);
                AmbientPool.setVec4(this._handle, AmbientView.SKY_COLOR, this._skyColor);
                AmbientPool.setVec4(this._handle, AmbientView.GROUND_ALBEDO, this._groundAlbedo);
                AmbientPool.set(this._handle, AmbientView.ILLUM, ambientInfo.skyIllum);
              };

              _proto.destroy = function destroy() {
                if (this._handle) {
                  AmbientPool.free(this._handle);
                  this._handle = NULL_HANDLE;
                }
              };

              _createClass(Ambient, [{
                key: "colorArray",
                get: function get() {
                  return this._colorArray;
                }
              }, {
                key: "albedoArray",
                get: function get() {
                  return this._albedoArray;
                }
              }, {
                key: "enabled",
                get: function get() {
                  return AmbientPool.get(this._handle, AmbientView.ENABLE);
                },
                set: function set(val) {
                  AmbientPool.set(this._handle, AmbientView.ENABLE, val ? 1 : 0);
                }
              }, {
                key: "skyColor",
                get: function get() {
                  return this._skyColor;
                },
                set: function set(color) {
                  this._skyColor.set(color);

                  Color.toArray(this._colorArray, this._skyColor);
                  AmbientPool.setVec4(this._handle, AmbientView.SKY_COLOR, this._skyColor);
                }
              }, {
                key: "skyIllum",
                get: function get() {
                  return AmbientPool.get(this._handle, AmbientView.ILLUM);
                },
                set: function set(illum) {
                  AmbientPool.set(this._handle, AmbientView.ILLUM, illum);
                }
              }, {
                key: "groundAlbedo",
                get: function get() {
                  return this._groundAlbedo;
                },
                set: function set(color) {
                  this._groundAlbedo.set(color);

                  Vec3.toArray(this._albedoArray, this._groundAlbedo);
                  AmbientPool.setVec4(this._handle, AmbientView.GROUND_ALBEDO, this._groundAlbedo);
                }
              }, {
                key: "handle",
                get: function get() {
                  return this._handle;
                }
              }]);

              return Ambient;
            }();
            Ambient.SUN_ILLUM = 65000.0;
            Ambient.SKY_ILLUM = 20000.0;
            legacyCC.Ambient = Ambient;

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

              for (var i = 0; i < 3; i++) {
                var dist = Vec3.dot(d, u[i]);

                if (dist > e[i]) {
                  dist = e[i];
                }

                if (dist < -e[i]) {
                  dist = -e[i];
                }

                out.x += dist * u[i].x;
                out.y += dist * u[i].y;
                out.z += dist * u[i].z;
              }

              return out;
            }
            function pt_point_line(out, point, linePointA, linePointB) {
              Vec3.subtract(X, linePointA, linePointB);
              var dir = X;
              var dirSquaredLength = Vec3.lengthSqr(dir);

              if (dirSquaredLength == 0) {
                Vec3.copy(out, linePointA);
              } else {
                Vec3.subtract(X, point, linePointA);
                var t = Vec3.dot(X, dir) / dirSquaredLength;

                if (t < 0) {
                  Vec3.copy(out, linePointA);
                } else if (t > 1) {
                  Vec3.copy(out, linePointB);
                } else {
                  Vec3.scaleAndAdd(out, linePointA, dir, t);
                }
              }
            }

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

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

            var Line = function () {
              Line.create = function create(sx, sy, sz, ex, ey, ez) {
                return new Line(sx, sy, sz, ex, ey, ez);
              };

              Line.clone = function clone(a) {
                return new Line(a.s.x, a.s.y, a.s.z, a.e.x, a.e.y, a.e.z);
              };

              Line.copy = function copy(out, a) {
                Vec3.copy(out.s, a.s);
                Vec3.copy(out.e, a.e);
                return out;
              };

              Line.fromPoints = function fromPoints(out, start, end) {
                Vec3.copy(out.s, start);
                Vec3.copy(out.e, end);
                return out;
              };

              Line.set = function set(out, sx, sy, sz, ex, ey, ez) {
                out.s.x = sx;
                out.s.y = sy;
                out.s.z = sz;
                out.e.x = ex;
                out.e.y = ey;
                out.e.z = ez;
                return out;
              };

              Line.len = function len(a) {
                return Vec3.distance(a.s, a.e);
              };

              function Line(sx, sy, sz, ex, ey, ez) {
                if (sx === void 0) {
                  sx = 0;
                }

                if (sy === void 0) {
                  sy = 0;
                }

                if (sz === void 0) {
                  sz = 0;
                }

                if (ex === void 0) {
                  ex = 0;
                }

                if (ey === void 0) {
                  ey = 0;
                }

                if (ez === void 0) {
                  ez = -1;
                }

                this.s = void 0;
                this.e = void 0;
                this._type = void 0;
                this._type = enums.SHAPE_LINE;
                this.s = new Vec3(sx, sy, sz);
                this.e = new Vec3(ex, ey, ez);
              }

              var _proto = Line.prototype;

              _proto.length = function length() {
                return Vec3.distance(this.s, this.e);
              };

              _createClass(Line, [{
                key: "type",
                get: function get() {
                  return this._type;
                }
              }]);

              return Line;
            }();

            var Ray = function () {
              Ray.create = function create(ox, oy, oz, dx, dy, dz) {
                if (ox === void 0) {
                  ox = 0;
                }

                if (oy === void 0) {
                  oy = 0;
                }

                if (oz === void 0) {
                  oz = 0;
                }

                if (dx === void 0) {
                  dx = 0;
                }

                if (dy === void 0) {
                  dy = 0;
                }

                if (dz === void 0) {
                  dz = 1;
                }

                return new Ray(ox, oy, oz, dx, dy, dz);
              };

              Ray.clone = function clone(a) {
                return new Ray(a.o.x, a.o.y, a.o.z, a.d.x, a.d.y, a.d.z);
              };

              Ray.copy = function copy(out, a) {
                Vec3.copy(out.o, a.o);
                Vec3.copy(out.d, a.d);
                return out;
              };

              Ray.fromPoints = function fromPoints(out, origin, target) {
                Vec3.copy(out.o, origin);
                Vec3.normalize(out.d, Vec3.subtract(out.d, target, origin));
                return out;
              };

              Ray.set = function set(out, ox, oy, oz, dx, dy, dz) {
                out.o.x = ox;
                out.o.y = oy;
                out.o.z = oz;
                out.d.x = dx;
                out.d.y = dy;
                out.d.z = dz;
                return out;
              };

              function Ray(ox, oy, oz, dx, dy, dz) {
                if (ox === void 0) {
                  ox = 0;
                }

                if (oy === void 0) {
                  oy = 0;
                }

                if (oz === void 0) {
                  oz = 0;
                }

                if (dx === void 0) {
                  dx = 0;
                }

                if (dy === void 0) {
                  dy = 0;
                }

                if (dz === void 0) {
                  dz = -1;
                }

                this.o = void 0;
                this.d = void 0;
                this._type = void 0;
                this._type = enums.SHAPE_RAY;
                this.o = new Vec3(ox, oy, oz);
                this.d = new Vec3(dx, dy, dz);
              }

              var _proto = Ray.prototype;

              _proto.computeHit = function computeHit(out, distance) {
                Vec3.normalize(out, this.d);
                Vec3.scaleAndAdd(out, this.o, out, distance);
              };

              _createClass(Ray, [{
                key: "type",
                get: function get() {
                  return this._type;
                }
              }]);

              return Ray;
            }();

            var _v3_tmp = new Vec3();

            var _offset = new Vec3();

            var _min = new Vec3();

            var _max = new Vec3();

            function maxComponent(v) {
              return Math.max(Math.max(v.x, v.y), v.z);
            }

            var Sphere = function () {
              Sphere.create = function create(cx, cy, cz, r) {
                return new Sphere(cx, cy, cz, r);
              };

              Sphere.clone = function clone(p) {
                return new Sphere(p.center.x, p.center.y, p.center.z, p.radius);
              };

              Sphere.copy = function copy(out, p) {
                Vec3.copy(out.center, p.center);
                out.radius = p.radius;
                return out;
              };

              Sphere.fromPoints = function fromPoints(out, minPos, maxPos) {
                Vec3.multiplyScalar(out.center, Vec3.add(_v3_tmp, minPos, maxPos), 0.5);
                out.radius = Vec3.subtract(_v3_tmp, maxPos, minPos).length() * 0.5;
                return out;
              };

              Sphere.set = function set(out, cx, cy, cz, r) {
                out.center.x = cx;
                out.center.y = cy;
                out.center.z = cz;
                out.radius = r;
                return out;
              };

              Sphere.mergePoint = function mergePoint(out, s, point) {
                if (s.radius < 0.0) {
                  out.center.set(point);
                  out.radius = 0.0;
                  return out;
                }

                Vec3.subtract(_offset, point, s.center);

                var dist = _offset.length();

                if (dist > s.radius) {
                  var half = (dist - s.radius) * 0.5;
                  out.radius += half;
                  Vec3.multiplyScalar(_offset, _offset, half / dist);
                  Vec3.add(out.center, out.center, _offset);
                }

                return out;
              };

              Sphere.mergeAABB = function mergeAABB(out, s, a) {
                a.getBoundary(_min, _max);
                Sphere.mergePoint(out, s, _min);
                Sphere.mergePoint(out, s, _max);
                return out;
              };

              function Sphere(cx, cy, cz, r) {
                if (cx === void 0) {
                  cx = 0;
                }

                if (cy === void 0) {
                  cy = 0;
                }

                if (cz === void 0) {
                  cz = 0;
                }

                if (r === void 0) {
                  r = 1;
                }

                this._center = new Vec3(0, 0, 0);
                this._poolHandle = NULL_HANDLE;
                this._type = void 0;
                this._type = enums.SHAPE_SPHERE;
                this._center = new Vec3(cx, cy, cz);
                this._poolHandle = SpherePool.alloc();
                SpherePool.setVec3(this._poolHandle, SphereView.CENTER, this._center);
                SpherePool.set(this._poolHandle, SphereView.RADIUS, r);
              }

              var _proto = Sphere.prototype;

              _proto.destroy = function destroy() {
                if (this._poolHandle) {
                  SpherePool.free(this._poolHandle);
                  this._poolHandle = NULL_HANDLE;
                }
              };

              _proto.clone = function clone() {
                return Sphere.clone(this);
              };

              _proto.copy = function copy(a) {
                return Sphere.copy(this, a);
              };

              _proto.getBoundary = function getBoundary(minPos, maxPos) {
                Vec3.set(minPos, this.center.x - this.radius, this.center.y - this.radius, this.center.z - this.radius);
                Vec3.set(maxPos, this.center.x + this.radius, this.center.y + this.radius, this.center.z + this.radius);
              };

              _proto.transform = function transform(m, pos, rot, scale, out) {
                Vec3.transformMat4(out.center, this.center, m);
                out.radius = this.radius * maxComponent(scale);
              };

              _proto.translateAndRotate = function translateAndRotate(m, rot, out) {
                Vec3.transformMat4(out.center, this.center, m);
              };

              _proto.setScale = function setScale(scale, out) {
                out.radius = this.radius * maxComponent(scale);
              };

              _createClass(Sphere, [{
                key: "center",
                get: function get() {
                  return this._center;
                },
                set: function set(val) {
                  this._center = val;
                  SpherePool.setVec3(this._poolHandle, SphereView.CENTER, this._center);
                }
              }, {
                key: "radius",
                get: function get() {
                  return SpherePool.get(this._poolHandle, SphereView.RADIUS);
                },
                set: function set(val) {
                  SpherePool.set(this._poolHandle, SphereView.RADIUS, val);
                }
              }, {
                key: "handle",
                get: function get() {
                  return this._poolHandle;
                }
              }, {
                key: "type",
                get: function get() {
                  return this._type;
                }
              }]);

              return Sphere;
            }();

            var Triangle = function () {
              Triangle.create = function create(ax, ay, az, bx, by, bz, cx, cy, cz) {
                if (ax === void 0) {
                  ax = 1;
                }

                if (ay === void 0) {
                  ay = 0;
                }

                if (az === void 0) {
                  az = 0;
                }

                if (bx === void 0) {
                  bx = 0;
                }

                if (by === void 0) {
                  by = 0;
                }

                if (bz === void 0) {
                  bz = 0;
                }

                if (cx === void 0) {
                  cx = 0;
                }

                if (cy === void 0) {
                  cy = 0;
                }

                if (cz === void 0) {
                  cz = 1;
                }

                return new Triangle(ax, ay, az, bx, by, bz, cx, cy, cz);
              };

              Triangle.clone = function clone(t) {
                return new Triangle(t.a.x, t.a.y, t.a.z, t.b.x, t.b.y, t.b.z, t.c.x, t.c.y, t.c.z);
              };

              Triangle.copy = function copy(out, t) {
                Vec3.copy(out.a, t.a);
                Vec3.copy(out.b, t.b);
                Vec3.copy(out.c, t.c);
                return out;
              };

              Triangle.fromPoints = function fromPoints(out, a, b, c) {
                Vec3.copy(out.a, a);
                Vec3.copy(out.b, b);
                Vec3.copy(out.c, c);
                return out;
              };

              Triangle.set = function set(out, ax, ay, az, bx, by, bz, cx, cy, cz) {
                out.a.x = ax;
                out.a.y = ay;
                out.a.z = az;
                out.b.x = bx;
                out.b.y = by;
                out.b.z = bz;
                out.c.x = cx;
                out.c.y = cy;
                out.c.z = cz;
                return out;
              };

              function Triangle(ax, ay, az, bx, by, bz, cx, cy, cz) {
                if (ax === void 0) {
                  ax = 0;
                }

                if (ay === void 0) {
                  ay = 0;
                }

                if (az === void 0) {
                  az = 0;
                }

                if (bx === void 0) {
                  bx = 1;
                }

                if (by === void 0) {
                  by = 0;
                }

                if (bz === void 0) {
                  bz = 0;
                }

                if (cx === void 0) {
                  cx = 0;
                }

                if (cy === void 0) {
                  cy = 1;
                }

                if (cz === void 0) {
                  cz = 0;
                }

                this.a = void 0;
                this.b = void 0;
                this.c = void 0;
                this._type = void 0;
                this._type = enums.SHAPE_TRIANGLE;
                this.a = new Vec3(ax, ay, az);
                this.b = new Vec3(bx, by, bz);
                this.c = new Vec3(cx, cy, cz);
              }

              _createClass(Triangle, [{
                key: "type",
                get: function get() {
                  return this._type;
                }
              }]);

              return Triangle;
            }();

            var deepCopy = function deepCopy(target, source, Ctor) {
              for (var i = 0; i < source.length; ++i) {
                if (target.length <= i) target.push(new Ctor());
                target[i].copy(source[i]);
              }

              target.length = source.length;
            };

            var ObjectType;

            (function (ObjectType) {
              ObjectType[ObjectType["UNKNOWN"] = 0] = "UNKNOWN";
              ObjectType[ObjectType["BUFFER"] = 1] = "BUFFER";
              ObjectType[ObjectType["TEXTURE"] = 2] = "TEXTURE";
              ObjectType[ObjectType["RENDER_PASS"] = 3] = "RENDER_PASS";
              ObjectType[ObjectType["FRAMEBUFFER"] = 4] = "FRAMEBUFFER";
              ObjectType[ObjectType["SAMPLER"] = 5] = "SAMPLER";
              ObjectType[ObjectType["SHADER"] = 6] = "SHADER";
              ObjectType[ObjectType["DESCRIPTOR_SET_LAYOUT"] = 7] = "DESCRIPTOR_SET_LAYOUT";
              ObjectType[ObjectType["PIPELINE_LAYOUT"] = 8] = "PIPELINE_LAYOUT";
              ObjectType[ObjectType["PIPELINE_STATE"] = 9] = "PIPELINE_STATE";
              ObjectType[ObjectType["DESCRIPTOR_SET"] = 10] = "DESCRIPTOR_SET";
              ObjectType[ObjectType["INPUT_ASSEMBLER"] = 11] = "INPUT_ASSEMBLER";
              ObjectType[ObjectType["COMMAND_BUFFER"] = 12] = "COMMAND_BUFFER";
              ObjectType[ObjectType["QUEUE"] = 13] = "QUEUE";
              ObjectType[ObjectType["GLOBAL_BARRIER"] = 14] = "GLOBAL_BARRIER";
              ObjectType[ObjectType["TEXTURE_BARRIER"] = 15] = "TEXTURE_BARRIER";
              ObjectType[ObjectType["BUFFER_BARRIER"] = 16] = "BUFFER_BARRIER";
            })(ObjectType || (ObjectType = {}));

            var Status;

            (function (Status) {
              Status[Status["UNREADY"] = 0] = "UNREADY";
              Status[Status["FAILED"] = 1] = "FAILED";
              Status[Status["SUCCESS"] = 2] = "SUCCESS";
            })(Status || (Status = {}));

            var API;

            (function (API) {
              API[API["UNKNOWN"] = 0] = "UNKNOWN";
              API[API["GLES2"] = 1] = "GLES2";
              API[API["GLES3"] = 2] = "GLES3";
              API[API["METAL"] = 3] = "METAL";
              API[API["VULKAN"] = 4] = "VULKAN";
              API[API["WEBGL"] = 5] = "WEBGL";
              API[API["WEBGL2"] = 6] = "WEBGL2";
              API[API["WEBGPU"] = 7] = "WEBGPU";
            })(API || (API = {}));

            var SurfaceTransform;

            (function (SurfaceTransform) {
              SurfaceTransform[SurfaceTransform["IDENTITY"] = 0] = "IDENTITY";
              SurfaceTransform[SurfaceTransform["ROTATE_90"] = 1] = "ROTATE_90";
              SurfaceTransform[SurfaceTransform["ROTATE_180"] = 2] = "ROTATE_180";
              SurfaceTransform[SurfaceTransform["ROTATE_270"] = 3] = "ROTATE_270";
            })(SurfaceTransform || (SurfaceTransform = {}));

            var Feature;

            (function (Feature) {
              Feature[Feature["COLOR_FLOAT"] = 0] = "COLOR_FLOAT";
              Feature[Feature["COLOR_HALF_FLOAT"] = 1] = "COLOR_HALF_FLOAT";
              Feature[Feature["TEXTURE_FLOAT"] = 2] = "TEXTURE_FLOAT";
              Feature[Feature["TEXTURE_HALF_FLOAT"] = 3] = "TEXTURE_HALF_FLOAT";
              Feature[Feature["TEXTURE_FLOAT_LINEAR"] = 4] = "TEXTURE_FLOAT_LINEAR";
              Feature[Feature["TEXTURE_HALF_FLOAT_LINEAR"] = 5] = "TEXTURE_HALF_FLOAT_LINEAR";
              Feature[Feature["FORMAT_R11G11B10F"] = 6] = "FORMAT_R11G11B10F";
              Feature[Feature["FORMAT_D16"] = 7] = "FORMAT_D16";
              Feature[Feature["FORMAT_D16S8"] = 8] = "FORMAT_D16S8";
              Feature[Feature["FORMAT_D24"] = 9] = "FORMAT_D24";
              Feature[Feature["FORMAT_D24S8"] = 10] = "FORMAT_D24S8";
              Feature[Feature["FORMAT_D32F"] = 11] = "FORMAT_D32F";
              Feature[Feature["FORMAT_D32FS8"] = 12] = "FORMAT_D32FS8";
              Feature[Feature["FORMAT_ETC1"] = 13] = "FORMAT_ETC1";
              Feature[Feature["FORMAT_ETC2"] = 14] = "FORMAT_ETC2";
              Feature[Feature["FORMAT_DXT"] = 15] = "FORMAT_DXT";
              Feature[Feature["FORMAT_PVRTC"] = 16] = "FORMAT_PVRTC";
              Feature[Feature["FORMAT_ASTC"] = 17] = "FORMAT_ASTC";
              Feature[Feature["FORMAT_RGB8"] = 18] = "FORMAT_RGB8";
              Feature[Feature["MSAA"] = 19] = "MSAA";
              Feature[Feature["ELEMENT_INDEX_UINT"] = 20] = "ELEMENT_INDEX_UINT";
              Feature[Feature["INSTANCED_ARRAYS"] = 21] = "INSTANCED_ARRAYS";
              Feature[Feature["MULTIPLE_RENDER_TARGETS"] = 22] = "MULTIPLE_RENDER_TARGETS";
              Feature[Feature["BLEND_MINMAX"] = 23] = "BLEND_MINMAX";
              Feature[Feature["DEPTH_BOUNDS"] = 24] = "DEPTH_BOUNDS";
              Feature[Feature["LINE_WIDTH"] = 25] = "LINE_WIDTH";
              Feature[Feature["STENCIL_WRITE_MASK"] = 26] = "STENCIL_WRITE_MASK";
              Feature[Feature["STENCIL_COMPARE_MASK"] = 27] = "STENCIL_COMPARE_MASK";
              Feature[Feature["MULTITHREADED_SUBMISSION"] = 28] = "MULTITHREADED_SUBMISSION";
              Feature[Feature["COMPUTE_SHADER"] = 29] = "COMPUTE_SHADER";
              Feature[Feature["COUNT"] = 30] = "COUNT";
            })(Feature || (Feature = {}));

            var Format;

            (function (Format) {
              Format[Format["UNKNOWN"] = 0] = "UNKNOWN";
              Format[Format["A8"] = 1] = "A8";
              Format[Format["L8"] = 2] = "L8";
              Format[Format["LA8"] = 3] = "LA8";
              Format[Format["R8"] = 4] = "R8";
              Format[Format["R8SN"] = 5] = "R8SN";
              Format[Format["R8UI"] = 6] = "R8UI";
              Format[Format["R8I"] = 7] = "R8I";
              Format[Format["R16F"] = 8] = "R16F";
              Format[Format["R16UI"] = 9] = "R16UI";
              Format[Format["R16I"] = 10] = "R16I";
              Format[Format["R32F"] = 11] = "R32F";
              Format[Format["R32UI"] = 12] = "R32UI";
              Format[Format["R32I"] = 13] = "R32I";
              Format[Format["RG8"] = 14] = "RG8";
              Format[Format["RG8SN"] = 15] = "RG8SN";
              Format[Format["RG8UI"] = 16] = "RG8UI";
              Format[Format["RG8I"] = 17] = "RG8I";
              Format[Format["RG16F"] = 18] = "RG16F";
              Format[Format["RG16UI"] = 19] = "RG16UI";
              Format[Format["RG16I"] = 20] = "RG16I";
              Format[Format["RG32F"] = 21] = "RG32F";
              Format[Format["RG32UI"] = 22] = "RG32UI";
              Format[Format["RG32I"] = 23] = "RG32I";
              Format[Format["RGB8"] = 24] = "RGB8";
              Format[Format["SRGB8"] = 25] = "SRGB8";
              Format[Format["RGB8SN"] = 26] = "RGB8SN";
              Format[Format["RGB8UI"] = 27] = "RGB8UI";
              Format[Format["RGB8I"] = 28] = "RGB8I";
              Format[Format["RGB16F"] = 29] = "RGB16F";
              Format[Format["RGB16UI"] = 30] = "RGB16UI";
              Format[Format["RGB16I"] = 31] = "RGB16I";
              Format[Format["RGB32F"] = 32] = "RGB32F";
              Format[Format["RGB32UI"] = 33] = "RGB32UI";
              Format[Format["RGB32I"] = 34] = "RGB32I";
              Format[Format["RGBA8"] = 35] = "RGBA8";
              Format[Format["BGRA8"] = 36] = "BGRA8";
              Format[Format["SRGB8_A8"] = 37] = "SRGB8_A8";
              Format[Format["RGBA8SN"] = 38] = "RGBA8SN";
              Format[Format["RGBA8UI"] = 39] = "RGBA8UI";
              Format[Format["RGBA8I"] = 40] = "RGBA8I";
              Format[Format["RGBA16F"] = 41] = "RGBA16F";
              Format[Format["RGBA16UI"] = 42] = "RGBA16UI";
              Format[Format["RGBA16I"] = 43] = "RGBA16I";
              Format[Format["RGBA32F"] = 44] = "RGBA32F";
              Format[Format["RGBA32UI"] = 45] = "RGBA32UI";
              Format[Format["RGBA32I"] = 46] = "RGBA32I";
              Format[Format["R5G6B5"] = 47] = "R5G6B5";
              Format[Format["R11G11B10F"] = 48] = "R11G11B10F";
              Format[Format["RGB5A1"] = 49] = "RGB5A1";
              Format[Format["RGBA4"] = 50] = "RGBA4";
              Format[Format["RGB10A2"] = 51] = "RGB10A2";
              Format[Format["RGB10A2UI"] = 52] = "RGB10A2UI";
              Format[Format["RGB9E5"] = 53] = "RGB9E5";
              Format[Format["D16"] = 54] = "D16";
              Format[Format["D16S8"] = 55] = "D16S8";
              Format[Format["D24"] = 56] = "D24";
              Format[Format["D24S8"] = 57] = "D24S8";
              Format[Format["D32F"] = 58] = "D32F";
              Format[Format["D32F_S8"] = 59] = "D32F_S8";
              Format[Format["BC1"] = 60] = "BC1";
              Format[Format["BC1_ALPHA"] = 61] = "BC1_ALPHA";
              Format[Format["BC1_SRGB"] = 62] = "BC1_SRGB";
              Format[Format["BC1_SRGB_ALPHA"] = 63] = "BC1_SRGB_ALPHA";
              Format[Format["BC2"] = 64] = "BC2";
              Format[Format["BC2_SRGB"] = 65] = "BC2_SRGB";
              Format[Format["BC3"] = 66] = "BC3";
              Format[Format["BC3_SRGB"] = 67] = "BC3_SRGB";
              Format[Format["BC4"] = 68] = "BC4";
              Format[Format["BC4_SNORM"] = 69] = "BC4_SNORM";
              Format[Format["BC5"] = 70] = "BC5";
              Format[Format["BC5_SNORM"] = 71] = "BC5_SNORM";
              Format[Format["BC6H_UF16"] = 72] = "BC6H_UF16";
              Format[Format["BC6H_SF16"] = 73] = "BC6H_SF16";
              Format[Format["BC7"] = 74] = "BC7";
              Format[Format["BC7_SRGB"] = 75] = "BC7_SRGB";
              Format[Format["ETC_RGB8"] = 76] = "ETC_RGB8";
              Format[Format["ETC2_RGB8"] = 77] = "ETC2_RGB8";
              Format[Format["ETC2_SRGB8"] = 78] = "ETC2_SRGB8";
              Format[Format["ETC2_RGB8_A1"] = 79] = "ETC2_RGB8_A1";
              Format[Format["ETC2_SRGB8_A1"] = 80] = "ETC2_SRGB8_A1";
              Format[Format["ETC2_RGBA8"] = 81] = "ETC2_RGBA8";
              Format[Format["ETC2_SRGB8_A8"] = 82] = "ETC2_SRGB8_A8";
              Format[Format["EAC_R11"] = 83] = "EAC_R11";
              Format[Format["EAC_R11SN"] = 84] = "EAC_R11SN";
              Format[Format["EAC_RG11"] = 85] = "EAC_RG11";
              Format[Format["EAC_RG11SN"] = 86] = "EAC_RG11SN";
              Format[Format["PVRTC_RGB2"] = 87] = "PVRTC_RGB2";
              Format[Format["PVRTC_RGBA2"] = 88] = "PVRTC_RGBA2";
              Format[Format["PVRTC_RGB4"] = 89] = "PVRTC_RGB4";
              Format[Format["PVRTC_RGBA4"] = 90] = "PVRTC_RGBA4";
              Format[Format["PVRTC2_2BPP"] = 91] = "PVRTC2_2BPP";
              Format[Format["PVRTC2_4BPP"] = 92] = "PVRTC2_4BPP";
              Format[Format["ASTC_RGBA_4x4"] = 93] = "ASTC_RGBA_4x4";
              Format[Format["ASTC_RGBA_5x4"] = 94] = "ASTC_RGBA_5x4";
              Format[Format["ASTC_RGBA_5x5"] = 95] = "ASTC_RGBA_5x5";
              Format[Format["ASTC_RGBA_6x5"] = 96] = "ASTC_RGBA_6x5";
              Format[Format["ASTC_RGBA_6x6"] = 97] = "ASTC_RGBA_6x6";
              Format[Format["ASTC_RGBA_8x5"] = 98] = "ASTC_RGBA_8x5";
              Format[Format["ASTC_RGBA_8x6"] = 99] = "ASTC_RGBA_8x6";
              Format[Format["ASTC_RGBA_8x8"] = 100] = "ASTC_RGBA_8x8";
              Format[Format["ASTC_RGBA_10x5"] = 101] = "ASTC_RGBA_10x5";
              Format[Format["ASTC_RGBA_10x6"] = 102] = "ASTC_RGBA_10x6";
              Format[Format["ASTC_RGBA_10x8"] = 103] = "ASTC_RGBA_10x8";
              Format[Format["ASTC_RGBA_10x10"] = 104] = "ASTC_RGBA_10x10";
              Format[Format["ASTC_RGBA_12x10"] = 105] = "ASTC_RGBA_12x10";
              Format[Format["ASTC_RGBA_12x12"] = 106] = "ASTC_RGBA_12x12";
              Format[Format["ASTC_SRGBA_4x4"] = 107] = "ASTC_SRGBA_4x4";
              Format[Format["ASTC_SRGBA_5x4"] = 108] = "ASTC_SRGBA_5x4";
              Format[Format["ASTC_SRGBA_5x5"] = 109] = "ASTC_SRGBA_5x5";
              Format[Format["ASTC_SRGBA_6x5"] = 110] = "ASTC_SRGBA_6x5";
              Format[Format["ASTC_SRGBA_6x6"] = 111] = "ASTC_SRGBA_6x6";
              Format[Format["ASTC_SRGBA_8x5"] = 112] = "ASTC_SRGBA_8x5";
              Format[Format["ASTC_SRGBA_8x6"] = 113] = "ASTC_SRGBA_8x6";
              Format[Format["ASTC_SRGBA_8x8"] = 114] = "ASTC_SRGBA_8x8";
              Format[Format["ASTC_SRGBA_10x5"] = 115] = "ASTC_SRGBA_10x5";
              Format[Format["ASTC_SRGBA_10x6"] = 116] = "ASTC_SRGBA_10x6";
              Format[Format["ASTC_SRGBA_10x8"] = 117] = "ASTC_SRGBA_10x8";
              Format[Format["ASTC_SRGBA_10x10"] = 118] = "ASTC_SRGBA_10x10";
              Format[Format["ASTC_SRGBA_12x10"] = 119] = "ASTC_SRGBA_12x10";
              Format[Format["ASTC_SRGBA_12x12"] = 120] = "ASTC_SRGBA_12x12";
              Format[Format["COUNT"] = 121] = "COUNT";
            })(Format || (Format = {}));

            var FormatType;

            (function (FormatType) {
              FormatType[FormatType["NONE"] = 0] = "NONE";
              FormatType[FormatType["UNORM"] = 1] = "UNORM";
              FormatType[FormatType["SNORM"] = 2] = "SNORM";
              FormatType[FormatType["UINT"] = 3] = "UINT";
              FormatType[FormatType["INT"] = 4] = "INT";
              FormatType[FormatType["UFLOAT"] = 5] = "UFLOAT";
              FormatType[FormatType["FLOAT"] = 6] = "FLOAT";
            })(FormatType || (FormatType = {}));

            var Type;

            (function (Type) {
              Type[Type["UNKNOWN"] = 0] = "UNKNOWN";
              Type[Type["BOOL"] = 1] = "BOOL";
              Type[Type["BOOL2"] = 2] = "BOOL2";
              Type[Type["BOOL3"] = 3] = "BOOL3";
              Type[Type["BOOL4"] = 4] = "BOOL4";
              Type[Type["INT"] = 5] = "INT";
              Type[Type["INT2"] = 6] = "INT2";
              Type[Type["INT3"] = 7] = "INT3";
              Type[Type["INT4"] = 8] = "INT4";
              Type[Type["UINT"] = 9] = "UINT";
              Type[Type["UINT2"] = 10] = "UINT2";
              Type[Type["UINT3"] = 11] = "UINT3";
              Type[Type["UINT4"] = 12] = "UINT4";
              Type[Type["FLOAT"] = 13] = "FLOAT";
              Type[Type["FLOAT2"] = 14] = "FLOAT2";
              Type[Type["FLOAT3"] = 15] = "FLOAT3";
              Type[Type["FLOAT4"] = 16] = "FLOAT4";
              Type[Type["MAT2"] = 17] = "MAT2";
              Type[Type["MAT2X3"] = 18] = "MAT2X3";
              Type[Type["MAT2X4"] = 19] = "MAT2X4";
              Type[Type["MAT3X2"] = 20] = "MAT3X2";
              Type[Type["MAT3"] = 21] = "MAT3";
              Type[Type["MAT3X4"] = 22] = "MAT3X4";
              Type[Type["MAT4X2"] = 23] = "MAT4X2";
              Type[Type["MAT4X3"] = 24] = "MAT4X3";
              Type[Type["MAT4"] = 25] = "MAT4";
              Type[Type["SAMPLER1D"] = 26] = "SAMPLER1D";
              Type[Type["SAMPLER1D_ARRAY"] = 27] = "SAMPLER1D_ARRAY";
              Type[Type["SAMPLER2D"] = 28] = "SAMPLER2D";
              Type[Type["SAMPLER2D_ARRAY"] = 29] = "SAMPLER2D_ARRAY";
              Type[Type["SAMPLER3D"] = 30] = "SAMPLER3D";
              Type[Type["SAMPLER_CUBE"] = 31] = "SAMPLER_CUBE";
              Type[Type["SAMPLER"] = 32] = "SAMPLER";
              Type[Type["TEXTURE1D"] = 33] = "TEXTURE1D";
              Type[Type["TEXTURE1D_ARRAY"] = 34] = "TEXTURE1D_ARRAY";
              Type[Type["TEXTURE2D"] = 35] = "TEXTURE2D";
              Type[Type["TEXTURE2D_ARRAY"] = 36] = "TEXTURE2D_ARRAY";
              Type[Type["TEXTURE3D"] = 37] = "TEXTURE3D";
              Type[Type["TEXTURE_CUBE"] = 38] = "TEXTURE_CUBE";
              Type[Type["IMAGE1D"] = 39] = "IMAGE1D";
              Type[Type["IMAGE1D_ARRAY"] = 40] = "IMAGE1D_ARRAY";
              Type[Type["IMAGE2D"] = 41] = "IMAGE2D";
              Type[Type["IMAGE2D_ARRAY"] = 42] = "IMAGE2D_ARRAY";
              Type[Type["IMAGE3D"] = 43] = "IMAGE3D";
              Type[Type["IMAGE_CUBE"] = 44] = "IMAGE_CUBE";
              Type[Type["SUBPASS_INPUT"] = 45] = "SUBPASS_INPUT";
              Type[Type["COUNT"] = 46] = "COUNT";
            })(Type || (Type = {}));

            var BufferUsageBit;

            (function (BufferUsageBit) {
              BufferUsageBit[BufferUsageBit["NONE"] = 0] = "NONE";
              BufferUsageBit[BufferUsageBit["TRANSFER_SRC"] = 1] = "TRANSFER_SRC";
              BufferUsageBit[BufferUsageBit["TRANSFER_DST"] = 2] = "TRANSFER_DST";
              BufferUsageBit[BufferUsageBit["INDEX"] = 4] = "INDEX";
              BufferUsageBit[BufferUsageBit["VERTEX"] = 8] = "VERTEX";
              BufferUsageBit[BufferUsageBit["UNIFORM"] = 16] = "UNIFORM";
              BufferUsageBit[BufferUsageBit["STORAGE"] = 32] = "STORAGE";
              BufferUsageBit[BufferUsageBit["INDIRECT"] = 64] = "INDIRECT";
            })(BufferUsageBit || (BufferUsageBit = {}));

            var BufferFlagBit;

            (function (BufferFlagBit) {
              BufferFlagBit[BufferFlagBit["NONE"] = 0] = "NONE";
            })(BufferFlagBit || (BufferFlagBit = {}));

            var MemoryAccessBit;

            (function (MemoryAccessBit) {
              MemoryAccessBit[MemoryAccessBit["NONE"] = 0] = "NONE";
              MemoryAccessBit[MemoryAccessBit["READ_ONLY"] = 1] = "READ_ONLY";
              MemoryAccessBit[MemoryAccessBit["WRITE_ONLY"] = 2] = "WRITE_ONLY";
              MemoryAccessBit[MemoryAccessBit["READ_WRITE"] = 3] = "READ_WRITE";
            })(MemoryAccessBit || (MemoryAccessBit = {}));

            var MemoryUsageBit;

            (function (MemoryUsageBit) {
              MemoryUsageBit[MemoryUsageBit["NONE"] = 0] = "NONE";
              MemoryUsageBit[MemoryUsageBit["DEVICE"] = 1] = "DEVICE";
              MemoryUsageBit[MemoryUsageBit["HOST"] = 2] = "HOST";
            })(MemoryUsageBit || (MemoryUsageBit = {}));

            var TextureType;

            (function (TextureType) {
              TextureType[TextureType["TEX1D"] = 0] = "TEX1D";
              TextureType[TextureType["TEX2D"] = 1] = "TEX2D";
              TextureType[TextureType["TEX3D"] = 2] = "TEX3D";
              TextureType[TextureType["CUBE"] = 3] = "CUBE";
              TextureType[TextureType["TEX1D_ARRAY"] = 4] = "TEX1D_ARRAY";
              TextureType[TextureType["TEX2D_ARRAY"] = 5] = "TEX2D_ARRAY";
            })(TextureType || (TextureType = {}));

            var TextureUsageBit;

            (function (TextureUsageBit) {
              TextureUsageBit[TextureUsageBit["NONE"] = 0] = "NONE";
              TextureUsageBit[TextureUsageBit["TRANSFER_SRC"] = 1] = "TRANSFER_SRC";
              TextureUsageBit[TextureUsageBit["TRANSFER_DST"] = 2] = "TRANSFER_DST";
              TextureUsageBit[TextureUsageBit["SAMPLED"] = 4] = "SAMPLED";
              TextureUsageBit[TextureUsageBit["STORAGE"] = 8] = "STORAGE";
              TextureUsageBit[TextureUsageBit["COLOR_ATTACHMENT"] = 16] = "COLOR_ATTACHMENT";
              TextureUsageBit[TextureUsageBit["DEPTH_STENCIL_ATTACHMENT"] = 32] = "DEPTH_STENCIL_ATTACHMENT";
              TextureUsageBit[TextureUsageBit["TRANSIENT_ATTACHMENT"] = 64] = "TRANSIENT_ATTACHMENT";
              TextureUsageBit[TextureUsageBit["INPUT_ATTACHMENT"] = 128] = "INPUT_ATTACHMENT";
            })(TextureUsageBit || (TextureUsageBit = {}));

            var TextureFlagBit;

            (function (TextureFlagBit) {
              TextureFlagBit[TextureFlagBit["NONE"] = 0] = "NONE";
              TextureFlagBit[TextureFlagBit["GEN_MIPMAP"] = 1] = "GEN_MIPMAP";
              TextureFlagBit[TextureFlagBit["IMMUTABLE"] = 2] = "IMMUTABLE";
            })(TextureFlagBit || (TextureFlagBit = {}));

            var SampleCount;

            (function (SampleCount) {
              SampleCount[SampleCount["X1"] = 0] = "X1";
              SampleCount[SampleCount["X2"] = 1] = "X2";
              SampleCount[SampleCount["X4"] = 2] = "X4";
              SampleCount[SampleCount["X8"] = 3] = "X8";
              SampleCount[SampleCount["X16"] = 4] = "X16";
              SampleCount[SampleCount["X32"] = 5] = "X32";
              SampleCount[SampleCount["X64"] = 6] = "X64";
            })(SampleCount || (SampleCount = {}));

            var Filter;

            (function (Filter) {
              Filter[Filter["NONE"] = 0] = "NONE";
              Filter[Filter["POINT"] = 1] = "POINT";
              Filter[Filter["LINEAR"] = 2] = "LINEAR";
              Filter[Filter["ANISOTROPIC"] = 3] = "ANISOTROPIC";
            })(Filter || (Filter = {}));

            var Address;

            (function (Address) {
              Address[Address["WRAP"] = 0] = "WRAP";
              Address[Address["MIRROR"] = 1] = "MIRROR";
              Address[Address["CLAMP"] = 2] = "CLAMP";
              Address[Address["BORDER"] = 3] = "BORDER";
            })(Address || (Address = {}));

            var ComparisonFunc;

            (function (ComparisonFunc) {
              ComparisonFunc[ComparisonFunc["NEVER"] = 0] = "NEVER";
              ComparisonFunc[ComparisonFunc["LESS"] = 1] = "LESS";
              ComparisonFunc[ComparisonFunc["EQUAL"] = 2] = "EQUAL";
              ComparisonFunc[ComparisonFunc["LESS_EQUAL"] = 3] = "LESS_EQUAL";
              ComparisonFunc[ComparisonFunc["GREATER"] = 4] = "GREATER";
              ComparisonFunc[ComparisonFunc["NOT_EQUAL"] = 5] = "NOT_EQUAL";
              ComparisonFunc[ComparisonFunc["GREATER_EQUAL"] = 6] = "GREATER_EQUAL";
              ComparisonFunc[ComparisonFunc["ALWAYS"] = 7] = "ALWAYS";
            })(ComparisonFunc || (ComparisonFunc = {}));

            var StencilOp;

            (function (StencilOp) {
              StencilOp[StencilOp["ZERO"] = 0] = "ZERO";
              StencilOp[StencilOp["KEEP"] = 1] = "KEEP";
              StencilOp[StencilOp["REPLACE"] = 2] = "REPLACE";
              StencilOp[StencilOp["INCR"] = 3] = "INCR";
              StencilOp[StencilOp["DECR"] = 4] = "DECR";
              StencilOp[StencilOp["INVERT"] = 5] = "INVERT";
              StencilOp[StencilOp["INCR_WRAP"] = 6] = "INCR_WRAP";
              StencilOp[StencilOp["DECR_WRAP"] = 7] = "DECR_WRAP";
            })(StencilOp || (StencilOp = {}));

            var BlendFactor;

            (function (BlendFactor) {
              BlendFactor[BlendFactor["ZERO"] = 0] = "ZERO";
              BlendFactor[BlendFactor["ONE"] = 1] = "ONE";
              BlendFactor[BlendFactor["SRC_ALPHA"] = 2] = "SRC_ALPHA";
              BlendFactor[BlendFactor["DST_ALPHA"] = 3] = "DST_ALPHA";
              BlendFactor[BlendFactor["ONE_MINUS_SRC_ALPHA"] = 4] = "ONE_MINUS_SRC_ALPHA";
              BlendFactor[BlendFactor["ONE_MINUS_DST_ALPHA"] = 5] = "ONE_MINUS_DST_ALPHA";
              BlendFactor[BlendFactor["SRC_COLOR"] = 6] = "SRC_COLOR";
              BlendFactor[BlendFactor["DST_COLOR"] = 7] = "DST_COLOR";
              BlendFactor[BlendFactor["ONE_MINUS_SRC_COLOR"] = 8] = "ONE_MINUS_SRC_COLOR";
              BlendFactor[BlendFactor["ONE_MINUS_DST_COLOR"] = 9] = "ONE_MINUS_DST_COLOR";
              BlendFactor[BlendFactor["SRC_ALPHA_SATURATE"] = 10] = "SRC_ALPHA_SATURATE";
              BlendFactor[BlendFactor["CONSTANT_COLOR"] = 11] = "CONSTANT_COLOR";
              BlendFactor[BlendFactor["ONE_MINUS_CONSTANT_COLOR"] = 12] = "ONE_MINUS_CONSTANT_COLOR";
              BlendFactor[BlendFactor["CONSTANT_ALPHA"] = 13] = "CONSTANT_ALPHA";
              BlendFactor[BlendFactor["ONE_MINUS_CONSTANT_ALPHA"] = 14] = "ONE_MINUS_CONSTANT_ALPHA";
            })(BlendFactor || (BlendFactor = {}));

            var BlendOp;

            (function (BlendOp) {
              BlendOp[BlendOp["ADD"] = 0] = "ADD";
              BlendOp[BlendOp["SUB"] = 1] = "SUB";
              BlendOp[BlendOp["REV_SUB"] = 2] = "REV_SUB";
              BlendOp[BlendOp["MIN"] = 3] = "MIN";
              BlendOp[BlendOp["MAX"] = 4] = "MAX";
            })(BlendOp || (BlendOp = {}));

            var ColorMask;

            (function (ColorMask) {
              ColorMask[ColorMask["NONE"] = 0] = "NONE";
              ColorMask[ColorMask["R"] = 1] = "R";
              ColorMask[ColorMask["G"] = 2] = "G";
              ColorMask[ColorMask["B"] = 4] = "B";
              ColorMask[ColorMask["A"] = 8] = "A";
              ColorMask[ColorMask["ALL"] = 15] = "ALL";
            })(ColorMask || (ColorMask = {}));

            var ShaderStageFlagBit;

            (function (ShaderStageFlagBit) {
              ShaderStageFlagBit[ShaderStageFlagBit["NONE"] = 0] = "NONE";
              ShaderStageFlagBit[ShaderStageFlagBit["VERTEX"] = 1] = "VERTEX";
              ShaderStageFlagBit[ShaderStageFlagBit["CONTROL"] = 2] = "CONTROL";
              ShaderStageFlagBit[ShaderStageFlagBit["EVALUATION"] = 4] = "EVALUATION";
              ShaderStageFlagBit[ShaderStageFlagBit["GEOMETRY"] = 8] = "GEOMETRY";
              ShaderStageFlagBit[ShaderStageFlagBit["FRAGMENT"] = 16] = "FRAGMENT";
              ShaderStageFlagBit[ShaderStageFlagBit["COMPUTE"] = 32] = "COMPUTE";
              ShaderStageFlagBit[ShaderStageFlagBit["ALL"] = 63] = "ALL";
            })(ShaderStageFlagBit || (ShaderStageFlagBit = {}));

            var LoadOp;

            (function (LoadOp) {
              LoadOp[LoadOp["LOAD"] = 0] = "LOAD";
              LoadOp[LoadOp["CLEAR"] = 1] = "CLEAR";
              LoadOp[LoadOp["DISCARD"] = 2] = "DISCARD";
            })(LoadOp || (LoadOp = {}));

            var StoreOp;

            (function (StoreOp) {
              StoreOp[StoreOp["STORE"] = 0] = "STORE";
              StoreOp[StoreOp["DISCARD"] = 1] = "DISCARD";
            })(StoreOp || (StoreOp = {}));

            var AccessType;

            (function (AccessType) {
              AccessType[AccessType["NONE"] = 0] = "NONE";
              AccessType[AccessType["INDIRECT_BUFFER"] = 1] = "INDIRECT_BUFFER";
              AccessType[AccessType["INDEX_BUFFER"] = 2] = "INDEX_BUFFER";
              AccessType[AccessType["VERTEX_BUFFER"] = 3] = "VERTEX_BUFFER";
              AccessType[AccessType["VERTEX_SHADER_READ_UNIFORM_BUFFER"] = 4] = "VERTEX_SHADER_READ_UNIFORM_BUFFER";
              AccessType[AccessType["VERTEX_SHADER_READ_TEXTURE"] = 5] = "VERTEX_SHADER_READ_TEXTURE";
              AccessType[AccessType["VERTEX_SHADER_READ_OTHER"] = 6] = "VERTEX_SHADER_READ_OTHER";
              AccessType[AccessType["FRAGMENT_SHADER_READ_UNIFORM_BUFFER"] = 7] = "FRAGMENT_SHADER_READ_UNIFORM_BUFFER";
              AccessType[AccessType["FRAGMENT_SHADER_READ_TEXTURE"] = 8] = "FRAGMENT_SHADER_READ_TEXTURE";
              AccessType[AccessType["FRAGMENT_SHADER_READ_COLOR_INPUT_ATTACHMENT"] = 9] = "FRAGMENT_SHADER_READ_COLOR_INPUT_ATTACHMENT";
              AccessType[AccessType["FRAGMENT_SHADER_READ_DEPTH_STENCIL_INPUT_ATTACHMENT"] = 10] = "FRAGMENT_SHADER_READ_DEPTH_STENCIL_INPUT_ATTACHMENT";
              AccessType[AccessType["FRAGMENT_SHADER_READ_OTHER"] = 11] = "FRAGMENT_SHADER_READ_OTHER";
              AccessType[AccessType["COLOR_ATTACHMENT_READ"] = 12] = "COLOR_ATTACHMENT_READ";
              AccessType[AccessType["DEPTH_STENCIL_ATTACHMENT_READ"] = 13] = "DEPTH_STENCIL_ATTACHMENT_READ";
              AccessType[AccessType["COMPUTE_SHADER_READ_UNIFORM_BUFFER"] = 14] = "COMPUTE_SHADER_READ_UNIFORM_BUFFER";
              AccessType[AccessType["COMPUTE_SHADER_READ_TEXTURE"] = 15] = "COMPUTE_SHADER_READ_TEXTURE";
              AccessType[AccessType["COMPUTE_SHADER_READ_OTHER"] = 16] = "COMPUTE_SHADER_READ_OTHER";
              AccessType[AccessType["TRANSFER_READ"] = 17] = "TRANSFER_READ";
              AccessType[AccessType["HOST_READ"] = 18] = "HOST_READ";
              AccessType[AccessType["PRESENT"] = 19] = "PRESENT";
              AccessType[AccessType["VERTEX_SHADER_WRITE"] = 20] = "VERTEX_SHADER_WRITE";
              AccessType[AccessType["FRAGMENT_SHADER_WRITE"] = 21] = "FRAGMENT_SHADER_WRITE";
              AccessType[AccessType["COLOR_ATTACHMENT_WRITE"] = 22] = "COLOR_ATTACHMENT_WRITE";
              AccessType[AccessType["DEPTH_STENCIL_ATTACHMENT_WRITE"] = 23] = "DEPTH_STENCIL_ATTACHMENT_WRITE";
              AccessType[AccessType["COMPUTE_SHADER_WRITE"] = 24] = "COMPUTE_SHADER_WRITE";
              AccessType[AccessType["TRANSFER_WRITE"] = 25] = "TRANSFER_WRITE";
              AccessType[AccessType["HOST_PREINITIALIZED"] = 26] = "HOST_PREINITIALIZED";
              AccessType[AccessType["HOST_WRITE"] = 27] = "HOST_WRITE";
            })(AccessType || (AccessType = {}));

            var PipelineBindPoint;

            (function (PipelineBindPoint) {
              PipelineBindPoint[PipelineBindPoint["GRAPHICS"] = 0] = "GRAPHICS";
              PipelineBindPoint[PipelineBindPoint["COMPUTE"] = 1] = "COMPUTE";
              PipelineBindPoint[PipelineBindPoint["RAY_TRACING"] = 2] = "RAY_TRACING";
            })(PipelineBindPoint || (PipelineBindPoint = {}));

            var PrimitiveMode;

            (function (PrimitiveMode) {
              PrimitiveMode[PrimitiveMode["POINT_LIST"] = 0] = "POINT_LIST";
              PrimitiveMode[PrimitiveMode["LINE_LIST"] = 1] = "LINE_LIST";
              PrimitiveMode[PrimitiveMode["LINE_STRIP"] = 2] = "LINE_STRIP";
              PrimitiveMode[PrimitiveMode["LINE_LOOP"] = 3] = "LINE_LOOP";
              PrimitiveMode[PrimitiveMode["LINE_LIST_ADJACENCY"] = 4] = "LINE_LIST_ADJACENCY";
              PrimitiveMode[PrimitiveMode["LINE_STRIP_ADJACENCY"] = 5] = "LINE_STRIP_ADJACENCY";
              PrimitiveMode[PrimitiveMode["ISO_LINE_LIST"] = 6] = "ISO_LINE_LIST";
              PrimitiveMode[PrimitiveMode["TRIANGLE_LIST"] = 7] = "TRIANGLE_LIST";
              PrimitiveMode[PrimitiveMode["TRIANGLE_STRIP"] = 8] = "TRIANGLE_STRIP";
              PrimitiveMode[PrimitiveMode["TRIANGLE_FAN"] = 9] = "TRIANGLE_FAN";
              PrimitiveMode[PrimitiveMode["TRIANGLE_LIST_ADJACENCY"] = 10] = "TRIANGLE_LIST_ADJACENCY";
              PrimitiveMode[PrimitiveMode["TRIANGLE_STRIP_ADJACENCY"] = 11] = "TRIANGLE_STRIP_ADJACENCY";
              PrimitiveMode[PrimitiveMode["TRIANGLE_PATCH_ADJACENCY"] = 12] = "TRIANGLE_PATCH_ADJACENCY";
              PrimitiveMode[PrimitiveMode["QUAD_PATCH_LIST"] = 13] = "QUAD_PATCH_LIST";
            })(PrimitiveMode || (PrimitiveMode = {}));

            var PolygonMode;

            (function (PolygonMode) {
              PolygonMode[PolygonMode["FILL"] = 0] = "FILL";
              PolygonMode[PolygonMode["POINT"] = 1] = "POINT";
              PolygonMode[PolygonMode["LINE"] = 2] = "LINE";
            })(PolygonMode || (PolygonMode = {}));

            var ShadeModel;

            (function (ShadeModel) {
              ShadeModel[ShadeModel["GOURAND"] = 0] = "GOURAND";
              ShadeModel[ShadeModel["FLAT"] = 1] = "FLAT";
            })(ShadeModel || (ShadeModel = {}));

            var CullMode;

            (function (CullMode) {
              CullMode[CullMode["NONE"] = 0] = "NONE";
              CullMode[CullMode["FRONT"] = 1] = "FRONT";
              CullMode[CullMode["BACK"] = 2] = "BACK";
            })(CullMode || (CullMode = {}));

            var DynamicStateFlagBit;

            (function (DynamicStateFlagBit) {
              DynamicStateFlagBit[DynamicStateFlagBit["NONE"] = 0] = "NONE";
              DynamicStateFlagBit[DynamicStateFlagBit["VIEWPORT"] = 1] = "VIEWPORT";
              DynamicStateFlagBit[DynamicStateFlagBit["SCISSOR"] = 2] = "SCISSOR";
              DynamicStateFlagBit[DynamicStateFlagBit["LINE_WIDTH"] = 4] = "LINE_WIDTH";
              DynamicStateFlagBit[DynamicStateFlagBit["DEPTH_BIAS"] = 8] = "DEPTH_BIAS";
              DynamicStateFlagBit[DynamicStateFlagBit["BLEND_CONSTANTS"] = 16] = "BLEND_CONSTANTS";
              DynamicStateFlagBit[DynamicStateFlagBit["DEPTH_BOUNDS"] = 32] = "DEPTH_BOUNDS";
              DynamicStateFlagBit[DynamicStateFlagBit["STENCIL_WRITE_MASK"] = 64] = "STENCIL_WRITE_MASK";
              DynamicStateFlagBit[DynamicStateFlagBit["STENCIL_COMPARE_MASK"] = 128] = "STENCIL_COMPARE_MASK";
            })(DynamicStateFlagBit || (DynamicStateFlagBit = {}));

            var StencilFace;

            (function (StencilFace) {
              StencilFace[StencilFace["FRONT"] = 1] = "FRONT";
              StencilFace[StencilFace["BACK"] = 2] = "BACK";
              StencilFace[StencilFace["ALL"] = 3] = "ALL";
            })(StencilFace || (StencilFace = {}));

            var DescriptorType;

            (function (DescriptorType) {
              DescriptorType[DescriptorType["UNKNOWN"] = 0] = "UNKNOWN";
              DescriptorType[DescriptorType["UNIFORM_BUFFER"] = 1] = "UNIFORM_BUFFER";
              DescriptorType[DescriptorType["DYNAMIC_UNIFORM_BUFFER"] = 2] = "DYNAMIC_UNIFORM_BUFFER";
              DescriptorType[DescriptorType["STORAGE_BUFFER"] = 4] = "STORAGE_BUFFER";
              DescriptorType[DescriptorType["DYNAMIC_STORAGE_BUFFER"] = 8] = "DYNAMIC_STORAGE_BUFFER";
              DescriptorType[DescriptorType["SAMPLER_TEXTURE"] = 16] = "SAMPLER_TEXTURE";
              DescriptorType[DescriptorType["SAMPLER"] = 32] = "SAMPLER";
              DescriptorType[DescriptorType["TEXTURE"] = 64] = "TEXTURE";
              DescriptorType[DescriptorType["STORAGE_IMAGE"] = 128] = "STORAGE_IMAGE";
              DescriptorType[DescriptorType["INPUT_ATTACHMENT"] = 256] = "INPUT_ATTACHMENT";
            })(DescriptorType || (DescriptorType = {}));

            var QueueType;

            (function (QueueType) {
              QueueType[QueueType["GRAPHICS"] = 0] = "GRAPHICS";
              QueueType[QueueType["COMPUTE"] = 1] = "COMPUTE";
              QueueType[QueueType["TRANSFER"] = 2] = "TRANSFER";
            })(QueueType || (QueueType = {}));

            var CommandBufferType;

            (function (CommandBufferType) {
              CommandBufferType[CommandBufferType["PRIMARY"] = 0] = "PRIMARY";
              CommandBufferType[CommandBufferType["SECONDARY"] = 1] = "SECONDARY";
            })(CommandBufferType || (CommandBufferType = {}));

            var ClearFlagBit;

            (function (ClearFlagBit) {
              ClearFlagBit[ClearFlagBit["NONE"] = 0] = "NONE";
              ClearFlagBit[ClearFlagBit["COLOR"] = 1] = "COLOR";
              ClearFlagBit[ClearFlagBit["DEPTH"] = 2] = "DEPTH";
              ClearFlagBit[ClearFlagBit["STENCIL"] = 4] = "STENCIL";
              ClearFlagBit[ClearFlagBit["DEPTH_STENCIL"] = 6] = "DEPTH_STENCIL";
              ClearFlagBit[ClearFlagBit["ALL"] = 7] = "ALL";
            })(ClearFlagBit || (ClearFlagBit = {}));

            var Size$1 = function () {
              function Size(x, y, z) {
                if (x === void 0) {
                  x = 0;
                }

                if (y === void 0) {
                  y = 0;
                }

                if (z === void 0) {
                  z = 0;
                }

                this.x = x;
                this.y = y;
                this.z = z;
              }

              var _proto = Size.prototype;

              _proto.copy = function copy(info) {
                this.x = info.x;
                this.y = info.y;
                this.z = info.z;
                return this;
              };

              return Size;
            }();
            var DeviceCaps = function () {
              function DeviceCaps(maxVertexAttributes, maxVertexUniformVectors, maxFragmentUniformVectors, maxTextureUnits, maxImageUnits, maxVertexTextureUnits, maxColorRenderTargets, maxShaderStorageBufferBindings, maxShaderStorageBlockSize, maxUniformBufferBindings, maxUniformBlockSize, maxTextureSize, maxCubeMapTextureSize, depthBits, stencilBits, uboOffsetAlignment, maxComputeSharedMemorySize, maxComputeWorkGroupInvocations, maxComputeWorkGroupSize, maxComputeWorkGroupCount, clipSpaceMinZ, screenSpaceSignY, clipSpaceSignY) {
                if (maxVertexAttributes === void 0) {
                  maxVertexAttributes = 0;
                }

                if (maxVertexUniformVectors === void 0) {
                  maxVertexUniformVectors = 0;
                }

                if (maxFragmentUniformVectors === void 0) {
                  maxFragmentUniformVectors = 0;
                }

                if (maxTextureUnits === void 0) {
                  maxTextureUnits = 0;
                }

                if (maxImageUnits === void 0) {
                  maxImageUnits = 0;
                }

                if (maxVertexTextureUnits === void 0) {
                  maxVertexTextureUnits = 0;
                }

                if (maxColorRenderTargets === void 0) {
                  maxColorRenderTargets = 0;
                }

                if (maxShaderStorageBufferBindings === void 0) {
                  maxShaderStorageBufferBindings = 0;
                }

                if (maxShaderStorageBlockSize === void 0) {
                  maxShaderStorageBlockSize = 0;
                }

                if (maxUniformBufferBindings === void 0) {
                  maxUniformBufferBindings = 0;
                }

                if (maxUniformBlockSize === void 0) {
                  maxUniformBlockSize = 0;
                }

                if (maxTextureSize === void 0) {
                  maxTextureSize = 0;
                }

                if (maxCubeMapTextureSize === void 0) {
                  maxCubeMapTextureSize = 0;
                }

                if (depthBits === void 0) {
                  depthBits = 0;
                }

                if (stencilBits === void 0) {
                  stencilBits = 0;
                }

                if (uboOffsetAlignment === void 0) {
                  uboOffsetAlignment = 1;
                }

                if (maxComputeSharedMemorySize === void 0) {
                  maxComputeSharedMemorySize = 0;
                }

                if (maxComputeWorkGroupInvocations === void 0) {
                  maxComputeWorkGroupInvocations = 0;
                }

                if (maxComputeWorkGroupSize === void 0) {
                  maxComputeWorkGroupSize = new Size$1();
                }

                if (maxComputeWorkGroupCount === void 0) {
                  maxComputeWorkGroupCount = new Size$1();
                }

                if (clipSpaceMinZ === void 0) {
                  clipSpaceMinZ = -1;
                }

                if (screenSpaceSignY === void 0) {
                  screenSpaceSignY = 1;
                }

                if (clipSpaceSignY === void 0) {
                  clipSpaceSignY = 1;
                }

                this.maxVertexAttributes = maxVertexAttributes;
                this.maxVertexUniformVectors = maxVertexUniformVectors;
                this.maxFragmentUniformVectors = maxFragmentUniformVectors;
                this.maxTextureUnits = maxTextureUnits;
                this.maxImageUnits = maxImageUnits;
                this.maxVertexTextureUnits = maxVertexTextureUnits;
                this.maxColorRenderTargets = maxColorRenderTargets;
                this.maxShaderStorageBufferBindings = maxShaderStorageBufferBindings;
                this.maxShaderStorageBlockSize = maxShaderStorageBlockSize;
                this.maxUniformBufferBindings = maxUniformBufferBindings;
                this.maxUniformBlockSize = maxUniformBlockSize;
                this.maxTextureSize = maxTextureSize;
                this.maxCubeMapTextureSize = maxCubeMapTextureSize;
                this.depthBits = depthBits;
                this.stencilBits = stencilBits;
                this.uboOffsetAlignment = uboOffsetAlignment;
                this.maxComputeSharedMemorySize = maxComputeSharedMemorySize;
                this.maxComputeWorkGroupInvocations = maxComputeWorkGroupInvocations;
                this.maxComputeWorkGroupSize = maxComputeWorkGroupSize;
                this.maxComputeWorkGroupCount = maxComputeWorkGroupCount;
                this.clipSpaceMinZ = clipSpaceMinZ;
                this.screenSpaceSignY = screenSpaceSignY;
                this.clipSpaceSignY = clipSpaceSignY;
              }

              var _proto2 = DeviceCaps.prototype;

              _proto2.copy = function copy(info) {
                this.maxVertexAttributes = info.maxVertexAttributes;
                this.maxVertexUniformVectors = info.maxVertexUniformVectors;
                this.maxFragmentUniformVectors = info.maxFragmentUniformVectors;
                this.maxTextureUnits = info.maxTextureUnits;
                this.maxImageUnits = info.maxImageUnits;
                this.maxVertexTextureUnits = info.maxVertexTextureUnits;
                this.maxColorRenderTargets = info.maxColorRenderTargets;
                this.maxShaderStorageBufferBindings = info.maxShaderStorageBufferBindings;
                this.maxShaderStorageBlockSize = info.maxShaderStorageBlockSize;
                this.maxUniformBufferBindings = info.maxUniformBufferBindings;
                this.maxUniformBlockSize = info.maxUniformBlockSize;
                this.maxTextureSize = info.maxTextureSize;
                this.maxCubeMapTextureSize = info.maxCubeMapTextureSize;
                this.depthBits = info.depthBits;
                this.stencilBits = info.stencilBits;
                this.uboOffsetAlignment = info.uboOffsetAlignment;
                this.maxComputeSharedMemorySize = info.maxComputeSharedMemorySize;
                this.maxComputeWorkGroupInvocations = info.maxComputeWorkGroupInvocations;
                this.maxComputeWorkGroupSize.copy(info.maxComputeWorkGroupSize);
                this.maxComputeWorkGroupCount.copy(info.maxComputeWorkGroupCount);
                this.clipSpaceMinZ = info.clipSpaceMinZ;
                this.screenSpaceSignY = info.screenSpaceSignY;
                this.clipSpaceSignY = info.clipSpaceSignY;
                return this;
              };

              return DeviceCaps;
            }();
            var Offset = function () {
              function Offset(x, y, z) {
                if (x === void 0) {
                  x = 0;
                }

                if (y === void 0) {
                  y = 0;
                }

                if (z === void 0) {
                  z = 0;
                }

                this.x = x;
                this.y = y;
                this.z = z;
              }

              var _proto3 = Offset.prototype;

              _proto3.copy = function copy(info) {
                this.x = info.x;
                this.y = info.y;
                this.z = info.z;
                return this;
              };

              return Offset;
            }();
            var Rect$1 = function () {
              function Rect(x, y, width, height) {
                if (x === void 0) {
                  x = 0;
                }

                if (y === void 0) {
                  y = 0;
                }

                if (width === void 0) {
                  width = 0;
                }

                if (height === void 0) {
                  height = 0;
                }

                this.x = x;
                this.y = y;
                this.width = width;
                this.height = height;
              }

              var _proto4 = Rect.prototype;

              _proto4.copy = function copy(info) {
                this.x = info.x;
                this.y = info.y;
                this.width = info.width;
                this.height = info.height;
                return this;
              };

              return Rect;
            }();
            var Extent = function () {
              function Extent(width, height, depth) {
                if (width === void 0) {
                  width = 0;
                }

                if (height === void 0) {
                  height = 0;
                }

                if (depth === void 0) {
                  depth = 1;
                }

                this.width = width;
                this.height = height;
                this.depth = depth;
              }

              var _proto5 = Extent.prototype;

              _proto5.copy = function copy(info) {
                this.width = info.width;
                this.height = info.height;
                this.depth = info.depth;
                return this;
              };

              return Extent;
            }();
            var TextureSubresLayers = function () {
              function TextureSubresLayers(mipLevel, baseArrayLayer, layerCount) {
                if (mipLevel === void 0) {
                  mipLevel = 0;
                }

                if (baseArrayLayer === void 0) {
                  baseArrayLayer = 0;
                }

                if (layerCount === void 0) {
                  layerCount = 1;
                }

                this.mipLevel = mipLevel;
                this.baseArrayLayer = baseArrayLayer;
                this.layerCount = layerCount;
              }

              var _proto6 = TextureSubresLayers.prototype;

              _proto6.copy = function copy(info) {
                this.mipLevel = info.mipLevel;
                this.baseArrayLayer = info.baseArrayLayer;
                this.layerCount = info.layerCount;
                return this;
              };

              return TextureSubresLayers;
            }();
            var TextureSubresRange = function () {
              function TextureSubresRange(baseMipLevel, levelCount, baseArrayLayer, layerCount) {
                if (baseMipLevel === void 0) {
                  baseMipLevel = 0;
                }

                if (levelCount === void 0) {
                  levelCount = 1;
                }

                if (baseArrayLayer === void 0) {
                  baseArrayLayer = 0;
                }

                if (layerCount === void 0) {
                  layerCount = 1;
                }

                this.baseMipLevel = baseMipLevel;
                this.levelCount = levelCount;
                this.baseArrayLayer = baseArrayLayer;
                this.layerCount = layerCount;
              }

              var _proto7 = TextureSubresRange.prototype;

              _proto7.copy = function copy(info) {
                this.baseMipLevel = info.baseMipLevel;
                this.levelCount = info.levelCount;
                this.baseArrayLayer = info.baseArrayLayer;
                this.layerCount = info.layerCount;
                return this;
              };

              return TextureSubresRange;
            }();
            var TextureCopy = function () {
              function TextureCopy(srcSubres, srcOffset, dstSubres, dstOffset, extent) {
                if (srcSubres === void 0) {
                  srcSubres = new TextureSubresLayers();
                }

                if (srcOffset === void 0) {
                  srcOffset = new Offset();
                }

                if (dstSubres === void 0) {
                  dstSubres = new TextureSubresLayers();
                }

                if (dstOffset === void 0) {
                  dstOffset = new Offset();
                }

                if (extent === void 0) {
                  extent = new Extent();
                }

                this.srcSubres = srcSubres;
                this.srcOffset = srcOffset;
                this.dstSubres = dstSubres;
                this.dstOffset = dstOffset;
                this.extent = extent;
              }

              var _proto8 = TextureCopy.prototype;

              _proto8.copy = function copy(info) {
                this.srcSubres.copy(info.srcSubres);
                this.srcOffset.copy(info.srcOffset);
                this.dstSubres.copy(info.dstSubres);
                this.dstOffset.copy(info.dstOffset);
                this.extent.copy(info.extent);
                return this;
              };

              return TextureCopy;
            }();
            var TextureBlit = function () {
              function TextureBlit(srcSubres, srcOffset, srcExtent, dstSubres, dstOffset, dstExtent) {
                if (srcSubres === void 0) {
                  srcSubres = new TextureSubresLayers();
                }

                if (srcOffset === void 0) {
                  srcOffset = new Offset();
                }

                if (srcExtent === void 0) {
                  srcExtent = new Extent();
                }

                if (dstSubres === void 0) {
                  dstSubres = new TextureSubresLayers();
                }

                if (dstOffset === void 0) {
                  dstOffset = new Offset();
                }

                if (dstExtent === void 0) {
                  dstExtent = new Extent();
                }

                this.srcSubres = srcSubres;
                this.srcOffset = srcOffset;
                this.srcExtent = srcExtent;
                this.dstSubres = dstSubres;
                this.dstOffset = dstOffset;
                this.dstExtent = dstExtent;
              }

              var _proto9 = TextureBlit.prototype;

              _proto9.copy = function copy(info) {
                this.srcSubres.copy(info.srcSubres);
                this.srcOffset.copy(info.srcOffset);
                this.srcExtent.copy(info.srcExtent);
                this.dstSubres.copy(info.dstSubres);
                this.dstOffset.copy(info.dstOffset);
                this.dstExtent.copy(info.dstExtent);
                return this;
              };

              return TextureBlit;
            }();
            var BufferTextureCopy = function () {
              function BufferTextureCopy(buffStride, buffTexHeight, texOffset, texExtent, texSubres) {
                if (buffStride === void 0) {
                  buffStride = 0;
                }

                if (buffTexHeight === void 0) {
                  buffTexHeight = 0;
                }

                if (texOffset === void 0) {
                  texOffset = new Offset();
                }

                if (texExtent === void 0) {
                  texExtent = new Extent();
                }

                if (texSubres === void 0) {
                  texSubres = new TextureSubresLayers();
                }

                this.buffStride = buffStride;
                this.buffTexHeight = buffTexHeight;
                this.texOffset = texOffset;
                this.texExtent = texExtent;
                this.texSubres = texSubres;
              }

              var _proto10 = BufferTextureCopy.prototype;

              _proto10.copy = function copy(info) {
                this.buffStride = info.buffStride;
                this.buffTexHeight = info.buffTexHeight;
                this.texOffset.copy(info.texOffset);
                this.texExtent.copy(info.texExtent);
                this.texSubres.copy(info.texSubres);
                return this;
              };

              return BufferTextureCopy;
            }();
            var Viewport = function () {
              function Viewport(left, top, width, height, minDepth, maxDepth) {
                if (left === void 0) {
                  left = 0;
                }

                if (top === void 0) {
                  top = 0;
                }

                if (width === void 0) {
                  width = 0;
                }

                if (height === void 0) {
                  height = 0;
                }

                if (minDepth === void 0) {
                  minDepth = 0;
                }

                if (maxDepth === void 0) {
                  maxDepth = 1;
                }

                this.left = left;
                this.top = top;
                this.width = width;
                this.height = height;
                this.minDepth = minDepth;
                this.maxDepth = maxDepth;
              }

              var _proto11 = Viewport.prototype;

              _proto11.copy = function copy(info) {
                this.left = info.left;
                this.top = info.top;
                this.width = info.width;
                this.height = info.height;
                this.minDepth = info.minDepth;
                this.maxDepth = info.maxDepth;
                return this;
              };

              return Viewport;
            }();
            var Color$1 = function () {
              function Color(x, y, z, w) {
                if (x === void 0) {
                  x = 0;
                }

                if (y === void 0) {
                  y = 0;
                }

                if (z === void 0) {
                  z = 0;
                }

                if (w === void 0) {
                  w = 0;
                }

                this.x = x;
                this.y = y;
                this.z = z;
                this.w = w;
              }

              var _proto12 = Color.prototype;

              _proto12.copy = function copy(info) {
                this.x = info.x;
                this.y = info.y;
                this.z = info.z;
                this.w = info.w;
                return this;
              };

              return Color;
            }();
            var BindingMappingInfo = function () {
              function BindingMappingInfo(bufferOffsets, samplerOffsets, flexibleSet) {
                if (bufferOffsets === void 0) {
                  bufferOffsets = [];
                }

                if (samplerOffsets === void 0) {
                  samplerOffsets = [];
                }

                if (flexibleSet === void 0) {
                  flexibleSet = 0;
                }

                this.bufferOffsets = bufferOffsets;
                this.samplerOffsets = samplerOffsets;
                this.flexibleSet = flexibleSet;
              }

              var _proto13 = BindingMappingInfo.prototype;

              _proto13.copy = function copy(info) {
                this.bufferOffsets = info.bufferOffsets.slice();
                this.samplerOffsets = info.samplerOffsets.slice();
                this.flexibleSet = info.flexibleSet;
                return this;
              };

              return BindingMappingInfo;
            }();
            var BufferInfo = function () {
              function BufferInfo(usage, memUsage, size, stride, flags) {
                if (usage === void 0) {
                  usage = BufferUsageBit.NONE;
                }

                if (memUsage === void 0) {
                  memUsage = MemoryUsageBit.NONE;
                }

                if (size === void 0) {
                  size = 0;
                }

                if (stride === void 0) {
                  stride = 0;
                }

                if (flags === void 0) {
                  flags = BufferFlagBit.NONE;
                }

                this.usage = usage;
                this.memUsage = memUsage;
                this.size = size;
                this.stride = stride;
                this.flags = flags;
              }

              var _proto14 = BufferInfo.prototype;

              _proto14.copy = function copy(info) {
                this.usage = info.usage;
                this.memUsage = info.memUsage;
                this.size = info.size;
                this.stride = info.stride;
                this.flags = info.flags;
                return this;
              };

              return BufferInfo;
            }();
            var BufferViewInfo = function () {
              function BufferViewInfo(buffer, offset, range) {
                if (buffer === void 0) {
                  buffer = null;
                }

                if (offset === void 0) {
                  offset = 0;
                }

                if (range === void 0) {
                  range = 0;
                }

                this.buffer = buffer;
                this.offset = offset;
                this.range = range;
              }

              var _proto15 = BufferViewInfo.prototype;

              _proto15.copy = function copy(info) {
                this.buffer = info.buffer;
                this.offset = info.offset;
                this.range = info.range;
                return this;
              };

              return BufferViewInfo;
            }();
            var DrawInfo = function () {
              function DrawInfo(vertexCount, firstVertex, indexCount, firstIndex, vertexOffset, instanceCount, firstInstance) {
                if (vertexCount === void 0) {
                  vertexCount = 0;
                }

                if (firstVertex === void 0) {
                  firstVertex = 0;
                }

                if (indexCount === void 0) {
                  indexCount = 0;
                }

                if (firstIndex === void 0) {
                  firstIndex = 0;
                }

                if (vertexOffset === void 0) {
                  vertexOffset = 0;
                }

                if (instanceCount === void 0) {
                  instanceCount = 0;
                }

                if (firstInstance === void 0) {
                  firstInstance = 0;
                }

                this.vertexCount = vertexCount;
                this.firstVertex = firstVertex;
                this.indexCount = indexCount;
                this.firstIndex = firstIndex;
                this.vertexOffset = vertexOffset;
                this.instanceCount = instanceCount;
                this.firstInstance = firstInstance;
              }

              var _proto16 = DrawInfo.prototype;

              _proto16.copy = function copy(info) {
                this.vertexCount = info.vertexCount;
                this.firstVertex = info.firstVertex;
                this.indexCount = info.indexCount;
                this.firstIndex = info.firstIndex;
                this.vertexOffset = info.vertexOffset;
                this.instanceCount = info.instanceCount;
                this.firstInstance = info.firstInstance;
                return this;
              };

              return DrawInfo;
            }();
            var DispatchInfo = function () {
              function DispatchInfo(groupCountX, groupCountY, groupCountZ, indirectBuffer, indirectOffset) {
                if (groupCountX === void 0) {
                  groupCountX = 0;
                }

                if (groupCountY === void 0) {
                  groupCountY = 0;
                }

                if (groupCountZ === void 0) {
                  groupCountZ = 0;
                }

                if (indirectBuffer === void 0) {
                  indirectBuffer = null;
                }

                if (indirectOffset === void 0) {
                  indirectOffset = 0;
                }

                this.groupCountX = groupCountX;
                this.groupCountY = groupCountY;
                this.groupCountZ = groupCountZ;
                this.indirectBuffer = indirectBuffer;
                this.indirectOffset = indirectOffset;
              }

              var _proto17 = DispatchInfo.prototype;

              _proto17.copy = function copy(info) {
                this.groupCountX = info.groupCountX;
                this.groupCountY = info.groupCountY;
                this.groupCountZ = info.groupCountZ;
                this.indirectBuffer = info.indirectBuffer;
                this.indirectOffset = info.indirectOffset;
                return this;
              };

              return DispatchInfo;
            }();
            var IndirectBuffer = function () {
              function IndirectBuffer(drawInfos) {
                if (drawInfos === void 0) {
                  drawInfos = [];
                }

                this.drawInfos = drawInfos;
              }

              var _proto18 = IndirectBuffer.prototype;

              _proto18.copy = function copy(info) {
                deepCopy(this.drawInfos, info.drawInfos, DrawInfo);
                return this;
              };

              return IndirectBuffer;
            }();
            var TextureInfo = function () {
              function TextureInfo(type, usage, format, width, height, flags, layerCount, levelCount, samples, depth) {
                if (type === void 0) {
                  type = TextureType.TEX2D;
                }

                if (usage === void 0) {
                  usage = TextureUsageBit.NONE;
                }

                if (format === void 0) {
                  format = Format.UNKNOWN;
                }

                if (width === void 0) {
                  width = 0;
                }

                if (height === void 0) {
                  height = 0;
                }

                if (flags === void 0) {
                  flags = TextureFlagBit.NONE;
                }

                if (layerCount === void 0) {
                  layerCount = 1;
                }

                if (levelCount === void 0) {
                  levelCount = 1;
                }

                if (samples === void 0) {
                  samples = SampleCount.X1;
                }

                if (depth === void 0) {
                  depth = 1;
                }

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

              var _proto19 = TextureInfo.prototype;

              _proto19.copy = function copy(info) {
                this.type = info.type;
                this.usage = info.usage;
                this.format = info.format;
                this.width = info.width;
                this.height = info.height;
                this.flags = info.flags;
                this.layerCount = info.layerCount;
                this.levelCount = info.levelCount;
                this.samples = info.samples;
                this.depth = info.depth;
                return this;
              };

              return TextureInfo;
            }();
            var TextureViewInfo = function () {
              function TextureViewInfo(texture, type, format, baseLevel, levelCount, baseLayer, layerCount) {
                if (texture === void 0) {
                  texture = null;
                }

                if (type === void 0) {
                  type = TextureType.TEX2D;
                }

                if (format === void 0) {
                  format = Format.UNKNOWN;
                }

                if (baseLevel === void 0) {
                  baseLevel = 0;
                }

                if (levelCount === void 0) {
                  levelCount = 1;
                }

                if (baseLayer === void 0) {
                  baseLayer = 0;
                }

                if (layerCount === void 0) {
                  layerCount = 1;
                }

                this.texture = texture;
                this.type = type;
                this.format = format;
                this.baseLevel = baseLevel;
                this.levelCount = levelCount;
                this.baseLayer = baseLayer;
                this.layerCount = layerCount;
              }

              var _proto20 = TextureViewInfo.prototype;

              _proto20.copy = function copy(info) {
                this.texture = info.texture;
                this.type = info.type;
                this.format = info.format;
                this.baseLevel = info.baseLevel;
                this.levelCount = info.levelCount;
                this.baseLayer = info.baseLayer;
                this.layerCount = info.layerCount;
                return this;
              };

              return TextureViewInfo;
            }();
            var SamplerInfo = function () {
              function SamplerInfo(minFilter, magFilter, mipFilter, addressU, addressV, addressW, maxAnisotropy, cmpFunc, borderColor, mipLODBias) {
                if (minFilter === void 0) {
                  minFilter = Filter.LINEAR;
                }

                if (magFilter === void 0) {
                  magFilter = Filter.LINEAR;
                }

                if (mipFilter === void 0) {
                  mipFilter = Filter.NONE;
                }

                if (addressU === void 0) {
                  addressU = Address.WRAP;
                }

                if (addressV === void 0) {
                  addressV = Address.WRAP;
                }

                if (addressW === void 0) {
                  addressW = Address.WRAP;
                }

                if (maxAnisotropy === void 0) {
                  maxAnisotropy = 0;
                }

                if (cmpFunc === void 0) {
                  cmpFunc = ComparisonFunc.ALWAYS;
                }

                if (borderColor === void 0) {
                  borderColor = new Color$1();
                }

                if (mipLODBias === void 0) {
                  mipLODBias = 0;
                }

                this.minFilter = minFilter;
                this.magFilter = magFilter;
                this.mipFilter = mipFilter;
                this.addressU = addressU;
                this.addressV = addressV;
                this.addressW = addressW;
                this.maxAnisotropy = maxAnisotropy;
                this.cmpFunc = cmpFunc;
                this.borderColor = borderColor;
                this.mipLODBias = mipLODBias;
              }

              var _proto21 = SamplerInfo.prototype;

              _proto21.copy = function copy(info) {
                this.minFilter = info.minFilter;
                this.magFilter = info.magFilter;
                this.mipFilter = info.mipFilter;
                this.addressU = info.addressU;
                this.addressV = info.addressV;
                this.addressW = info.addressW;
                this.maxAnisotropy = info.maxAnisotropy;
                this.cmpFunc = info.cmpFunc;
                this.borderColor.copy(info.borderColor);
                this.mipLODBias = info.mipLODBias;
                return this;
              };

              return SamplerInfo;
            }();
            var Uniform = function () {
              function Uniform(name, type, count) {
                if (name === void 0) {
                  name = '';
                }

                if (type === void 0) {
                  type = Type.UNKNOWN;
                }

                if (count === void 0) {
                  count = 0;
                }

                this.name = name;
                this.type = type;
                this.count = count;
              }

              var _proto22 = Uniform.prototype;

              _proto22.copy = function copy(info) {
                this.name = info.name;
                this.type = info.type;
                this.count = info.count;
                return this;
              };

              return Uniform;
            }();
            var UniformBlock = function () {
              function UniformBlock(set, binding, name, members, count) {
                if (set === void 0) {
                  set = 0;
                }

                if (binding === void 0) {
                  binding = 0;
                }

                if (name === void 0) {
                  name = '';
                }

                if (members === void 0) {
                  members = [];
                }

                if (count === void 0) {
                  count = 0;
                }

                this.set = set;
                this.binding = binding;
                this.name = name;
                this.members = members;
                this.count = count;
              }

              var _proto23 = UniformBlock.prototype;

              _proto23.copy = function copy(info) {
                this.set = info.set;
                this.binding = info.binding;
                this.name = info.name;
                deepCopy(this.members, info.members, Uniform);
                this.count = info.count;
                return this;
              };

              return UniformBlock;
            }();
            var UniformSamplerTexture = function () {
              function UniformSamplerTexture(set, binding, name, type, count) {
                if (set === void 0) {
                  set = 0;
                }

                if (binding === void 0) {
                  binding = 0;
                }

                if (name === void 0) {
                  name = '';
                }

                if (type === void 0) {
                  type = Type.UNKNOWN;
                }

                if (count === void 0) {
                  count = 0;
                }

                this.set = set;
                this.binding = binding;
                this.name = name;
                this.type = type;
                this.count = count;
              }

              var _proto24 = UniformSamplerTexture.prototype;

              _proto24.copy = function copy(info) {
                this.set = info.set;
                this.binding = info.binding;
                this.name = info.name;
                this.type = info.type;
                this.count = info.count;
                return this;
              };

              return UniformSamplerTexture;
            }();
            var UniformSampler = function () {
              function UniformSampler(set, binding, name, count) {
                if (set === void 0) {
                  set = 0;
                }

                if (binding === void 0) {
                  binding = 0;
                }

                if (name === void 0) {
                  name = '';
                }

                if (count === void 0) {
                  count = 0;
                }

                this.set = set;
                this.binding = binding;
                this.name = name;
                this.count = count;
              }

              var _proto25 = UniformSampler.prototype;

              _proto25.copy = function copy(info) {
                this.set = info.set;
                this.binding = info.binding;
                this.name = info.name;
                this.count = info.count;
                return this;
              };

              return UniformSampler;
            }();
            var UniformTexture = function () {
              function UniformTexture(set, binding, name, type, count) {
                if (set === void 0) {
                  set = 0;
                }

                if (binding === void 0) {
                  binding = 0;
                }

                if (name === void 0) {
                  name = '';
                }

                if (type === void 0) {
                  type = Type.UNKNOWN;
                }

                if (count === void 0) {
                  count = 0;
                }

                this.set = set;
                this.binding = binding;
                this.name = name;
                this.type = type;
                this.count = count;
              }

              var _proto26 = UniformTexture.prototype;

              _proto26.copy = function copy(info) {
                this.set = info.set;
                this.binding = info.binding;
                this.name = info.name;
                this.type = info.type;
                this.count = info.count;
                return this;
              };

              return UniformTexture;
            }();
            var UniformStorageImage = function () {
              function UniformStorageImage(set, binding, name, type, count, memoryAccess) {
                if (set === void 0) {
                  set = 0;
                }

                if (binding === void 0) {
                  binding = 0;
                }

                if (name === void 0) {
                  name = '';
                }

                if (type === void 0) {
                  type = Type.UNKNOWN;
                }

                if (count === void 0) {
                  count = 0;
                }

                if (memoryAccess === void 0) {
                  memoryAccess = MemoryAccessBit.READ_WRITE;
                }

                this.set = set;
                this.binding = binding;
                this.name = name;
                this.type = type;
                this.count = count;
                this.memoryAccess = memoryAccess;
              }

              var _proto27 = UniformStorageImage.prototype;

              _proto27.copy = function copy(info) {
                this.set = info.set;
                this.binding = info.binding;
                this.name = info.name;
                this.type = info.type;
                this.count = info.count;
                this.memoryAccess = info.memoryAccess;
                return this;
              };

              return UniformStorageImage;
            }();
            var UniformStorageBuffer = function () {
              function UniformStorageBuffer(set, binding, name, count, memoryAccess) {
                if (set === void 0) {
                  set = 0;
                }

                if (binding === void 0) {
                  binding = 0;
                }

                if (name === void 0) {
                  name = '';
                }

                if (count === void 0) {
                  count = 0;
                }

                if (memoryAccess === void 0) {
                  memoryAccess = MemoryAccessBit.READ_WRITE;
                }

                this.set = set;
                this.binding = binding;
                this.name = name;
                this.count = count;
                this.memoryAccess = memoryAccess;
              }

              var _proto28 = UniformStorageBuffer.prototype;

              _proto28.copy = function copy(info) {
                this.set = info.set;
                this.binding = info.binding;
                this.name = info.name;
                this.count = info.count;
                this.memoryAccess = info.memoryAccess;
                return this;
              };

              return UniformStorageBuffer;
            }();
            var UniformInputAttachment = function () {
              function UniformInputAttachment(set, binding, name, count) {
                if (set === void 0) {
                  set = 0;
                }

                if (binding === void 0) {
                  binding = 0;
                }

                if (name === void 0) {
                  name = '';
                }

                if (count === void 0) {
                  count = 0;
                }

                this.set = set;
                this.binding = binding;
                this.name = name;
                this.count = count;
              }

              var _proto29 = UniformInputAttachment.prototype;

              _proto29.copy = function copy(info) {
                this.set = info.set;
                this.binding = info.binding;
                this.name = info.name;
                this.count = info.count;
                return this;
              };

              return UniformInputAttachment;
            }();
            var ShaderStage = function () {
              function ShaderStage(stage, source) {
                if (stage === void 0) {
                  stage = ShaderStageFlagBit.NONE;
                }

                if (source === void 0) {
                  source = '';
                }

                this.stage = stage;
                this.source = source;
              }

              var _proto30 = ShaderStage.prototype;

              _proto30.copy = function copy(info) {
                this.stage = info.stage;
                this.source = info.source;
                return this;
              };

              return ShaderStage;
            }();
            var Attribute = function () {
              function Attribute(name, format, isNormalized, stream, isInstanced, location) {
                if (name === void 0) {
                  name = '';
                }

                if (format === void 0) {
                  format = Format.UNKNOWN;
                }

                if (isNormalized === void 0) {
                  isNormalized = false;
                }

                if (stream === void 0) {
                  stream = 0;
                }

                if (isInstanced === void 0) {
                  isInstanced = false;
                }

                if (location === void 0) {
                  location = 0;
                }

                this.name = name;
                this.format = format;
                this.isNormalized = isNormalized;
                this.stream = stream;
                this.isInstanced = isInstanced;
                this.location = location;
              }

              var _proto31 = Attribute.prototype;

              _proto31.copy = function copy(info) {
                this.name = info.name;
                this.format = info.format;
                this.isNormalized = info.isNormalized;
                this.stream = info.stream;
                this.isInstanced = info.isInstanced;
                this.location = info.location;
                return this;
              };

              return Attribute;
            }();
            var ShaderInfo = function () {
              function ShaderInfo(name, stages, attributes, blocks, buffers, samplerTextures, samplers, textures, images, subpassInputs) {
                if (name === void 0) {
                  name = '';
                }

                if (stages === void 0) {
                  stages = [];
                }

                if (attributes === void 0) {
                  attributes = [];
                }

                if (blocks === void 0) {
                  blocks = [];
                }

                if (buffers === void 0) {
                  buffers = [];
                }

                if (samplerTextures === void 0) {
                  samplerTextures = [];
                }

                if (samplers === void 0) {
                  samplers = [];
                }

                if (textures === void 0) {
                  textures = [];
                }

                if (images === void 0) {
                  images = [];
                }

                if (subpassInputs === void 0) {
                  subpassInputs = [];
                }

                this.name = name;
                this.stages = stages;
                this.attributes = attributes;
                this.blocks = blocks;
                this.buffers = buffers;
                this.samplerTextures = samplerTextures;
                this.samplers = samplers;
                this.textures = textures;
                this.images = images;
                this.subpassInputs = subpassInputs;
              }

              var _proto32 = ShaderInfo.prototype;

              _proto32.copy = function copy(info) {
                this.name = info.name;
                deepCopy(this.stages, info.stages, ShaderStage);
                deepCopy(this.attributes, info.attributes, Attribute);
                deepCopy(this.blocks, info.blocks, UniformBlock);
                deepCopy(this.buffers, info.buffers, UniformStorageBuffer);
                deepCopy(this.samplerTextures, info.samplerTextures, UniformSamplerTexture);
                deepCopy(this.samplers, info.samplers, UniformSampler);
                deepCopy(this.textures, info.textures, UniformTexture);
                deepCopy(this.images, info.images, UniformStorageImage);
                deepCopy(this.subpassInputs, info.subpassInputs, UniformInputAttachment);
                return this;
              };

              return ShaderInfo;
            }();
            var InputAssemblerInfo = function () {
              function InputAssemblerInfo(attributes, vertexBuffers, indexBuffer, indirectBuffer) {
                if (attributes === void 0) {
                  attributes = [];
                }

                if (vertexBuffers === void 0) {
                  vertexBuffers = [];
                }

                if (indexBuffer === void 0) {
                  indexBuffer = null;
                }

                if (indirectBuffer === void 0) {
                  indirectBuffer = null;
                }

                this.attributes = attributes;
                this.vertexBuffers = vertexBuffers;
                this.indexBuffer = indexBuffer;
                this.indirectBuffer = indirectBuffer;
              }

              var _proto33 = InputAssemblerInfo.prototype;

              _proto33.copy = function copy(info) {
                deepCopy(this.attributes, info.attributes, Attribute);
                this.vertexBuffers = info.vertexBuffers.slice();
                this.indexBuffer = info.indexBuffer;
                this.indirectBuffer = info.indirectBuffer;
                return this;
              };

              return InputAssemblerInfo;
            }();
            var ColorAttachment = function () {
              function ColorAttachment(format, sampleCount, loadOp, storeOp, beginAccesses, endAccesses) {
                if (format === void 0) {
                  format = Format.UNKNOWN;
                }

                if (sampleCount === void 0) {
                  sampleCount = SampleCount.X1;
                }

                if (loadOp === void 0) {
                  loadOp = LoadOp.CLEAR;
                }

                if (storeOp === void 0) {
                  storeOp = StoreOp.STORE;
                }

                if (beginAccesses === void 0) {
                  beginAccesses = [];
                }

                if (endAccesses === void 0) {
                  endAccesses = [AccessType.PRESENT];
                }

                this.format = format;
                this.sampleCount = sampleCount;
                this.loadOp = loadOp;
                this.storeOp = storeOp;
                this.beginAccesses = beginAccesses;
                this.endAccesses = endAccesses;
              }

              var _proto34 = ColorAttachment.prototype;

              _proto34.copy = function copy(info) {
                this.format = info.format;
                this.sampleCount = info.sampleCount;
                this.loadOp = info.loadOp;
                this.storeOp = info.storeOp;
                this.beginAccesses = info.beginAccesses.slice();
                this.endAccesses = info.endAccesses.slice();
                return this;
              };

              return ColorAttachment;
            }();
            var DepthStencilAttachment = function () {
              function DepthStencilAttachment(format, sampleCount, depthLoadOp, depthStoreOp, stencilLoadOp, stencilStoreOp, beginAccesses, endAccesses) {
                if (format === void 0) {
                  format = Format.UNKNOWN;
                }

                if (sampleCount === void 0) {
                  sampleCount = SampleCount.X1;
                }

                if (depthLoadOp === void 0) {
                  depthLoadOp = LoadOp.CLEAR;
                }

                if (depthStoreOp === void 0) {
                  depthStoreOp = StoreOp.STORE;
                }

                if (stencilLoadOp === void 0) {
                  stencilLoadOp = LoadOp.CLEAR;
                }

                if (stencilStoreOp === void 0) {
                  stencilStoreOp = StoreOp.STORE;
                }

                if (beginAccesses === void 0) {
                  beginAccesses = [];
                }

                if (endAccesses === void 0) {
                  endAccesses = [AccessType.DEPTH_STENCIL_ATTACHMENT_WRITE];
                }

                this.format = format;
                this.sampleCount = sampleCount;
                this.depthLoadOp = depthLoadOp;
                this.depthStoreOp = depthStoreOp;
                this.stencilLoadOp = stencilLoadOp;
                this.stencilStoreOp = stencilStoreOp;
                this.beginAccesses = beginAccesses;
                this.endAccesses = endAccesses;
              }

              var _proto35 = DepthStencilAttachment.prototype;

              _proto35.copy = function copy(info) {
                this.format = info.format;
                this.sampleCount = info.sampleCount;
                this.depthLoadOp = info.depthLoadOp;
                this.depthStoreOp = info.depthStoreOp;
                this.stencilLoadOp = info.stencilLoadOp;
                this.stencilStoreOp = info.stencilStoreOp;
                this.beginAccesses = info.beginAccesses.slice();
                this.endAccesses = info.endAccesses.slice();
                return this;
              };

              return DepthStencilAttachment;
            }();
            var SubpassInfo = function () {
              function SubpassInfo(inputs, colors, resolves, preserves, depthStencil) {
                if (inputs === void 0) {
                  inputs = [];
                }

                if (colors === void 0) {
                  colors = [];
                }

                if (resolves === void 0) {
                  resolves = [];
                }

                if (preserves === void 0) {
                  preserves = [];
                }

                if (depthStencil === void 0) {
                  depthStencil = -1;
                }

                this.inputs = inputs;
                this.colors = colors;
                this.resolves = resolves;
                this.preserves = preserves;
                this.depthStencil = depthStencil;
              }

              var _proto36 = SubpassInfo.prototype;

              _proto36.copy = function copy(info) {
                this.inputs = info.inputs.slice();
                this.colors = info.colors.slice();
                this.resolves = info.resolves.slice();
                this.preserves = info.preserves.slice();
                this.depthStencil = info.depthStencil;
                return this;
              };

              return SubpassInfo;
            }();
            var RenderPassInfo = function () {
              function RenderPassInfo(colorAttachments, depthStencilAttachment, subpasses) {
                if (colorAttachments === void 0) {
                  colorAttachments = [];
                }

                if (depthStencilAttachment === void 0) {
                  depthStencilAttachment = new DepthStencilAttachment();
                }

                if (subpasses === void 0) {
                  subpasses = [];
                }

                this.colorAttachments = colorAttachments;
                this.depthStencilAttachment = depthStencilAttachment;
                this.subpasses = subpasses;
              }

              var _proto37 = RenderPassInfo.prototype;

              _proto37.copy = function copy(info) {
                deepCopy(this.colorAttachments, info.colorAttachments, ColorAttachment);
                this.depthStencilAttachment.copy(info.depthStencilAttachment);
                deepCopy(this.subpasses, info.subpasses, SubpassInfo);
                return this;
              };

              return RenderPassInfo;
            }();
            var GlobalBarrierInfo = function () {
              function GlobalBarrierInfo(prevAccesses, nextAccesses) {
                if (prevAccesses === void 0) {
                  prevAccesses = [];
                }

                if (nextAccesses === void 0) {
                  nextAccesses = [];
                }

                this.prevAccesses = prevAccesses;
                this.nextAccesses = nextAccesses;
              }

              var _proto38 = GlobalBarrierInfo.prototype;

              _proto38.copy = function copy(info) {
                this.prevAccesses = info.prevAccesses.slice();
                this.nextAccesses = info.nextAccesses.slice();
                return this;
              };

              return GlobalBarrierInfo;
            }();
            var TextureBarrierInfo = function () {
              function TextureBarrierInfo(prevAccesses, nextAccesses, discardContents, srcQueue, dstQueue) {
                if (prevAccesses === void 0) {
                  prevAccesses = [];
                }

                if (nextAccesses === void 0) {
                  nextAccesses = [];
                }

                if (discardContents === void 0) {
                  discardContents = false;
                }

                if (srcQueue === void 0) {
                  srcQueue = null;
                }

                if (dstQueue === void 0) {
                  dstQueue = null;
                }

                this.prevAccesses = prevAccesses;
                this.nextAccesses = nextAccesses;
                this.discardContents = discardContents;
                this.srcQueue = srcQueue;
                this.dstQueue = dstQueue;
              }

              var _proto39 = TextureBarrierInfo.prototype;

              _proto39.copy = function copy(info) {
                this.prevAccesses = info.prevAccesses.slice();
                this.nextAccesses = info.nextAccesses.slice();
                this.discardContents = info.discardContents;
                this.srcQueue = info.srcQueue;
                this.dstQueue = info.dstQueue;
                return this;
              };

              return TextureBarrierInfo;
            }();
            var FramebufferInfo = function () {
              function FramebufferInfo(renderPass, colorTextures, depthStencilTexture, colorMipmapLevels, depthStencilMipmapLevel) {
                if (renderPass === void 0) {
                  renderPass = null;
                }

                if (colorTextures === void 0) {
                  colorTextures = [];
                }

                if (depthStencilTexture === void 0) {
                  depthStencilTexture = null;
                }

                if (colorMipmapLevels === void 0) {
                  colorMipmapLevels = [];
                }

                if (depthStencilMipmapLevel === void 0) {
                  depthStencilMipmapLevel = 0;
                }

                this.renderPass = renderPass;
                this.colorTextures = colorTextures;
                this.depthStencilTexture = depthStencilTexture;
                this.colorMipmapLevels = colorMipmapLevels;
                this.depthStencilMipmapLevel = depthStencilMipmapLevel;
              }

              var _proto40 = FramebufferInfo.prototype;

              _proto40.copy = function copy(info) {
                this.renderPass = info.renderPass;
                this.colorTextures = info.colorTextures.slice();
                this.depthStencilTexture = info.depthStencilTexture;
                this.colorMipmapLevels = info.colorMipmapLevels.slice();
                this.depthStencilMipmapLevel = info.depthStencilMipmapLevel;
                return this;
              };

              return FramebufferInfo;
            }();
            var DescriptorSetLayoutBinding = function () {
              function DescriptorSetLayoutBinding(binding, descriptorType, count, stageFlags, immutableSamplers) {
                if (binding === void 0) {
                  binding = -1;
                }

                if (descriptorType === void 0) {
                  descriptorType = DescriptorType.UNKNOWN;
                }

                if (count === void 0) {
                  count = 0;
                }

                if (stageFlags === void 0) {
                  stageFlags = ShaderStageFlagBit.NONE;
                }

                if (immutableSamplers === void 0) {
                  immutableSamplers = [];
                }

                this.binding = binding;
                this.descriptorType = descriptorType;
                this.count = count;
                this.stageFlags = stageFlags;
                this.immutableSamplers = immutableSamplers;
              }

              var _proto41 = DescriptorSetLayoutBinding.prototype;

              _proto41.copy = function copy(info) {
                this.binding = info.binding;
                this.descriptorType = info.descriptorType;
                this.count = info.count;
                this.stageFlags = info.stageFlags;
                this.immutableSamplers = info.immutableSamplers.slice();
                return this;
              };

              return DescriptorSetLayoutBinding;
            }();
            var DescriptorSetLayoutInfo = function () {
              function DescriptorSetLayoutInfo(bindings) {
                if (bindings === void 0) {
                  bindings = [];
                }

                this.bindings = bindings;
              }

              var _proto42 = DescriptorSetLayoutInfo.prototype;

              _proto42.copy = function copy(info) {
                deepCopy(this.bindings, info.bindings, DescriptorSetLayoutBinding);
                return this;
              };

              return DescriptorSetLayoutInfo;
            }();
            var DescriptorSetInfo = function () {
              function DescriptorSetInfo(layout) {
                if (layout === void 0) {
                  layout = null;
                }

                this.layout = layout;
              }

              var _proto43 = DescriptorSetInfo.prototype;

              _proto43.copy = function copy(info) {
                this.layout = info.layout;
                return this;
              };

              return DescriptorSetInfo;
            }();
            var PipelineLayoutInfo = function () {
              function PipelineLayoutInfo(setLayouts) {
                if (setLayouts === void 0) {
                  setLayouts = [];
                }

                this.setLayouts = setLayouts;
              }

              var _proto44 = PipelineLayoutInfo.prototype;

              _proto44.copy = function copy(info) {
                this.setLayouts = info.setLayouts.slice();
                return this;
              };

              return PipelineLayoutInfo;
            }();
            var InputState = function () {
              function InputState(attributes) {
                if (attributes === void 0) {
                  attributes = [];
                }

                this.attributes = attributes;
              }

              var _proto45 = InputState.prototype;

              _proto45.copy = function copy(info) {
                deepCopy(this.attributes, info.attributes, Attribute);
                return this;
              };

              return InputState;
            }();
            var CommandBufferInfo = function () {
              function CommandBufferInfo(queue, type) {
                if (queue === void 0) {
                  queue = null;
                }

                if (type === void 0) {
                  type = CommandBufferType.PRIMARY;
                }

                this.queue = queue;
                this.type = type;
              }

              var _proto46 = CommandBufferInfo.prototype;

              _proto46.copy = function copy(info) {
                this.queue = info.queue;
                this.type = info.type;
                return this;
              };

              return CommandBufferInfo;
            }();
            var QueueInfo = function () {
              function QueueInfo(type) {
                if (type === void 0) {
                  type = QueueType.GRAPHICS;
                }

                this.type = type;
              }

              var _proto47 = QueueInfo.prototype;

              _proto47.copy = function copy(info) {
                this.type = info.type;
                return this;
              };

              return QueueInfo;
            }();
            var FormatInfo = function FormatInfo(name, size, count, type, hasAlpha, hasDepth, hasStencil, isCompressed) {
              if (name === void 0) {
                name = '';
              }

              if (size === void 0) {
                size = 0;
              }

              if (count === void 0) {
                count = 0;
              }

              if (type === void 0) {
                type = FormatType.NONE;
              }

              if (hasAlpha === void 0) {
                hasAlpha = false;
              }

              if (hasDepth === void 0) {
                hasDepth = false;
              }

              if (hasStencil === void 0) {
                hasStencil = false;
              }

              if (isCompressed === void 0) {
                isCompressed = false;
              }

              this.name = name;
              this.size = size;
              this.count = count;
              this.type = type;
              this.hasAlpha = hasAlpha;
              this.hasDepth = hasDepth;
              this.hasStencil = hasStencil;
              this.isCompressed = isCompressed;
            };
            var MemoryStatus = function () {
              function MemoryStatus(bufferSize, textureSize) {
                if (bufferSize === void 0) {
                  bufferSize = 0;
                }

                if (textureSize === void 0) {
                  textureSize = 0;
                }

                this.bufferSize = bufferSize;
                this.textureSize = textureSize;
              }

              var _proto48 = MemoryStatus.prototype;

              _proto48.copy = function copy(info) {
                this.bufferSize = info.bufferSize;
                this.textureSize = info.textureSize;
                return this;
              };

              return MemoryStatus;
            }();
            var DynamicStencilStates = function () {
              function DynamicStencilStates(writeMask, compareMask, reference) {
                if (writeMask === void 0) {
                  writeMask = 0;
                }

                if (compareMask === void 0) {
                  compareMask = 0;
                }

                if (reference === void 0) {
                  reference = 0;
                }

                this.writeMask = writeMask;
                this.compareMask = compareMask;
                this.reference = reference;
              }

              var _proto49 = DynamicStencilStates.prototype;

              _proto49.copy = function copy(info) {
                this.writeMask = info.writeMask;
                this.compareMask = info.compareMask;
                this.reference = info.reference;
                return this;
              };

              return DynamicStencilStates;
            }();
            var DynamicStates = function () {
              function DynamicStates(viewport, scissor, blendConstant, lineWidth, depthBiasConstant, depthBiasClamp, depthBiasSlope, depthMinBounds, depthMaxBounds, stencilStatesFront, stencilStatesBack) {
                if (viewport === void 0) {
                  viewport = new Viewport();
                }

                if (scissor === void 0) {
                  scissor = new Rect$1();
                }

                if (blendConstant === void 0) {
                  blendConstant = new Color$1();
                }

                if (lineWidth === void 0) {
                  lineWidth = 1;
                }

                if (depthBiasConstant === void 0) {
                  depthBiasConstant = 0;
                }

                if (depthBiasClamp === void 0) {
                  depthBiasClamp = 0;
                }

                if (depthBiasSlope === void 0) {
                  depthBiasSlope = 0;
                }

                if (depthMinBounds === void 0) {
                  depthMinBounds = 0;
                }

                if (depthMaxBounds === void 0) {
                  depthMaxBounds = 0;
                }

                if (stencilStatesFront === void 0) {
                  stencilStatesFront = new DynamicStencilStates();
                }

                if (stencilStatesBack === void 0) {
                  stencilStatesBack = new DynamicStencilStates();
                }

                this.viewport = viewport;
                this.scissor = scissor;
                this.blendConstant = blendConstant;
                this.lineWidth = lineWidth;
                this.depthBiasConstant = depthBiasConstant;
                this.depthBiasClamp = depthBiasClamp;
                this.depthBiasSlope = depthBiasSlope;
                this.depthMinBounds = depthMinBounds;
                this.depthMaxBounds = depthMaxBounds;
                this.stencilStatesFront = stencilStatesFront;
                this.stencilStatesBack = stencilStatesBack;
              }

              var _proto50 = DynamicStates.prototype;

              _proto50.copy = function copy(info) {
                this.viewport.copy(info.viewport);
                this.scissor.copy(info.scissor);
                this.blendConstant.copy(info.blendConstant);
                this.lineWidth = info.lineWidth;
                this.depthBiasConstant = info.depthBiasConstant;
                this.depthBiasClamp = info.depthBiasClamp;
                this.depthBiasSlope = info.depthBiasSlope;
                this.depthMinBounds = info.depthMinBounds;
                this.depthMaxBounds = info.depthMaxBounds;
                this.stencilStatesFront.copy(info.stencilStatesFront);
                this.stencilStatesBack.copy(info.stencilStatesBack);
                return this;
              };

              return DynamicStates;
            }();
            var Obj = function () {
              function Obj(gfxType) {
                this._gfxType = ObjectType.UNKNOWN;
                this._gfxType = gfxType;
              }

              _createClass(Obj, [{
                key: "gfxType",
                get: function get() {
                  return this._gfxType;
                }
              }]);

              return Obj;
            }();
            var DeviceInfo = function DeviceInfo(canvasElm, isAntialias, isPremultipliedAlpha, devicePixelRatio, nativeWidth, nativeHeight, bindingMappingInfo) {
              if (isAntialias === void 0) {
                isAntialias = true;
              }

              if (isPremultipliedAlpha === void 0) {
                isPremultipliedAlpha = true;
              }

              if (devicePixelRatio === void 0) {
                devicePixelRatio = 1;
              }

              if (nativeWidth === void 0) {
                nativeWidth = 1;
              }

              if (nativeHeight === void 0) {
                nativeHeight = 1;
              }

              if (bindingMappingInfo === void 0) {
                bindingMappingInfo = new BindingMappingInfo();
              }

              this.canvasElm = canvasElm;
              this.isAntialias = isAntialias;
              this.isPremultipliedAlpha = isPremultipliedAlpha;
              this.devicePixelRatio = devicePixelRatio;
              this.nativeWidth = nativeWidth;
              this.nativeHeight = nativeHeight;
              this.bindingMappingInfo = bindingMappingInfo;
            };
            var AttributeName;

            (function (AttributeName) {
              AttributeName["ATTR_POSITION"] = "a_position";
              AttributeName["ATTR_NORMAL"] = "a_normal";
              AttributeName["ATTR_TANGENT"] = "a_tangent";
              AttributeName["ATTR_BITANGENT"] = "a_bitangent";
              AttributeName["ATTR_WEIGHTS"] = "a_weights";
              AttributeName["ATTR_JOINTS"] = "a_joints";
              AttributeName["ATTR_COLOR"] = "a_color";
              AttributeName["ATTR_COLOR1"] = "a_color1";
              AttributeName["ATTR_COLOR2"] = "a_color2";
              AttributeName["ATTR_TEX_COORD"] = "a_texCoord";
              AttributeName["ATTR_TEX_COORD1"] = "a_texCoord1";
              AttributeName["ATTR_TEX_COORD2"] = "a_texCoord2";
              AttributeName["ATTR_TEX_COORD3"] = "a_texCoord3";
              AttributeName["ATTR_TEX_COORD4"] = "a_texCoord4";
              AttributeName["ATTR_TEX_COORD5"] = "a_texCoord5";
              AttributeName["ATTR_TEX_COORD6"] = "a_texCoord6";
              AttributeName["ATTR_TEX_COORD7"] = "a_texCoord7";
              AttributeName["ATTR_TEX_COORD8"] = "a_texCoord8";
              AttributeName["ATTR_BATCH_ID"] = "a_batch_id";
              AttributeName["ATTR_BATCH_UV"] = "a_batch_uv";
            })(AttributeName || (AttributeName = {}));

            var FormatInfos = Object.freeze([new FormatInfo('UNKNOWN', 0, 0, FormatType.NONE, false, false, false, false), new FormatInfo('A8', 1, 1, FormatType.UNORM, true, false, false, false), new FormatInfo('L8', 1, 1, FormatType.UNORM, false, false, false, false), new FormatInfo('LA8', 1, 2, FormatType.UNORM, true, false, false, false), new FormatInfo('R8', 1, 1, FormatType.UNORM, false, false, false, false), new FormatInfo('R8SN', 1, 1, FormatType.SNORM, false, false, false, false), new FormatInfo('R8UI', 1, 1, FormatType.UINT, false, false, false, false), new FormatInfo('R8I', 1, 1, FormatType.INT, false, false, false, false), new FormatInfo('R16F', 2, 1, FormatType.FLOAT, false, false, false, false), new FormatInfo('R16UI', 2, 1, FormatType.UINT, false, false, false, false), new FormatInfo('R16I', 2, 1, FormatType.INT, false, false, false, false), new FormatInfo('R32F', 4, 1, FormatType.FLOAT, false, false, false, false), new FormatInfo('R32UI', 4, 1, FormatType.UINT, false, false, false, false), new FormatInfo('R32I', 4, 1, FormatType.INT, false, false, false, false), new FormatInfo('RG8', 2, 2, FormatType.UNORM, false, false, false, false), new FormatInfo('RG8SN', 2, 2, FormatType.SNORM, false, false, false, false), new FormatInfo('RG8UI', 2, 2, FormatType.UINT, false, false, false, false), new FormatInfo('RG8I', 2, 2, FormatType.INT, false, false, false, false), new FormatInfo('RG16F', 4, 2, FormatType.FLOAT, false, false, false, false), new FormatInfo('RG16UI', 4, 2, FormatType.UINT, false, false, false, false), new FormatInfo('RG16I', 4, 2, FormatType.INT, false, false, false, false), new FormatInfo('RG32F', 8, 2, FormatType.FLOAT, false, false, false, false), new FormatInfo('RG32UI', 8, 2, FormatType.UINT, false, false, false, false), new FormatInfo('RG32I', 8, 2, FormatType.INT, false, false, false, false), new FormatInfo('RGB8', 3, 3, FormatType.UNORM, false, false, false, false), new FormatInfo('SRGB8', 3, 3, FormatType.UNORM, false, false, false, false), new FormatInfo('RGB8SN', 3, 3, FormatType.SNORM, false, false, false, false), new FormatInfo('RGB8UI', 3, 3, FormatType.UINT, false, false, false, false), new FormatInfo('RGB8I', 3, 3, FormatType.INT, false, false, false, false), new FormatInfo('RGB16F', 6, 3, FormatType.FLOAT, false, false, false, false), new FormatInfo('RGB16UI', 6, 3, FormatType.UINT, false, false, false, false), new FormatInfo('RGB16I', 6, 3, FormatType.INT, false, false, false, false), new FormatInfo('RGB32F', 12, 3, FormatType.FLOAT, false, false, false, false), new FormatInfo('RGB32UI', 12, 3, FormatType.UINT, false, false, false, false), new FormatInfo('RGB32I', 12, 3, FormatType.INT, false, false, false, false), new FormatInfo('RGBA8', 4, 4, FormatType.UNORM, true, false, false, false), new FormatInfo('BGRA8', 4, 4, FormatType.UNORM, true, false, false, false), new FormatInfo('SRGB8_A8', 4, 4, FormatType.UNORM, true, false, false, false), new FormatInfo('RGBA8SN', 4, 4, FormatType.SNORM, true, false, false, false), new FormatInfo('RGBA8UI', 4, 4, FormatType.UINT, true, false, false, false), new FormatInfo('RGBA8I', 4, 4, FormatType.INT, true, false, false, false), new FormatInfo('RGBA16F', 8, 4, FormatType.FLOAT, true, false, false, false), new FormatInfo('RGBA16UI', 8, 4, FormatType.UINT, true, false, false, false), new FormatInfo('RGBA16I', 8, 4, FormatType.INT, true, false, false, false), new FormatInfo('RGBA32F', 16, 4, FormatType.FLOAT, true, false, false, false), new FormatInfo('RGBA32UI', 16, 4, FormatType.UINT, true, false, false, false), new FormatInfo('RGBA32I', 16, 4, FormatType.INT, true, false, false, false), new FormatInfo('R5G6B5', 2, 3, FormatType.UNORM, false, false, false, false), new FormatInfo('R11G11B10F', 4, 3, FormatType.FLOAT, false, false, false, false), new FormatInfo('RGB5A1', 2, 4, FormatType.UNORM, true, false, false, false), new FormatInfo('RGBA4', 2, 4, FormatType.UNORM, true, false, false, false), new FormatInfo('RGB10A2', 2, 4, FormatType.UNORM, true, false, false, false), new FormatInfo('RGB10A2UI', 2, 4, FormatType.UINT, true, false, false, false), new FormatInfo('RGB9E5', 2, 4, FormatType.FLOAT, true, false, false, false), new FormatInfo('D16', 2, 1, FormatType.UINT, false, true, false, false), new FormatInfo('D16S8', 3, 2, FormatType.UINT, false, true, true, false), new FormatInfo('D24', 3, 1, FormatType.UINT, false, true, false, false), new FormatInfo('D24S8', 4, 2, FormatType.UINT, false, true, true, false), new FormatInfo('D32F', 4, 1, FormatType.FLOAT, false, true, false, false), new FormatInfo('D32FS8', 5, 2, FormatType.FLOAT, false, true, true, false), new FormatInfo('BC1', 1, 3, FormatType.UNORM, false, false, false, true), new FormatInfo('BC1_ALPHA', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('BC1_SRGB', 1, 3, FormatType.UNORM, false, false, false, true), new FormatInfo('BC1_SRGB_ALPHA', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('BC2', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('BC2_SRGB', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('BC3', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('BC3_SRGB', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('BC4', 1, 1, FormatType.UNORM, false, false, false, true), new FormatInfo('BC4_SNORM', 1, 1, FormatType.SNORM, false, false, false, true), new FormatInfo('BC5', 1, 2, FormatType.UNORM, false, false, false, true), new FormatInfo('BC5_SNORM', 1, 2, FormatType.SNORM, false, false, false, true), new FormatInfo('BC6H_UF16', 1, 3, FormatType.UFLOAT, false, false, false, true), new FormatInfo('BC6H_SF16', 1, 3, FormatType.FLOAT, false, false, false, true), new FormatInfo('BC7', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('BC7_SRGB', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ETC_RGB8', 1, 3, FormatType.UNORM, false, false, false, true), new FormatInfo('ETC2_RGB8', 1, 3, FormatType.UNORM, false, false, false, true), new FormatInfo('ETC2_SRGB8', 1, 3, FormatType.UNORM, false, false, false, true), new FormatInfo('ETC2_RGB8_A1', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ETC2_SRGB8_A1', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ETC2_RGBA8', 2, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ETC2_SRGB8_A8', 2, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('EAC_R11', 1, 1, FormatType.UNORM, false, false, false, true), new FormatInfo('EAC_R11SN', 1, 1, FormatType.SNORM, false, false, false, true), new FormatInfo('EAC_RG11', 2, 2, FormatType.UNORM, false, false, false, true), new FormatInfo('EAC_RG11SN', 2, 2, FormatType.SNORM, false, false, false, true), new FormatInfo('PVRTC_RGB2', 2, 3, FormatType.UNORM, false, false, false, true), new FormatInfo('PVRTC_RGBA2', 2, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('PVRTC_RGB4', 2, 3, FormatType.UNORM, false, false, false, true), new FormatInfo('PVRTC_RGBA4', 2, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('PVRTC2_2BPP', 2, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('PVRTC2_4BPP', 2, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_4x4', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_5x4', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_5x5', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_6x5', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_6x6', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_8x5', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_8x6', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_8x8', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_10x5', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_10x6', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_10x8', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_10x10', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_12x10', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_12x12', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_4x4', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_5x4', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_5x5', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_6x5', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_6x6', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_8x5', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_8x6', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_8x8', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_10x5', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_10x6', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_10x8', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_10x10', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_12x10', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_12x12', 1, 4, FormatType.UNORM, true, false, false, true)]);
            var DESCRIPTOR_BUFFER_TYPE = DescriptorType.UNIFORM_BUFFER | DescriptorType.DYNAMIC_UNIFORM_BUFFER | DescriptorType.STORAGE_BUFFER | DescriptorType.DYNAMIC_STORAGE_BUFFER;
            var DESCRIPTOR_SAMPLER_TYPE = DescriptorType.SAMPLER_TEXTURE | DescriptorType.SAMPLER | DescriptorType.TEXTURE | DescriptorType.STORAGE_IMAGE | DescriptorType.INPUT_ATTACHMENT;
            var DESCRIPTOR_DYNAMIC_TYPE = DescriptorType.DYNAMIC_STORAGE_BUFFER | DescriptorType.DYNAMIC_UNIFORM_BUFFER;
            var DRAW_INFO_SIZE = 28;
            function IsPowerOf2(x) {
              return x > 0 && (x & x - 1) === 0;
            }
            function FormatSize(format, width, height, depth) {
              if (!FormatInfos[format].isCompressed) {
                return width * height * depth * FormatInfos[format].size;
              } else {
                switch (format) {
                  case Format.BC1:
                  case Format.BC1_ALPHA:
                  case Format.BC1_SRGB:
                  case Format.BC1_SRGB_ALPHA:
                    return Math.ceil(width / 4) * Math.ceil(height / 4) * 8 * depth;

                  case Format.BC2:
                  case Format.BC2_SRGB:
                  case Format.BC3:
                  case Format.BC3_SRGB:
                  case Format.BC4:
                  case Format.BC4_SNORM:
                  case Format.BC6H_SF16:
                  case Format.BC6H_UF16:
                  case Format.BC7:
                  case Format.BC7_SRGB:
                    return Math.ceil(width / 4) * Math.ceil(height / 4) * 16 * depth;

                  case Format.BC5:
                  case Format.BC5_SNORM:
                    return Math.ceil(width / 4) * Math.ceil(height / 4) * 32 * depth;

                  case Format.ETC_RGB8:
                  case Format.ETC2_RGB8:
                  case Format.ETC2_SRGB8:
                  case Format.ETC2_RGB8_A1:
                  case Format.EAC_R11:
                  case Format.EAC_R11SN:
                    return Math.ceil(width / 4) * Math.ceil(height / 4) * 8 * depth;

                  case Format.ETC2_RGBA8:
                  case Format.ETC2_SRGB8_A1:
                  case Format.EAC_RG11:
                  case Format.EAC_RG11SN:
                    return Math.ceil(width / 4) * Math.ceil(height / 4) * 16 * depth;

                  case Format.PVRTC_RGB2:
                  case Format.PVRTC_RGBA2:
                  case Format.PVRTC2_2BPP:
                    return Math.ceil(Math.max(width, 16) * Math.max(height, 8) / 4) * depth;

                  case Format.PVRTC_RGB4:
                  case Format.PVRTC_RGBA4:
                  case Format.PVRTC2_4BPP:
                    return Math.ceil(Math.max(width, 8) * Math.max(height, 8) / 2) * depth;

                  case Format.ASTC_RGBA_4x4:
                  case Format.ASTC_SRGBA_4x4:
                    return Math.ceil(width / 4) * Math.ceil(height / 4) * 16 * depth;

                  case Format.ASTC_RGBA_5x4:
                  case Format.ASTC_SRGBA_5x4:
                    return Math.ceil(width / 5) * Math.ceil(height / 4) * 16 * depth;

                  case Format.ASTC_RGBA_5x5:
                  case Format.ASTC_SRGBA_5x5:
                    return Math.ceil(width / 5) * Math.ceil(height / 5) * 16 * depth;

                  case Format.ASTC_RGBA_6x5:
                  case Format.ASTC_SRGBA_6x5:
                    return Math.ceil(width / 6) * Math.ceil(height / 5) * 16 * depth;

                  case Format.ASTC_RGBA_6x6:
                  case Format.ASTC_SRGBA_6x6:
                    return Math.ceil(width / 6) * Math.ceil(height / 6) * 16 * depth;

                  case Format.ASTC_RGBA_8x5:
                  case Format.ASTC_SRGBA_8x5:
                    return Math.ceil(width / 8) * Math.ceil(height / 5) * 16 * depth;

                  case Format.ASTC_RGBA_8x6:
                  case Format.ASTC_SRGBA_8x6:
                    return Math.ceil(width / 8) * Math.ceil(height / 6) * 16 * depth;

                  case Format.ASTC_RGBA_8x8:
                  case Format.ASTC_SRGBA_8x8:
                    return Math.ceil(width / 8) * Math.ceil(height / 8) * 16 * depth;

                  case Format.ASTC_RGBA_10x5:
                  case Format.ASTC_SRGBA_10x5:
                    return Math.ceil(width / 10) * Math.ceil(height / 5) * 16 * depth;

                  case Format.ASTC_RGBA_10x6:
                  case Format.ASTC_SRGBA_10x6:
                    return Math.ceil(width / 10) * Math.ceil(height / 6) * 16 * depth;

                  case Format.ASTC_RGBA_10x8:
                  case Format.ASTC_SRGBA_10x8:
                    return Math.ceil(width / 10) * Math.ceil(height / 8) * 16 * depth;

                  case Format.ASTC_RGBA_10x10:
                  case Format.ASTC_SRGBA_10x10:
                    return Math.ceil(width / 10) * Math.ceil(height / 10) * 16 * depth;

                  case Format.ASTC_RGBA_12x10:
                  case Format.ASTC_SRGBA_12x10:
                    return Math.ceil(width / 12) * Math.ceil(height / 10) * 16 * depth;

                  case Format.ASTC_RGBA_12x12:
                  case Format.ASTC_SRGBA_12x12:
                    return Math.ceil(width / 12) * Math.ceil(height / 12) * 16 * depth;

                  default:
                    {
                      return 0;
                    }
                }
              }
            }
            function FormatSurfaceSize(format, width, height, depth, mips) {
              var size = 0;

              for (var i = 0; i < mips; ++i) {
                size += FormatSize(format, width, height, depth);
                width = Math.max(width >> 1, 1);
                height = Math.max(height >> 1, 1);
              }

              return size;
            }
            var _type2size = [0, 4, 8, 12, 16, 4, 8, 12, 16, 4, 8, 12, 16, 4, 8, 12, 16, 16, 24, 32, 24, 36, 48, 32, 48, 64, 4, 4, 4, 4, 4, 4];
            function GetTypeSize(type) {
              return _type2size[type] || 0;
            }
            function getTypedArrayConstructor(info) {
              var stride = info.size / info.count;

              switch (info.type) {
                case FormatType.UNORM:
                case FormatType.UINT:
                  {
                    switch (stride) {
                      case 1:
                        return Uint8Array;

                      case 2:
                        return Uint16Array;

                      case 4:
                        return Uint32Array;
                    }

                    break;
                  }

                case FormatType.SNORM:
                case FormatType.INT:
                  {
                    switch (stride) {
                      case 1:
                        return Int8Array;

                      case 2:
                        return Int16Array;

                      case 4:
                        return Int32Array;
                    }

                    break;
                  }

                case FormatType.FLOAT:
                  {
                    return Float32Array;
                  }
              }

              return Float32Array;
            }

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

            var Buffer = function (_Obj) {
              _inheritsLoose(Buffer, _Obj);

              function Buffer(device) {
                var _this;

                _this = _Obj.call(this, ObjectType.BUFFER) || this;
                _this._device = void 0;
                _this._usage = BufferUsageBit.NONE;
                _this._memUsage = MemoryUsageBit.NONE;
                _this._size = 0;
                _this._stride = 1;
                _this._count = 0;
                _this._flags = BufferFlagBit.NONE;
                _this._indirectBuffer = null;
                _this._isBufferView = false;
                _this._device = device;
                return _this;
              }

              _createClass(Buffer, [{
                key: "usage",
                get: function get() {
                  return this._usage;
                }
              }, {
                key: "memUsage",
                get: function get() {
                  return this._memUsage;
                }
              }, {
                key: "size",
                get: function get() {
                  return this._size;
                }
              }, {
                key: "stride",
                get: function get() {
                  return this._stride;
                }
              }, {
                key: "count",
                get: function get() {
                  return this._count;
                }
              }, {
                key: "flags",
                get: function get() {
                  return this._flags;
                }
              }]);

              return Buffer;
            }(Obj);

            var CommandBuffer = function (_Obj) {
              _inheritsLoose(CommandBuffer, _Obj);

              function CommandBuffer(device) {
                var _this;

                _this = _Obj.call(this, ObjectType.COMMAND_BUFFER) || this;
                _this._device = void 0;
                _this._queue = null;
                _this._type = CommandBufferType.PRIMARY;
                _this._numDrawCalls = 0;
                _this._numInstances = 0;
                _this._numTris = 0;
                _this._device = device;
                return _this;
              }

              _createClass(CommandBuffer, [{
                key: "type",
                get: function get() {
                  return this._type;
                }
              }, {
                key: "queue",
                get: function get() {
                  return this._queue;
                }
              }, {
                key: "numDrawCalls",
                get: function get() {
                  return this._numDrawCalls;
                }
              }, {
                key: "numInstances",
                get: function get() {
                  return this._numInstances;
                }
              }, {
                key: "numTris",
                get: function get() {
                  return this._numTris;
                }
              }]);

              return CommandBuffer;
            }(Obj);

            ccenum(Format);
            var Device = function () {
              function Device() {
                this._canvas = null;
                this._canvas2D = null;
                this._gfxAPI = API.UNKNOWN;
                this._transform = SurfaceTransform.IDENTITY;
                this._deviceName = '';
                this._renderer = '';
                this._vendor = '';
                this._version = '';
                this._features = new Array(Feature.COUNT);
                this._queue = null;
                this._cmdBuff = null;
                this._devicePixelRatio = 1.0;
                this._width = 0;
                this._height = 0;
                this._nativeWidth = 0;
                this._nativeHeight = 0;
                this._colorFmt = Format.UNKNOWN;
                this._depthStencilFmt = Format.UNKNOWN;
                this._numDrawCalls = 0;
                this._numInstances = 0;
                this._numTris = 0;
                this._memoryStatus = new MemoryStatus();
                this._caps = new DeviceCaps();
              }

              var _proto = Device.prototype;

              _proto.hasFeature = function hasFeature(feature) {
                return this._features[feature];
              };

              _createClass(Device, [{
                key: "canvas",
                get: function get() {
                  return this._canvas;
                }
              }, {
                key: "canvas2D",
                get: function get() {
                  return this._canvas2D;
                }
              }, {
                key: "gfxAPI",
                get: function get() {
                  return this._gfxAPI;
                }
              }, {
                key: "queue",
                get: function get() {
                  return this._queue;
                }
              }, {
                key: "commandBuffer",
                get: function get() {
                  return this._cmdBuff;
                }
              }, {
                key: "devicePixelRatio",
                get: function get() {
                  return this._devicePixelRatio;
                }
              }, {
                key: "width",
                get: function get() {
                  return this._width;
                }
              }, {
                key: "height",
                get: function get() {
                  return this._height;
                }
              }, {
                key: "nativeWidth",
                get: function get() {
                  return this._nativeWidth;
                }
              }, {
                key: "nativeHeight",
                get: function get() {
                  return this._nativeHeight;
                }
              }, {
                key: "renderer",
                get: function get() {
                  return this._renderer;
                }
              }, {
                key: "vendor",
                get: function get() {
                  return this._vendor;
                }
              }, {
                key: "colorFormat",
                get: function get() {
                  return this._colorFmt;
                }
              }, {
                key: "depthStencilFormat",
                get: function get() {
                  return this._depthStencilFmt;
                }
              }, {
                key: "numDrawCalls",
                get: function get() {
                  return this._numDrawCalls;
                }
              }, {
                key: "numInstances",
                get: function get() {
                  return this._numInstances;
                }
              }, {
                key: "numTris",
                get: function get() {
                  return this._numTris;
                }
              }, {
                key: "memoryStatus",
                get: function get() {
                  return this._memoryStatus;
                }
              }, {
                key: "capabilities",
                get: function get() {
                  return this._caps;
                }
              }, {
                key: "surfaceTransform",
                get: function get() {
                  return this._transform;
                }
              }]);

              return Device;
            }();

            var Framebuffer = function (_Obj) {
              _inheritsLoose(Framebuffer, _Obj);

              function Framebuffer(device) {
                var _this;

                _this = _Obj.call(this, ObjectType.FRAMEBUFFER) || this;
                _this._device = void 0;
                _this._renderPass = null;
                _this._colorTextures = [];
                _this._depthStencilTexture = null;
                _this._device = device;
                return _this;
              }

              _createClass(Framebuffer, [{
                key: "renderPass",
                get: function get() {
                  return this._renderPass;
                }
              }, {
                key: "colorTextures",
                get: function get() {
                  return this._colorTextures;
                }
              }, {
                key: "depthStencilTexture",
                get: function get() {
                  return this._depthStencilTexture;
                }
              }]);

              return Framebuffer;
            }(Obj);

            var getUint8ForString = String.prototype.charCodeAt;

            function getUint8ForArray(idx) {
              return this[idx];
            }

            function murmurhash2_32_gc(input, seed) {
              var l = input.length;
              var h = seed ^ l;
              var i = 0;
              var getUint8 = typeof input === 'string' ? getUint8ForString : getUint8ForArray;

              while (l >= 4) {
                var k = getUint8.call(input, i) & 0xff | (getUint8.call(input, ++i) & 0xff) << 8 | (getUint8.call(input, ++i) & 0xff) << 16 | (getUint8.call(input, ++i) & 0xff) << 24;
                k = (k & 0xffff) * 0x5bd1e995 + (((k >>> 16) * 0x5bd1e995 & 0xffff) << 16);
                k ^= k >>> 24;
                k = (k & 0xffff) * 0x5bd1e995 + (((k >>> 16) * 0x5bd1e995 & 0xffff) << 16);
                h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16) ^ k;
                l -= 4;
                ++i;
              }

              switch (l) {
                case 3:
                  h ^= (getUint8.call(input, i + 2) & 0xff) << 16;

                case 2:
                  h ^= (getUint8.call(input, i + 1) & 0xff) << 8;

                case 1:
                  h ^= getUint8.call(input, i) & 0xff;
                  h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16);
              }

              h ^= h >>> 13;
              h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16);
              h ^= h >>> 15;
              return h >>> 0;
            }

            var InputAssembler = function (_Obj) {
              _inheritsLoose(InputAssembler, _Obj);

              function InputAssembler(device) {
                var _this;

                _this = _Obj.call(this, ObjectType.INPUT_ASSEMBLER) || this;
                _this._device = void 0;
                _this._attributes = [];
                _this._vertexBuffers = [];
                _this._indexBuffer = null;
                _this._vertexCount = 0;
                _this._firstVertex = 0;
                _this._indexCount = 0;
                _this._firstIndex = 0;
                _this._vertexOffset = 0;
                _this._instanceCount = 0;
                _this._firstInstance = 0;
                _this._attributesHash = 0;
                _this._indirectBuffer = null;
                _this._device = device;
                return _this;
              }

              var _proto = InputAssembler.prototype;

              _proto.getVertexBuffer = function getVertexBuffer(stream) {
                if (stream === void 0) {
                  stream = 0;
                }

                if (stream < this._vertexBuffers.length) {
                  return this._vertexBuffers[stream];
                } else {
                  return null;
                }
              };

              _proto.computeAttributesHash = function computeAttributesHash() {
                var res = 'attrs';

                for (var i = 0; i < this.attributes.length; ++i) {
                  var at = this.attributes[i];
                  res += "," + at.name + "," + at.format + "," + at.isNormalized + "," + at.stream + "," + at.isInstanced;
                }

                return murmurhash2_32_gc(res, 666);
              };

              _createClass(InputAssembler, [{
                key: "vertexBuffers",
                get: function get() {
                  return this._vertexBuffers;
                }
              }, {
                key: "indexBuffer",
                get: function get() {
                  return this._indexBuffer;
                }
              }, {
                key: "attributes",
                get: function get() {
                  return this._attributes;
                }
              }, {
                key: "attributesHash",
                get: function get() {
                  return this._attributesHash;
                }
              }, {
                key: "vertexCount",
                get: function get() {
                  return this._vertexCount;
                },
                set: function set(count) {
                  this._vertexCount = count;
                }
              }, {
                key: "firstVertex",
                get: function get() {
                  return this._firstVertex;
                },
                set: function set(first) {
                  this._firstVertex = first;
                }
              }, {
                key: "indexCount",
                get: function get() {
                  return this._indexCount;
                },
                set: function set(count) {
                  this._indexCount = count;
                }
              }, {
                key: "firstIndex",
                get: function get() {
                  return this._firstIndex;
                },
                set: function set(first) {
                  this._firstIndex = first;
                }
              }, {
                key: "vertexOffset",
                get: function get() {
                  return this._vertexOffset;
                },
                set: function set(offset) {
                  this._vertexOffset = offset;
                }
              }, {
                key: "instanceCount",
                get: function get() {
                  return this._instanceCount;
                },
                set: function set(count) {
                  this._instanceCount = count;
                }
              }, {
                key: "firstInstance",
                get: function get() {
                  return this._firstInstance;
                },
                set: function set(first) {
                  this._firstInstance = first;
                }
              }, {
                key: "indirectBuffer",
                get: function get() {
                  return this._indirectBuffer;
                }
              }]);

              return InputAssembler;
            }(Obj);

            var DescriptorSet = function (_Obj) {
              _inheritsLoose(DescriptorSet, _Obj);

              function DescriptorSet(device) {
                var _this;

                _this = _Obj.call(this, ObjectType.DESCRIPTOR_SET) || this;
                _this._device = void 0;
                _this._layout = null;
                _this._buffers = [];
                _this._textures = [];
                _this._samplers = [];
                _this._isDirty = false;
                _this._device = device;
                return _this;
              }

              var _proto = DescriptorSet.prototype;

              _proto.bindBuffer = function bindBuffer(binding, buffer, index) {
                if (index === void 0) {
                  index = 0;
                }

                var bindingIndex = this._layout.bindingIndices[binding];
                var info = this._layout.bindings[bindingIndex];

                if (!info) {
                  return;
                }

                if (info.descriptorType & DESCRIPTOR_BUFFER_TYPE) {
                  var descriptorIndex = this._layout.descriptorIndices[binding];

                  if (this._buffers[descriptorIndex + index] !== buffer) {
                    this._buffers[descriptorIndex + index] = buffer;
                    this._isDirty = true;
                  }
                }
              };

              _proto.bindSampler = function bindSampler(binding, sampler, index) {
                if (index === void 0) {
                  index = 0;
                }

                var bindingIndex = this._layout.bindingIndices[binding];
                var info = this._layout.bindings[bindingIndex];

                if (!info) {
                  return;
                }

                if (info.descriptorType & DESCRIPTOR_SAMPLER_TYPE) {
                  var descriptorIndex = this._layout.descriptorIndices[binding];

                  if (this._samplers[descriptorIndex + index] !== sampler) {
                    this._samplers[descriptorIndex + index] = sampler;
                    this._isDirty = true;
                  }
                }
              };

              _proto.bindTexture = function bindTexture(binding, texture, index) {
                if (index === void 0) {
                  index = 0;
                }

                var bindingIndex = this._layout.bindingIndices[binding];
                var info = this._layout.bindings[bindingIndex];

                if (!info) {
                  return;
                }

                if (info.descriptorType & DESCRIPTOR_SAMPLER_TYPE) {
                  var descriptorIndex = this._layout.descriptorIndices[binding];

                  if (this._textures[descriptorIndex + index] !== texture) {
                    this._textures[descriptorIndex + index] = texture;
                    this._isDirty = true;
                  }
                }
              };

              _proto.getBuffer = function getBuffer(binding, index) {
                if (index === void 0) {
                  index = 0;
                }

                var descriptorIndex = this._layout.descriptorIndices[binding];
                return this._buffers[descriptorIndex + index];
              };

              _proto.getSampler = function getSampler(binding, index) {
                if (index === void 0) {
                  index = 0;
                }

                var descriptorIndex = this._layout.descriptorIndices[binding];
                return this._samplers[descriptorIndex + index];
              };

              _proto.getTexture = function getTexture(binding, index) {
                if (index === void 0) {
                  index = 0;
                }

                var descriptorIndex = this._layout.descriptorIndices[binding];
                return this._textures[descriptorIndex + index];
              };

              _createClass(DescriptorSet, [{
                key: "layout",
                get: function get() {
                  return this._layout;
                }
              }]);

              return DescriptorSet;
            }(Obj);

            var DescriptorSetLayout = function (_Obj) {
              _inheritsLoose(DescriptorSetLayout, _Obj);

              function DescriptorSetLayout(device) {
                var _this;

                _this = _Obj.call(this, ObjectType.DESCRIPTOR_SET_LAYOUT) || this;
                _this._device = void 0;
                _this._bindings = [];
                _this._bindingIndices = [];
                _this._descriptorIndices = [];
                _this._device = device;
                return _this;
              }

              _createClass(DescriptorSetLayout, [{
                key: "bindings",
                get: function get() {
                  return this._bindings;
                }
              }, {
                key: "bindingIndices",
                get: function get() {
                  return this._bindingIndices;
                }
              }, {
                key: "descriptorIndices",
                get: function get() {
                  return this._descriptorIndices;
                }
              }]);

              return DescriptorSetLayout;
            }(Obj);

            var PipelineLayout = function (_Obj) {
              _inheritsLoose(PipelineLayout, _Obj);

              function PipelineLayout(device) {
                var _this;

                _this = _Obj.call(this, ObjectType.PIPELINE_LAYOUT) || this;
                _this._device = void 0;
                _this._setLayouts = [];
                _this._device = device;
                return _this;
              }

              _createClass(PipelineLayout, [{
                key: "setLayouts",
                get: function get() {
                  return this._setLayouts;
                }
              }]);

              return PipelineLayout;
            }(Obj);

            var RasterizerState = function () {
              function RasterizerState(isDiscard, polygonMode, shadeModel, cullMode, isFrontFaceCCW, depthBiasEnabled, depthBias, depthBiasClamp, depthBiasSlop, isDepthClip, isMultisample, lineWidth) {
                if (isDiscard === void 0) {
                  isDiscard = false;
                }

                if (polygonMode === void 0) {
                  polygonMode = PolygonMode.FILL;
                }

                if (shadeModel === void 0) {
                  shadeModel = ShadeModel.GOURAND;
                }

                if (cullMode === void 0) {
                  cullMode = CullMode.BACK;
                }

                if (isFrontFaceCCW === void 0) {
                  isFrontFaceCCW = true;
                }

                if (depthBiasEnabled === void 0) {
                  depthBiasEnabled = false;
                }

                if (depthBias === void 0) {
                  depthBias = 0;
                }

                if (depthBiasClamp === void 0) {
                  depthBiasClamp = 0.0;
                }

                if (depthBiasSlop === void 0) {
                  depthBiasSlop = 0.0;
                }

                if (isDepthClip === void 0) {
                  isDepthClip = true;
                }

                if (isMultisample === void 0) {
                  isMultisample = false;
                }

                if (lineWidth === void 0) {
                  lineWidth = 1.0;
                }

                this.isDiscard = isDiscard;
                this.polygonMode = polygonMode;
                this.shadeModel = shadeModel;
                this.cullMode = cullMode;
                this.isFrontFaceCCW = isFrontFaceCCW;
                this.depthBiasEnabled = depthBiasEnabled;
                this.depthBias = depthBias;
                this.depthBiasClamp = depthBiasClamp;
                this.depthBiasSlop = depthBiasSlop;
                this.isDepthClip = isDepthClip;
                this.isMultisample = isMultisample;
                this.lineWidth = lineWidth;
              }

              var _proto = RasterizerState.prototype;

              _proto.reset = function reset() {
                this.isDiscard = false;
                this.polygonMode = PolygonMode.FILL;
                this.shadeModel = ShadeModel.GOURAND;
                this.cullMode = CullMode.BACK;
                this.isFrontFaceCCW = true;
                this.depthBiasEnabled = false;
                this.depthBias = 0;
                this.depthBiasClamp = 0.0;
                this.depthBiasSlop = 0.0;
                this.isDepthClip = true;
                this.isMultisample = false;
                this.lineWidth = 1.0;
              };

              _proto.assign = function assign(rs) {
                Object.assign(this, rs);
              };

              _proto.destroy = function destroy() {};

              _createClass(RasterizerState, [{
                key: "handle",
                get: function get() {
                  return NULL_HANDLE;
                }
              }]);

              return RasterizerState;
            }();
            var DepthStencilState = function () {
              function DepthStencilState(depthTest, depthWrite, depthFunc, stencilTestFront, stencilFuncFront, stencilReadMaskFront, stencilWriteMaskFront, stencilFailOpFront, stencilZFailOpFront, stencilPassOpFront, stencilRefFront, stencilTestBack, stencilFuncBack, stencilReadMaskBack, stencilWriteMaskBack, stencilFailOpBack, stencilZFailOpBack, stencilPassOpBack, stencilRefBack) {
                if (depthTest === void 0) {
                  depthTest = true;
                }

                if (depthWrite === void 0) {
                  depthWrite = true;
                }

                if (depthFunc === void 0) {
                  depthFunc = ComparisonFunc.LESS;
                }

                if (stencilTestFront === void 0) {
                  stencilTestFront = false;
                }

                if (stencilFuncFront === void 0) {
                  stencilFuncFront = ComparisonFunc.ALWAYS;
                }

                if (stencilReadMaskFront === void 0) {
                  stencilReadMaskFront = 0xffff;
                }

                if (stencilWriteMaskFront === void 0) {
                  stencilWriteMaskFront = 0xffff;
                }

                if (stencilFailOpFront === void 0) {
                  stencilFailOpFront = StencilOp.KEEP;
                }

                if (stencilZFailOpFront === void 0) {
                  stencilZFailOpFront = StencilOp.KEEP;
                }

                if (stencilPassOpFront === void 0) {
                  stencilPassOpFront = StencilOp.KEEP;
                }

                if (stencilRefFront === void 0) {
                  stencilRefFront = 1;
                }

                if (stencilTestBack === void 0) {
                  stencilTestBack = false;
                }

                if (stencilFuncBack === void 0) {
                  stencilFuncBack = ComparisonFunc.ALWAYS;
                }

                if (stencilReadMaskBack === void 0) {
                  stencilReadMaskBack = 0xffff;
                }

                if (stencilWriteMaskBack === void 0) {
                  stencilWriteMaskBack = 0xffff;
                }

                if (stencilFailOpBack === void 0) {
                  stencilFailOpBack = StencilOp.KEEP;
                }

                if (stencilZFailOpBack === void 0) {
                  stencilZFailOpBack = StencilOp.KEEP;
                }

                if (stencilPassOpBack === void 0) {
                  stencilPassOpBack = StencilOp.KEEP;
                }

                if (stencilRefBack === void 0) {
                  stencilRefBack = 1;
                }

                this.depthTest = depthTest;
                this.depthWrite = depthWrite;
                this.depthFunc = depthFunc;
                this.stencilTestFront = stencilTestFront;
                this.stencilFuncFront = stencilFuncFront;
                this.stencilReadMaskFront = stencilReadMaskFront;
                this.stencilWriteMaskFront = stencilWriteMaskFront;
                this.stencilFailOpFront = stencilFailOpFront;
                this.stencilZFailOpFront = stencilZFailOpFront;
                this.stencilPassOpFront = stencilPassOpFront;
                this.stencilRefFront = stencilRefFront;
                this.stencilTestBack = stencilTestBack;
                this.stencilFuncBack = stencilFuncBack;
                this.stencilReadMaskBack = stencilReadMaskBack;
                this.stencilWriteMaskBack = stencilWriteMaskBack;
                this.stencilFailOpBack = stencilFailOpBack;
                this.stencilZFailOpBack = stencilZFailOpBack;
                this.stencilPassOpBack = stencilPassOpBack;
                this.stencilRefBack = stencilRefBack;
              }

              var _proto2 = DepthStencilState.prototype;

              _proto2.reset = function reset() {
                this.depthTest = true;
                this.depthWrite = true;
                this.depthFunc = ComparisonFunc.LESS;
                this.stencilTestFront = false;
                this.stencilFuncFront = ComparisonFunc.ALWAYS;
                this.stencilReadMaskFront = 0xffff;
                this.stencilWriteMaskFront = 0xffff;
                this.stencilFailOpFront = StencilOp.KEEP;
                this.stencilZFailOpFront = StencilOp.KEEP;
                this.stencilPassOpFront = StencilOp.KEEP;
                this.stencilRefFront = 1;
                this.stencilTestBack = false;
                this.stencilFuncBack = ComparisonFunc.ALWAYS;
                this.stencilReadMaskBack = 0xffff;
                this.stencilWriteMaskBack = 0xffff;
                this.stencilFailOpBack = StencilOp.KEEP;
                this.stencilZFailOpBack = StencilOp.KEEP;
                this.stencilPassOpBack = StencilOp.KEEP;
                this.stencilRefBack = 1;
              };

              _proto2.assign = function assign(dss) {
                Object.assign(this, dss);
              };

              _proto2.destroy = function destroy() {};

              _createClass(DepthStencilState, [{
                key: "handle",
                get: function get() {
                  return NULL_HANDLE;
                }
              }]);

              return DepthStencilState;
            }();
            var BlendTarget = function () {
              function BlendTarget(blend, blendSrc, blendDst, blendEq, blendSrcAlpha, blendDstAlpha, blendAlphaEq, blendColorMask) {
                if (blend === void 0) {
                  blend = false;
                }

                if (blendSrc === void 0) {
                  blendSrc = BlendFactor.ONE;
                }

                if (blendDst === void 0) {
                  blendDst = BlendFactor.ZERO;
                }

                if (blendEq === void 0) {
                  blendEq = BlendOp.ADD;
                }

                if (blendSrcAlpha === void 0) {
                  blendSrcAlpha = BlendFactor.ONE;
                }

                if (blendDstAlpha === void 0) {
                  blendDstAlpha = BlendFactor.ZERO;
                }

                if (blendAlphaEq === void 0) {
                  blendAlphaEq = BlendOp.ADD;
                }

                if (blendColorMask === void 0) {
                  blendColorMask = ColorMask.ALL;
                }

                this.blend = blend;
                this.blendSrc = blendSrc;
                this.blendDst = blendDst;
                this.blendEq = blendEq;
                this.blendSrcAlpha = blendSrcAlpha;
                this.blendDstAlpha = blendDstAlpha;
                this.blendAlphaEq = blendAlphaEq;
                this.blendColorMask = blendColorMask;
              }

              var _proto3 = BlendTarget.prototype;

              _proto3.reset = function reset() {
                this.blend = false;
                this.blendSrc = BlendFactor.ONE;
                this.blendDst = BlendFactor.ZERO;
                this.blendEq = BlendOp.ADD;
                this.blendSrcAlpha = BlendFactor.ONE;
                this.blendDstAlpha = BlendFactor.ZERO;
                this.blendAlphaEq = BlendOp.ADD;
                this.blendColorMask = ColorMask.ALL;
              };

              _proto3.assign = function assign(target) {
                Object.assign(this, target);
              };

              _proto3.destroy = function destroy() {};

              _createClass(BlendTarget, [{
                key: "handle",
                get: function get() {
                  return NULL_HANDLE;
                }
              }]);

              return BlendTarget;
            }();
            var BlendState = function () {
              function BlendState(isA2C, isIndepend, blendColor, targets) {
                if (isA2C === void 0) {
                  isA2C = false;
                }

                if (isIndepend === void 0) {
                  isIndepend = false;
                }

                if (blendColor === void 0) {
                  blendColor = new Color$1();
                }

                if (targets === void 0) {
                  targets = [new BlendTarget()];
                }

                this.isA2C = isA2C;
                this.isIndepend = isIndepend;
                this.blendColor = blendColor;
                this.targets = targets;
              }

              var _proto4 = BlendState.prototype;

              _proto4.setTarget = function setTarget(index, target) {
                var tg = this.targets[index];

                if (!tg) {
                  tg = this.targets[index] = new BlendTarget();
                }

                Object.assign(tg, target);
              };

              _proto4.reset = function reset() {
                this.isA2C = false;
                this.isIndepend = false;
                this.blendColor.x = 0;
                this.blendColor.y = 0;
                this.blendColor.z = 0;
                this.blendColor.w = 0;
                this.targets.length = 1;
                this.targets[0].reset();
              };

              _proto4.destroy = function destroy() {};

              _createClass(BlendState, [{
                key: "handle",
                get: function get() {
                  return NULL_HANDLE;
                }
              }]);

              return BlendState;
            }();
            var PipelineStateInfo = function PipelineStateInfo(shader, pipelineLayout, renderPass, inputState, rasterizerState, depthStencilState, blendState, primitive, dynamicStates, bindPoint) {
              if (shader === void 0) {
                shader = null;
              }

              if (pipelineLayout === void 0) {
                pipelineLayout = null;
              }

              if (renderPass === void 0) {
                renderPass = null;
              }

              if (inputState === void 0) {
                inputState = new InputState();
              }

              if (rasterizerState === void 0) {
                rasterizerState = new RasterizerState();
              }

              if (depthStencilState === void 0) {
                depthStencilState = new DepthStencilState();
              }

              if (blendState === void 0) {
                blendState = new BlendState();
              }

              if (primitive === void 0) {
                primitive = PrimitiveMode.TRIANGLE_LIST;
              }

              if (dynamicStates === void 0) {
                dynamicStates = DynamicStateFlagBit.NONE;
              }

              if (bindPoint === void 0) {
                bindPoint = PipelineBindPoint.GRAPHICS;
              }

              this.shader = shader;
              this.pipelineLayout = pipelineLayout;
              this.renderPass = renderPass;
              this.inputState = inputState;
              this.rasterizerState = rasterizerState;
              this.depthStencilState = depthStencilState;
              this.blendState = blendState;
              this.primitive = primitive;
              this.dynamicStates = dynamicStates;
              this.bindPoint = bindPoint;
            };
            var PipelineState = function (_Obj) {
              _inheritsLoose(PipelineState, _Obj);

              function PipelineState(device) {
                var _this;

                _this = _Obj.call(this, ObjectType.PIPELINE_STATE) || this;
                _this._device = void 0;
                _this._shader = null;
                _this._pipelineLayout = null;
                _this._primitive = PrimitiveMode.TRIANGLE_LIST;
                _this._is = null;
                _this._rs = new RasterizerState();
                _this._dss = new DepthStencilState();
                _this._bs = new BlendState();
                _this._dynamicStates = DynamicStateFlagBit.NONE;
                _this._renderPass = null;
                _this._device = device;
                return _this;
              }

              _createClass(PipelineState, [{
                key: "shader",
                get: function get() {
                  return this._shader;
                }
              }, {
                key: "pipelineLayout",
                get: function get() {
                  return this._pipelineLayout;
                }
              }, {
                key: "primitive",
                get: function get() {
                  return this._primitive;
                }
              }, {
                key: "rasterizerState",
                get: function get() {
                  return this._rs;
                }
              }, {
                key: "depthStencilState",
                get: function get() {
                  return this._dss;
                }
              }, {
                key: "blendState",
                get: function get() {
                  return this._bs;
                }
              }, {
                key: "inputState",
                get: function get() {
                  return this._is;
                }
              }, {
                key: "dynamicStates",
                get: function get() {
                  return this._dynamicStates;
                }
              }, {
                key: "renderPass",
                get: function get() {
                  return this._renderPass;
                }
              }]);

              return PipelineState;
            }(Obj);

            var Queue = function (_Obj) {
              _inheritsLoose(Queue, _Obj);

              function Queue(device) {
                var _this;

                _this = _Obj.call(this, ObjectType.QUEUE) || this;
                _this._device = void 0;
                _this._type = QueueType.GRAPHICS;
                _this._isAsync = false;
                _this._device = device;
                return _this;
              }

              var _proto = Queue.prototype;

              _proto.isAsync = function isAsync() {
                return this._isAsync;
              };

              _createClass(Queue, [{
                key: "type",
                get: function get() {
                  return this._type;
                }
              }]);

              return Queue;
            }(Obj);

            var RenderPass = function (_Obj) {
              _inheritsLoose(RenderPass, _Obj);

              function RenderPass(device) {
                var _this;

                _this = _Obj.call(this, ObjectType.RENDER_PASS) || this;
                _this._device = void 0;
                _this._colorInfos = [];
                _this._depthStencilInfo = null;
                _this._subpasses = [];
                _this._hash = 0;
                _this._device = device;
                return _this;
              }

              var _proto = RenderPass.prototype;

              _proto.computeHash = function computeHash() {
                var res = '';

                if (this._subpasses.length) {
                  for (var i = 0; i < this._subpasses.length; ++i) {
                    var subpass = this._subpasses[i];

                    if (subpass.inputs.length) {
                      res += 'ia';

                      for (var j = 0; j < subpass.inputs.length; ++j) {
                        var ia = this._colorInfos[subpass.inputs[j]];
                        res += "," + ia.format + "," + ia.sampleCount;
                      }
                    }

                    if (subpass.colors.length) {
                      res += 'ca';

                      for (var _j = 0; _j < subpass.inputs.length; ++_j) {
                        var ca = this._colorInfos[subpass.inputs[_j]];
                        res += "," + ca.format + "," + ca.sampleCount;
                      }
                    }

                    if (subpass.depthStencil >= 0) {
                      var ds = this._colorInfos[subpass.depthStencil];
                      res += "ds," + ds.format + "," + ds.sampleCount;
                    }
                  }
                } else {
                  res += 'ca';

                  for (var _i = 0; _i < this._colorInfos.length; ++_i) {
                    var _ca = this._colorInfos[_i];
                    res += "," + _ca.format + "," + _ca.sampleCount;
                  }

                  var _ds = this._depthStencilInfo;

                  if (_ds) {
                    res += "ds," + _ds.format + "," + _ds.sampleCount;
                  }
                }

                return murmurhash2_32_gc(res, 666);
              };

              _createClass(RenderPass, [{
                key: "colorAttachments",
                get: function get() {
                  return this._colorInfos;
                }
              }, {
                key: "depthStencilAttachment",
                get: function get() {
                  return this._depthStencilInfo;
                }
              }, {
                key: "subPasses",
                get: function get() {
                  return this._subpasses;
                }
              }, {
                key: "hash",
                get: function get() {
                  return this._hash;
                }
              }]);

              return RenderPass;
            }(Obj);

            var Sampler = function (_Obj) {
              _inheritsLoose(Sampler, _Obj);

              function Sampler(device) {
                var _this;

                _this = _Obj.call(this, ObjectType.SAMPLER) || this;
                _this._device = void 0;
                _this._minFilter = Filter.LINEAR;
                _this._magFilter = Filter.LINEAR;
                _this._mipFilter = Filter.NONE;
                _this._addressU = Address.WRAP;
                _this._addressV = Address.WRAP;
                _this._addressW = Address.WRAP;
                _this._maxAnisotropy = 16;
                _this._cmpFunc = ComparisonFunc.NEVER;
                _this._borderColor = new Color$1();
                _this._mipLODBias = 0.0;
                _this._device = device;
                return _this;
              }

              _createClass(Sampler, [{
                key: "minFilter",
                get: function get() {
                  return this._minFilter;
                }
              }, {
                key: "magFilter",
                get: function get() {
                  return this._magFilter;
                }
              }, {
                key: "mipFilter",
                get: function get() {
                  return this._mipFilter;
                }
              }, {
                key: "addressU",
                get: function get() {
                  return this._addressU;
                }
              }, {
                key: "addressV",
                get: function get() {
                  return this._addressV;
                }
              }, {
                key: "addressW",
                get: function get() {
                  return this._addressW;
                }
              }, {
                key: "maxAnisotropy",
                get: function get() {
                  return this._maxAnisotropy;
                }
              }, {
                key: "cmpFunc",
                get: function get() {
                  return this._cmpFunc;
                }
              }, {
                key: "borderColor",
                get: function get() {
                  return this._borderColor;
                }
              }, {
                key: "mipLODBias",
                get: function get() {
                  return this._mipLODBias;
                }
              }]);

              return Sampler;
            }(Obj);

            var Shader = function (_Obj) {
              _inheritsLoose(Shader, _Obj);

              function Shader(device) {
                var _this;

                _this = _Obj.call(this, ObjectType.SHADER) || this;
                _this._device = void 0;
                _this._id = void 0;
                _this._name = '';
                _this._stages = [];
                _this._attributes = [];
                _this._blocks = [];
                _this._samplers = [];
                _this._device = device;
                _this._id = Shader._shaderIdGen++;
                return _this;
              }

              _createClass(Shader, [{
                key: "id",
                get: function get() {
                  return this._id;
                }
              }, {
                key: "name",
                get: function get() {
                  return this._name;
                }
              }, {
                key: "attributes",
                get: function get() {
                  return this._attributes;
                }
              }, {
                key: "blocks",
                get: function get() {
                  return this._blocks;
                }
              }, {
                key: "samplers",
                get: function get() {
                  return this._samplers;
                }
              }]);

              return Shader;
            }(Obj);
            Shader._shaderIdGen = 0;

            var Texture = function (_Obj) {
              _inheritsLoose(Texture, _Obj);

              function Texture(device) {
                var _this;

                _this = _Obj.call(this, ObjectType.TEXTURE) || this;
                _this._device = void 0;
                _this._type = TextureType.TEX2D;
                _this._usage = TextureUsageBit.NONE;
                _this._format = Format.UNKNOWN;
                _this._width = 0;
                _this._height = 0;
                _this._depth = 1;
                _this._layerCount = 1;
                _this._levelCount = 1;
                _this._samples = SampleCount.X1;
                _this._flags = TextureFlagBit.NONE;
                _this._isPowerOf2 = false;
                _this._size = 0;
                _this._device = device;
                return _this;
              }

              _createClass(Texture, [{
                key: "type",
                get: function get() {
                  return this._type;
                }
              }, {
                key: "usage",
                get: function get() {
                  return this._usage;
                }
              }, {
                key: "format",
                get: function get() {
                  return this._format;
                }
              }, {
                key: "width",
                get: function get() {
                  return this._width;
                }
              }, {
                key: "height",
                get: function get() {
                  return this._height;
                }
              }, {
                key: "depth",
                get: function get() {
                  return this._depth;
                }
              }, {
                key: "layerCount",
                get: function get() {
                  return this._layerCount;
                }
              }, {
                key: "levelCount",
                get: function get() {
                  return this._levelCount;
                }
              }, {
                key: "samples",
                get: function get() {
                  return this._samples;
                }
              }, {
                key: "flags",
                get: function get() {
                  return this._flags;
                }
              }, {
                key: "size",
                get: function get() {
                  return this._size;
                }
              }]);

              return Texture;
            }(Obj);

            var GlobalBarrier = function (_Obj) {
              _inheritsLoose(GlobalBarrier, _Obj);

              function GlobalBarrier(device) {
                var _this;

                _this = _Obj.call(this, ObjectType.GLOBAL_BARRIER) || this;
                _this._device = void 0;
                _this._info = new GlobalBarrierInfo();
                _this._device = device;
                return _this;
              }

              var _proto = GlobalBarrier.prototype;

              _proto.initialize = function initialize(info) {
                this._info.copy(info);

                return true;
              };

              return GlobalBarrier;
            }(Obj);

            var TextureBarrier = function (_Obj) {
              _inheritsLoose(TextureBarrier, _Obj);

              function TextureBarrier(device) {
                var _this;

                _this = _Obj.call(this, ObjectType.TEXTURE_BARRIER) || this;
                _this._device = void 0;
                _this._info = new TextureBarrierInfo();
                _this._device = device;
                return _this;
              }

              var _proto = TextureBarrier.prototype;

              _proto.initialize = function initialize(info) {
                this._info.copy(info);

                return true;
              };

              return TextureBarrier;
            }(Obj);

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

            var customMappings = {
              Obj: 'GFXObject',
              DRAW_INFO_SIZE: 'GFX_DRAW_INFO_SIZE',
              DESCRIPTOR_BUFFER_TYPE: '',
              DESCRIPTOR_SAMPLER_TYPE: '',
              DESCRIPTOR_DYNAMIC_TYPE: '',
              getTypedArrayConstructor: ''
            };

            for (var api in legacyCC.gfx) {
              if (api === '__esModule') continue;
              var deprecated = customMappings[api];

              if (deprecated === '') {
                deprecated = api;
              } else if (deprecated === undefined) {
                deprecated = "GFX" + api;
              }

              replaceProperty(legacyCC, 'cc', [{
                name: deprecated,
                newName: api,
                target: legacyCC.gfx,
                targetName: 'cc.gfx'
              }]);
            }

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

            var ERaycastMode;

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

            var rayPlane = function () {
              var pt = new Vec3(0, 0, 0);
              return function (ray, plane) {
                var denom = Vec3.dot(ray.d, plane.n);

                if (Math.abs(denom) < Number.EPSILON) {
                  return 0;
                }

                Vec3.multiplyScalar(pt, plane.n, plane.d);
                var t = Vec3.dot(Vec3.subtract(pt, pt, ray.o), plane.n) / denom;

                if (t < 0) {
                  return 0;
                }

                return t;
              };
            }();

            var rayTriangle = function () {
              var ab = new Vec3(0, 0, 0);
              var ac = new Vec3(0, 0, 0);
              var pvec = new Vec3(0, 0, 0);
              var tvec = new Vec3(0, 0, 0);
              var qvec = new Vec3(0, 0, 0);
              return function (ray, triangle, doubleSided) {
                Vec3.subtract(ab, triangle.b, triangle.a);
                Vec3.subtract(ac, triangle.c, triangle.a);
                Vec3.cross(pvec, ray.d, ac);
                var det = Vec3.dot(ab, pvec);

                if (det < Number.EPSILON && (!doubleSided || det > -Number.EPSILON)) {
                  return 0;
                }

                var inv_det = 1 / det;
                Vec3.subtract(tvec, ray.o, triangle.a);
                var u = Vec3.dot(tvec, pvec) * inv_det;

                if (u < 0 || u > 1) {
                  return 0;
                }

                Vec3.cross(qvec, tvec, ab);
                var v = Vec3.dot(ray.d, qvec) * inv_det;

                if (v < 0 || u + v > 1) {
                  return 0;
                }

                var t = Vec3.dot(ac, qvec) * inv_det;
                return t < 0 ? 0 : t;
              };
            }();

            var raySphere = function () {
              var e = new Vec3(0, 0, 0);
              return function (ray, sphere) {
                var r = sphere.radius;
                var c = sphere.center;
                var o = ray.o;
                var d = ray.d;
                var rSq = r * r;
                Vec3.subtract(e, c, o);
                var eSq = e.lengthSqr();
                var aLength = Vec3.dot(e, d);
                var fSq = rSq - (eSq - aLength * aLength);

                if (fSq < 0) {
                  return 0;
                }

                var f = Math.sqrt(fSq);
                var t = eSq < rSq ? aLength + f : aLength - f;

                if (t < 0) {
                  return 0;
                }

                return t;
              };
            }();

            var rayAABB = function () {
              var min = new Vec3();
              var max = new Vec3();
              return function (ray, aabb) {
                Vec3.subtract(min, aabb.center, aabb.halfExtents);
                Vec3.add(max, aabb.center, aabb.halfExtents);
                return rayAABB2(ray, min, max);
              };
            }();

            function rayAABB2(ray, min, max) {
              var o = ray.o;
              var d = ray.d;
              var ix = 1 / d.x;
              var iy = 1 / d.y;
              var iz = 1 / d.z;
              var t1 = (min.x - o.x) * ix;
              var t2 = (max.x - o.x) * ix;
              var t3 = (min.y - o.y) * iy;
              var t4 = (max.y - o.y) * iy;
              var t5 = (min.z - o.z) * iz;
              var t6 = (max.z - o.z) * iz;
              var tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4)), Math.min(t5, t6));
              var tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4)), Math.max(t5, t6));

              if (tmax < 0 || tmin > tmax) {
                return 0;
              }

              return tmin > 0 ? tmin : tmax;
            }

            var rayOBB = function () {
              var center = new Vec3();
              var o = new Vec3();
              var d = new Vec3();
              var X = new Vec3();
              var Y = new Vec3();
              var Z = new Vec3();
              var p = new Vec3();
              var size = new Array(3);
              var f = new Array(3);
              var e = new Array(3);
              var t = new Array(6);
              return function (ray, obb) {
                size[0] = obb.halfExtents.x;
                size[1] = obb.halfExtents.y;
                size[2] = obb.halfExtents.z;
                center = obb.center;
                o = ray.o;
                d = ray.d;
                Vec3.set(X, obb.orientation.m00, obb.orientation.m01, obb.orientation.m02);
                Vec3.set(Y, obb.orientation.m03, obb.orientation.m04, obb.orientation.m05);
                Vec3.set(Z, obb.orientation.m06, obb.orientation.m07, obb.orientation.m08);
                Vec3.subtract(p, center, o);
                f[0] = Vec3.dot(X, d);
                f[1] = Vec3.dot(Y, d);
                f[2] = Vec3.dot(Z, d);
                e[0] = Vec3.dot(X, p);
                e[1] = Vec3.dot(Y, p);
                e[2] = Vec3.dot(Z, p);

                for (var i = 0; i < 3; ++i) {
                  if (f[i] === 0) {
                    if (-e[i] - size[i] > 0 || -e[i] + size[i] < 0) {
                      return 0;
                    }

                    f[i] = 0.0000001;
                  }

                  t[i * 2 + 0] = (e[i] + size[i]) / f[i];
                  t[i * 2 + 1] = (e[i] - size[i]) / f[i];
                }

                var tmin = Math.max(Math.max(Math.min(t[0], t[1]), Math.min(t[2], t[3])), Math.min(t[4], t[5]));
                var tmax = Math.min(Math.min(Math.max(t[0], t[1]), Math.max(t[2], t[3])), Math.max(t[4], t[5]));

                if (tmax < 0 || tmin > tmax) {
                  return 0;
                }

                return tmin > 0 ? tmin : tmax;
              };
            }();

            var rayCapsule = function () {
              var v3_0 = new Vec3();
              var v3_1 = new Vec3();
              var v3_2 = new Vec3();
              var v3_3 = new Vec3();
              var v3_4 = new Vec3();
              var v3_5 = new Vec3();
              var v3_6 = new Vec3();
              var sphere_0 = new Sphere();
              return function (ray, capsule) {
                var radiusSqr = capsule.radius * capsule.radius;
                var vRayNorm = Vec3.normalize(v3_0, ray.d);
                var A = capsule.ellipseCenter0;
                var B = capsule.ellipseCenter1;
                var BA = Vec3.subtract(v3_1, B, A);

                if (BA.equals(Vec3.ZERO)) {
                  sphere_0.radius = capsule.radius;
                  sphere_0.center.set(capsule.ellipseCenter0);
                  return intersect.raySphere(ray, sphere_0);
                }

                var O = ray.o;
                var OA = Vec3.subtract(v3_2, O, A);
                var VxBA = Vec3.cross(v3_3, vRayNorm, BA);
                var a = VxBA.lengthSqr();

                if (a === 0) {
                  sphere_0.radius = capsule.radius;
                  var BO = Vec3.subtract(v3_4, B, O);

                  if (OA.lengthSqr() < BO.lengthSqr()) {
                    sphere_0.center.set(capsule.ellipseCenter0);
                  } else {
                    sphere_0.center.set(capsule.ellipseCenter1);
                  }

                  return intersect.raySphere(ray, sphere_0);
                }

                var OAxBA = Vec3.cross(v3_4, OA, BA);
                var ab2 = BA.lengthSqr();
                var b = 2 * Vec3.dot(VxBA, OAxBA);
                var c = OAxBA.lengthSqr() - radiusSqr * ab2;
                var d = b * b - 4 * a * c;

                if (d < 0) {
                  return 0;
                }

                var t = (-b - Math.sqrt(d)) / (2 * a);

                if (t < 0) {
                  sphere_0.radius = capsule.radius;

                  var _BO = Vec3.subtract(v3_5, B, O);

                  if (OA.lengthSqr() < _BO.lengthSqr()) {
                    sphere_0.center.set(capsule.ellipseCenter0);
                  } else {
                    sphere_0.center.set(capsule.ellipseCenter1);
                  }

                  return intersect.raySphere(ray, sphere_0);
                } else {
                  var iPos = Vec3.scaleAndAdd(v3_5, ray.o, vRayNorm, t);
                  var iPosLen = Vec3.subtract(v3_6, iPos, A);
                  var tLimit = Vec3.dot(iPosLen, BA) / ab2;

                  if (tLimit >= 0 && tLimit <= 1) {
                    return t;
                  } else if (tLimit < 0) {
                    sphere_0.radius = capsule.radius;
                    sphere_0.center.set(capsule.ellipseCenter0);
                    return intersect.raySphere(ray, sphere_0);
                  } else if (tLimit > 1) {
                    sphere_0.radius = capsule.radius;
                    sphere_0.center.set(capsule.ellipseCenter1);
                    return intersect.raySphere(ray, sphere_0);
                  } else {
                    return 0;
                  }
                }
              };
            }();

            var raySubMesh = function () {
              var tri = Triangle.create();
              var deOpt = {
                distance: Infinity,
                doubleSided: false,
                mode: ERaycastMode.ANY
              };
              var minDis = 0;

              var fillResult = function fillResult(m, d, i0, i1, i2, r) {
                if (m === ERaycastMode.CLOSEST) {
                  if (minDis > d || minDis === 0) {
                    minDis = d;

                    if (r) {
                      if (r.length === 0) {
                        r.push({
                          distance: d,
                          vertexIndex0: i0 / 3,
                          vertexIndex1: i1 / 3,
                          vertexIndex2: i2 / 3
                        });
                      } else {
                        r[0].distance = d;
                        r[0].vertexIndex0 = i0 / 3;
                        r[0].vertexIndex1 = i1 / 3;
                        r[0].vertexIndex2 = i2 / 3;
                      }
                    }
                  }
                } else {
                  minDis = d;
                  if (r) r.push({
                    distance: d,
                    vertexIndex0: i0 / 3,
                    vertexIndex1: i1 / 3,
                    vertexIndex2: i2 / 3
                  });
                }
              };

              var narrowphase = function narrowphase(vb, ib, pm, ray, opt) {
                if (pm === PrimitiveMode.TRIANGLE_LIST) {
                  var cnt = ib.length;

                  for (var j = 0; j < cnt; j += 3) {
                    var i0 = ib[j] * 3;
                    var i1 = ib[j + 1] * 3;
                    var i2 = ib[j + 2] * 3;
                    Vec3.set(tri.a, vb[i0], vb[i0 + 1], vb[i0 + 2]);
                    Vec3.set(tri.b, vb[i1], vb[i1 + 1], vb[i1 + 2]);
                    Vec3.set(tri.c, vb[i2], vb[i2 + 1], vb[i2 + 2]);
                    var dist = intersect.rayTriangle(ray, tri, opt.doubleSided);
                    if (dist === 0 || dist > opt.distance) continue;
                    fillResult(opt.mode, dist, i0, i1, i2, opt.result);
                    if (opt.mode === ERaycastMode.ANY) return dist;
                  }
                } else if (pm === PrimitiveMode.TRIANGLE_STRIP) {
                  var _cnt = ib.length - 2;

                  var rev = 0;

                  for (var _j = 0; _j < _cnt; _j += 1) {
                    var _i = ib[_j - rev] * 3;

                    var _i2 = ib[_j + rev + 1] * 3;

                    var _i3 = ib[_j + 2] * 3;

                    Vec3.set(tri.a, vb[_i], vb[_i + 1], vb[_i + 2]);
                    Vec3.set(tri.b, vb[_i2], vb[_i2 + 1], vb[_i2 + 2]);
                    Vec3.set(tri.c, vb[_i3], vb[_i3 + 1], vb[_i3 + 2]);
                    rev = ~rev;

                    var _dist = intersect.rayTriangle(ray, tri, opt.doubleSided);

                    if (_dist === 0 || _dist > opt.distance) continue;
                    fillResult(opt.mode, _dist, _i, _i2, _i3, opt.result);
                    if (opt.mode === ERaycastMode.ANY) return _dist;
                  }
                } else if (pm === PrimitiveMode.TRIANGLE_FAN) {
                  var _cnt2 = ib.length - 1;

                  var _i4 = ib[0] * 3;

                  Vec3.set(tri.a, vb[_i4], vb[_i4 + 1], vb[_i4 + 2]);

                  for (var _j2 = 1; _j2 < _cnt2; _j2 += 1) {
                    var _i5 = ib[_j2] * 3;

                    var _i6 = ib[_j2 + 1] * 3;

                    Vec3.set(tri.b, vb[_i5], vb[_i5 + 1], vb[_i5 + 2]);
                    Vec3.set(tri.c, vb[_i6], vb[_i6 + 1], vb[_i6 + 2]);

                    var _dist2 = intersect.rayTriangle(ray, tri, opt.doubleSided);

                    if (_dist2 === 0 || _dist2 > opt.distance) continue;
                    fillResult(opt.mode, _dist2, _i4, _i5, _i6, opt.result);
                    if (opt.mode === ERaycastMode.ANY) return _dist2;
                  }
                }

                return minDis;
              };

              return function (ray, submesh, options) {
                minDis = 0;
                if (submesh.geometricInfo.positions.length === 0) return minDis;
                var opt = options === undefined ? deOpt : options;
                var min = submesh.geometricInfo.boundingBox.min;
                var max = submesh.geometricInfo.boundingBox.max;

                if (rayAABB2(ray, min, max)) {
                  var pm = submesh.primitiveMode;
                  var _submesh$geometricInf = submesh.geometricInfo,
                      vb = _submesh$geometricInf.positions,
                      ib = _submesh$geometricInf.indices;
                  narrowphase(vb, ib, pm, ray, opt);
                }

                return minDis;
              };
            }();

            var rayMesh = function () {
              var minDis = 0;
              var deOpt = {
                distance: Infinity,
                doubleSided: false,
                mode: ERaycastMode.ANY
              };
              return function (ray, mesh, options) {
                minDis = 0;
                var opt = options === undefined ? deOpt : options;
                var length = mesh.renderingSubMeshes.length;
                var min = mesh.struct.minPosition;
                var max = mesh.struct.maxPosition;
                if (min && max && !rayAABB2(ray, min, max)) return minDis;

                for (var i = 0; i < length; i++) {
                  var sm = mesh.renderingSubMeshes[i];
                  var dis = raySubMesh(ray, sm, opt);

                  if (dis) {
                    if (opt.mode === ERaycastMode.CLOSEST) {
                      if (minDis === 0 || minDis > dis) {
                        minDis = dis;
                        if (opt.subIndices) opt.subIndices[0] = i;
                      }
                    } else {
                      minDis = dis;
                      if (opt.subIndices) opt.subIndices.push(i);

                      if (opt.mode === ERaycastMode.ANY) {
                        return dis;
                      }
                    }
                  }
                }

                if (minDis && opt.mode === ERaycastMode.CLOSEST) {
                  if (opt.result) {
                    opt.result[0].distance = minDis;
                    opt.result.length = 1;
                  }

                  if (opt.subIndices) opt.subIndices.length = 1;
                }

                return minDis;
              };
            }();

            var rayModel = function () {
              var minDis = 0;
              var deOpt = {
                distance: Infinity,
                doubleSided: false,
                mode: ERaycastMode.ANY
              };
              var modelRay = new Ray();
              var m4 = new Mat4();
              return function (r, model, options) {
                minDis = 0;
                var opt = options === undefined ? deOpt : options;
                var wb = model.worldBounds;
                if (wb && !rayAABB(r, wb)) return minDis;
                Ray.copy(modelRay, r);

                if (model.node) {
                  Mat4.invert(m4, model.node.getWorldMatrix(m4));
                  Vec3.transformMat4(modelRay.o, r.o, m4);
                  Vec3.transformMat4Normal(modelRay.d, r.d, m4);
                }

                var subModels = model.subModels;

                for (var i = 0; i < subModels.length; i++) {
                  var subMesh = subModels[i].subMesh;
                  var dis = raySubMesh(modelRay, subMesh, opt);

                  if (dis) {
                    if (opt.mode === ERaycastMode.CLOSEST) {
                      if (minDis === 0 || minDis > dis) {
                        minDis = dis;
                        if (opt.subIndices) opt.subIndices[0] = i;
                      }
                    } else {
                      minDis = dis;
                      if (opt.subIndices) opt.subIndices.push(i);

                      if (opt.mode === ERaycastMode.ANY) {
                        return dis;
                      }
                    }
                  }
                }

                if (minDis && opt.mode === ERaycastMode.CLOSEST) {
                  if (opt.result) {
                    opt.result[0].distance = minDis;
                    opt.result.length = 1;
                  }

                  if (opt.subIndices) opt.subIndices.length = 1;
                }

                return minDis;
              };
            }();

            var linePlane = function () {
              var ab = new Vec3(0, 0, 0);
              return function (line, plane) {
                Vec3.subtract(ab, line.e, line.s);
                var t = (plane.d - Vec3.dot(line.s, plane.n)) / Vec3.dot(ab, plane.n);

                if (t < 0 || t > 1) {
                  return 0;
                }

                return t;
              };
            }();

            var lineTriangle = function () {
              var ab = new Vec3(0, 0, 0);
              var ac = new Vec3(0, 0, 0);
              var qp = new Vec3(0, 0, 0);
              var ap = new Vec3(0, 0, 0);
              var n = new Vec3(0, 0, 0);
              var e = new Vec3(0, 0, 0);
              return function (line, triangle, outPt) {
                Vec3.subtract(ab, triangle.b, triangle.a);
                Vec3.subtract(ac, triangle.c, triangle.a);
                Vec3.subtract(qp, line.s, line.e);
                Vec3.cross(n, ab, ac);
                var det = Vec3.dot(qp, n);

                if (det <= 0.0) {
                  return 0;
                }

                Vec3.subtract(ap, line.s, triangle.a);
                var t = Vec3.dot(ap, n);

                if (t < 0 || t > det) {
                  return 0;
                }

                Vec3.cross(e, qp, ap);
                var v = Vec3.dot(ac, e);

                if (v < 0 || v > det) {
                  return 0;
                }

                var w = -Vec3.dot(ab, e);

                if (w < 0.0 || v + w > det) {
                  return 0;
                }

                if (outPt) {
                  var invDet = 1.0 / det;
                  v *= invDet;
                  w *= invDet;
                  var u = 1.0 - v - w;
                  Vec3.set(outPt, triangle.a.x * u + triangle.b.x * v + triangle.c.x * w, triangle.a.y * u + triangle.b.y * v + triangle.c.y * w, triangle.a.z * u + triangle.b.z * v + triangle.c.z * w);
                }

                return 1;
              };
            }();

            var r_t = new Ray();

            function lineAABB(line, aabb) {
              r_t.o.set(line.s);
              Vec3.subtract(r_t.d, line.e, line.s);
              r_t.d.normalize();
              var min = rayAABB(r_t, aabb);
              var len = line.length();

              if (min <= len) {
                return min;
              } else {
                return 0;
              }
            }

            function lineOBB(line, obb) {
              r_t.o.set(line.s);
              Vec3.subtract(r_t.d, line.e, line.s);
              r_t.d.normalize();
              var min = rayOBB(r_t, obb);
              var len = line.length();

              if (min <= len) {
                return min;
              } else {
                return 0;
              }
            }

            function lineSphere(line, sphere) {
              r_t.o.set(line.s);
              Vec3.subtract(r_t.d, line.e, line.s);
              r_t.d.normalize();
              var min = raySphere(r_t, sphere);
              var len = line.length();

              if (min <= len) {
                return min;
              } else {
                return 0;
              }
            }

            var aabbWithAABB = function () {
              var aMin = new Vec3();
              var aMax = new Vec3();
              var bMin = new Vec3();
              var bMax = new Vec3();
              return function (aabb1, aabb2) {
                Vec3.subtract(aMin, aabb1.center, aabb1.halfExtents);
                Vec3.add(aMax, aabb1.center, aabb1.halfExtents);
                Vec3.subtract(bMin, aabb2.center, aabb2.halfExtents);
                Vec3.add(bMax, aabb2.center, aabb2.halfExtents);
                return aMin.x <= bMax.x && aMax.x >= bMin.x && aMin.y <= bMax.y && aMax.y >= bMin.y && aMin.z <= bMax.z && aMax.z >= bMin.z;
              };
            }();

            function getAABBVertices(min, max, out) {
              Vec3.set(out[0], min.x, max.y, max.z);
              Vec3.set(out[1], min.x, max.y, min.z);
              Vec3.set(out[2], min.x, min.y, max.z);
              Vec3.set(out[3], min.x, min.y, min.z);
              Vec3.set(out[4], max.x, max.y, max.z);
              Vec3.set(out[5], max.x, max.y, min.z);
              Vec3.set(out[6], max.x, min.y, max.z);
              Vec3.set(out[7], max.x, min.y, min.z);
            }

            function getOBBVertices(c, e, a1, a2, a3, out) {
              Vec3.set(out[0], c.x + a1.x * e.x + a2.x * e.y + a3.x * e.z, c.y + a1.y * e.x + a2.y * e.y + a3.y * e.z, c.z + a1.z * e.x + a2.z * e.y + a3.z * e.z);
              Vec3.set(out[1], c.x - a1.x * e.x + a2.x * e.y + a3.x * e.z, c.y - a1.y * e.x + a2.y * e.y + a3.y * e.z, c.z - a1.z * e.x + a2.z * e.y + a3.z * e.z);
              Vec3.set(out[2], c.x + a1.x * e.x - a2.x * e.y + a3.x * e.z, c.y + a1.y * e.x - a2.y * e.y + a3.y * e.z, c.z + a1.z * e.x - a2.z * e.y + a3.z * e.z);
              Vec3.set(out[3], c.x + a1.x * e.x + a2.x * e.y - a3.x * e.z, c.y + a1.y * e.x + a2.y * e.y - a3.y * e.z, c.z + a1.z * e.x + a2.z * e.y - a3.z * e.z);
              Vec3.set(out[4], c.x - a1.x * e.x - a2.x * e.y - a3.x * e.z, c.y - a1.y * e.x - a2.y * e.y - a3.y * e.z, c.z - a1.z * e.x - a2.z * e.y - a3.z * e.z);
              Vec3.set(out[5], c.x + a1.x * e.x - a2.x * e.y - a3.x * e.z, c.y + a1.y * e.x - a2.y * e.y - a3.y * e.z, c.z + a1.z * e.x - a2.z * e.y - a3.z * e.z);
              Vec3.set(out[6], c.x - a1.x * e.x + a2.x * e.y - a3.x * e.z, c.y - a1.y * e.x + a2.y * e.y - a3.y * e.z, c.z - a1.z * e.x + a2.z * e.y - a3.z * e.z);
              Vec3.set(out[7], c.x - a1.x * e.x - a2.x * e.y + a3.x * e.z, c.y - a1.y * e.x - a2.y * e.y + a3.y * e.z, c.z - a1.z * e.x - a2.z * e.y + a3.z * e.z);
            }

            function getInterval(vertices, axis) {
              var min = Vec3.dot(axis, vertices[0]);
              var max = min;

              for (var i = 1; i < 8; ++i) {
                var projection = Vec3.dot(axis, vertices[i]);
                min = projection < min ? projection : min;
                max = projection > max ? projection : max;
              }

              return [min, max];
            }

            var aabbWithOBB = function () {
              var test = new Array(15);

              for (var i = 0; i < 15; i++) {
                test[i] = new Vec3(0, 0, 0);
              }

              var vertices = new Array(8);
              var vertices2 = new Array(8);

              for (var _i7 = 0; _i7 < 8; _i7++) {
                vertices[_i7] = new Vec3(0, 0, 0);
                vertices2[_i7] = new Vec3(0, 0, 0);
              }

              var min = new Vec3();
              var max = new Vec3();
              return function (aabb, obb) {
                Vec3.set(test[0], 1, 0, 0);
                Vec3.set(test[1], 0, 1, 0);
                Vec3.set(test[2], 0, 0, 1);
                Vec3.set(test[3], obb.orientation.m00, obb.orientation.m01, obb.orientation.m02);
                Vec3.set(test[4], obb.orientation.m03, obb.orientation.m04, obb.orientation.m05);
                Vec3.set(test[5], obb.orientation.m06, obb.orientation.m07, obb.orientation.m08);

                for (var _i8 = 0; _i8 < 3; ++_i8) {
                  Vec3.cross(test[6 + _i8 * 3 + 0], test[_i8], test[0]);
                  Vec3.cross(test[6 + _i8 * 3 + 1], test[_i8], test[1]);
                  Vec3.cross(test[6 + _i8 * 3 + 1], test[_i8], test[2]);
                }

                Vec3.subtract(min, aabb.center, aabb.halfExtents);
                Vec3.add(max, aabb.center, aabb.halfExtents);
                getAABBVertices(min, max, vertices);
                getOBBVertices(obb.center, obb.halfExtents, test[3], test[4], test[5], vertices2);

                for (var j = 0; j < 15; ++j) {
                  var a = getInterval(vertices, test[j]);
                  var b = getInterval(vertices2, test[j]);

                  if (b[0] > a[1] || a[0] > b[1]) {
                    return 0;
                  }
                }

                return 1;
              };
            }();

            var aabbPlane = function aabbPlane(aabb, plane) {
              var r = aabb.halfExtents.x * Math.abs(plane.n.x) + aabb.halfExtents.y * Math.abs(plane.n.y) + aabb.halfExtents.z * Math.abs(plane.n.z);
              var dot = Vec3.dot(plane.n, aabb.center);

              if (dot + r < plane.d) {
                return -1;
              } else if (dot - r > plane.d) {
                return 0;
              }

              return 1;
            };

            var aabbFrustum = function aabbFrustum(aabb, frustum) {
              for (var i = 0; i < frustum.planes.length; i++) {
                if (aabbPlane(aabb, frustum.planes[i]) === -1) {
                  return 0;
                }
              }

              return 1;
            };

            var aabbFrustumAccurate = function () {
              var tmp = new Array(8);
              var out1 = 0;
              var out2 = 0;

              for (var i = 0; i < tmp.length; i++) {
                tmp[i] = new Vec3(0, 0, 0);
              }

              return function (aabb, frustum) {
                var result = 0;
                var intersects = false;

                for (var _i9 = 0; _i9 < frustum.planes.length; _i9++) {
                  result = aabbPlane(aabb, frustum.planes[_i9]);

                  if (result === -1) {
                    return 0;
                  } else if (result === 1) {
                      intersects = true;
                    }
                }

                if (!intersects) {
                  return 1;
                }

                for (var _i10 = 0; _i10 < frustum.vertices.length; _i10++) {
                  Vec3.subtract(tmp[_i10], frustum.vertices[_i10], aabb.center);
                }

                out1 = 0, out2 = 0;

                for (var _i11 = 0; _i11 < frustum.vertices.length; _i11++) {
                  if (tmp[_i11].x > aabb.halfExtents.x) {
                    out1++;
                  } else if (tmp[_i11].x < -aabb.halfExtents.x) {
                    out2++;
                  }
                }

                if (out1 === frustum.vertices.length || out2 === frustum.vertices.length) {
                  return 0;
                }

                out1 = 0;
                out2 = 0;

                for (var _i12 = 0; _i12 < frustum.vertices.length; _i12++) {
                  if (tmp[_i12].y > aabb.halfExtents.y) {
                    out1++;
                  } else if (tmp[_i12].y < -aabb.halfExtents.y) {
                    out2++;
                  }
                }

                if (out1 === frustum.vertices.length || out2 === frustum.vertices.length) {
                  return 0;
                }

                out1 = 0;
                out2 = 0;

                for (var _i13 = 0; _i13 < frustum.vertices.length; _i13++) {
                  if (tmp[_i13].z > aabb.halfExtents.z) {
                    out1++;
                  } else if (tmp[_i13].z < -aabb.halfExtents.z) {
                    out2++;
                  }
                }

                if (out1 === frustum.vertices.length || out2 === frustum.vertices.length) {
                  return 0;
                }

                return 1;
              };
            }();

            var obbPoint = function () {
              var tmp = new Vec3(0, 0, 0);
              var m3 = new Mat3();

              var lessThan = function lessThan(a, b) {
                return Math.abs(a.x) < b.x && Math.abs(a.y) < b.y && Math.abs(a.z) < b.z;
              };

              return function (obb, point) {
                Vec3.subtract(tmp, point, obb.center);
                Vec3.transformMat3(tmp, tmp, Mat3.transpose(m3, obb.orientation));
                return lessThan(tmp, obb.halfExtents);
              };
            }();

            var obbPlane = function () {
              var absDot = function absDot(n, x, y, z) {
                return Math.abs(n.x * x + n.y * y + n.z * z);
              };

              return function (obb, plane) {
                var r = obb.halfExtents.x * absDot(plane.n, obb.orientation.m00, obb.orientation.m01, obb.orientation.m02) + obb.halfExtents.y * absDot(plane.n, obb.orientation.m03, obb.orientation.m04, obb.orientation.m05) + obb.halfExtents.z * absDot(plane.n, obb.orientation.m06, obb.orientation.m07, obb.orientation.m08);
                var dot = Vec3.dot(plane.n, obb.center);

                if (dot + r < plane.d) {
                  return -1;
                } else if (dot - r > plane.d) {
                  return 0;
                }

                return 1;
              };
            }();

            var obbFrustum = function obbFrustum(obb, frustum) {
              for (var i = 0; i < frustum.planes.length; i++) {
                if (obbPlane(obb, frustum.planes[i]) === -1) {
                  return 0;
                }
              }

              return 1;
            };

            var obbFrustumAccurate = function () {
              var tmp = new Array(8);
              var dist = 0;
              var out1 = 0;
              var out2 = 0;

              for (var i = 0; i < tmp.length; i++) {
                tmp[i] = new Vec3(0, 0, 0);
              }

              var dot = function dot(n, x, y, z) {
                return n.x * x + n.y * y + n.z * z;
              };

              return function (obb, frustum) {
                var result = 0;
                var intersects = false;

                for (var _i14 = 0; _i14 < frustum.planes.length; _i14++) {
                  result = obbPlane(obb, frustum.planes[_i14]);

                  if (result === -1) {
                    return 0;
                  } else if (result === 1) {
                      intersects = true;
                    }
                }

                if (!intersects) {
                  return 1;
                }

                for (var _i15 = 0; _i15 < frustum.vertices.length; _i15++) {
                  Vec3.subtract(tmp[_i15], frustum.vertices[_i15], obb.center);
                }

                out1 = 0, out2 = 0;

                for (var _i16 = 0; _i16 < frustum.vertices.length; _i16++) {
                  dist = dot(tmp[_i16], obb.orientation.m00, obb.orientation.m01, obb.orientation.m02);

                  if (dist > obb.halfExtents.x) {
                    out1++;
                  } else if (dist < -obb.halfExtents.x) {
                    out2++;
                  }
                }

                if (out1 === frustum.vertices.length || out2 === frustum.vertices.length) {
                  return 0;
                }

                out1 = 0;
                out2 = 0;

                for (var _i17 = 0; _i17 < frustum.vertices.length; _i17++) {
                  dist = dot(tmp[_i17], obb.orientation.m03, obb.orientation.m04, obb.orientation.m05);

                  if (dist > obb.halfExtents.y) {
                    out1++;
                  } else if (dist < -obb.halfExtents.y) {
                    out2++;
                  }
                }

                if (out1 === frustum.vertices.length || out2 === frustum.vertices.length) {
                  return 0;
                }

                out1 = 0;
                out2 = 0;

                for (var _i18 = 0; _i18 < frustum.vertices.length; _i18++) {
                  dist = dot(tmp[_i18], obb.orientation.m06, obb.orientation.m07, obb.orientation.m08);

                  if (dist > obb.halfExtents.z) {
                    out1++;
                  } else if (dist < -obb.halfExtents.z) {
                    out2++;
                  }
                }

                if (out1 === frustum.vertices.length || out2 === frustum.vertices.length) {
                  return 0;
                }

                return 1;
              };
            }();

            var obbWithOBB = function () {
              var test = new Array(15);

              for (var i = 0; i < 15; i++) {
                test[i] = new Vec3(0, 0, 0);
              }

              var vertices = new Array(8);
              var vertices2 = new Array(8);

              for (var _i19 = 0; _i19 < 8; _i19++) {
                vertices[_i19] = new Vec3(0, 0, 0);
                vertices2[_i19] = new Vec3(0, 0, 0);
              }

              return function (obb1, obb2) {
                Vec3.set(test[0], obb1.orientation.m00, obb1.orientation.m01, obb1.orientation.m02);
                Vec3.set(test[1], obb1.orientation.m03, obb1.orientation.m04, obb1.orientation.m05);
                Vec3.set(test[2], obb1.orientation.m06, obb1.orientation.m07, obb1.orientation.m08);
                Vec3.set(test[3], obb2.orientation.m00, obb2.orientation.m01, obb2.orientation.m02);
                Vec3.set(test[4], obb2.orientation.m03, obb2.orientation.m04, obb2.orientation.m05);
                Vec3.set(test[5], obb2.orientation.m06, obb2.orientation.m07, obb2.orientation.m08);

                for (var _i20 = 0; _i20 < 3; ++_i20) {
                  Vec3.cross(test[6 + _i20 * 3 + 0], test[_i20], test[0]);
                  Vec3.cross(test[6 + _i20 * 3 + 1], test[_i20], test[1]);
                  Vec3.cross(test[6 + _i20 * 3 + 1], test[_i20], test[2]);
                }

                getOBBVertices(obb1.center, obb1.halfExtents, test[0], test[1], test[2], vertices);
                getOBBVertices(obb2.center, obb2.halfExtents, test[3], test[4], test[5], vertices2);

                for (var _i21 = 0; _i21 < 15; ++_i21) {
                  var a = getInterval(vertices, test[_i21]);
                  var b = getInterval(vertices2, test[_i21]);

                  if (b[0] > a[1] || a[0] > b[1]) {
                    return 0;
                  }
                }

                return 1;
              };
            }();

            var obbCapsule = function () {
              var sphere_0 = new Sphere();
              var v3_0 = new Vec3();
              var v3_1 = new Vec3();
              var v3_2 = new Vec3();
              var v3_verts8 = new Array(8);

              for (var i = 0; i < 8; i++) {
                v3_verts8[i] = new Vec3();
              }

              var v3_axis8 = new Array(8);

              for (var _i22 = 0; _i22 < 8; _i22++) {
                v3_axis8[_i22] = new Vec3();
              }

              return function (obb, capsule) {
                var h = Vec3.squaredDistance(capsule.ellipseCenter0, capsule.ellipseCenter1);

                if (h === 0) {
                  sphere_0.radius = capsule.radius;
                  sphere_0.center.set(capsule.ellipseCenter0);
                  return intersect.sphereOBB(sphere_0, obb);
                } else {
                  v3_0.x = obb.orientation.m00;
                  v3_0.y = obb.orientation.m01;
                  v3_0.z = obb.orientation.m02;
                  v3_1.x = obb.orientation.m03;
                  v3_1.y = obb.orientation.m04;
                  v3_1.z = obb.orientation.m05;
                  v3_2.x = obb.orientation.m06;
                  v3_2.y = obb.orientation.m07;
                  v3_2.z = obb.orientation.m08;
                  getOBBVertices(obb.center, obb.halfExtents, v3_0, v3_1, v3_2, v3_verts8);
                  var axes = v3_axis8;
                  var a0 = Vec3.copy(axes[0], v3_0);
                  var a1 = Vec3.copy(axes[1], v3_1);
                  var a2 = Vec3.copy(axes[2], v3_2);
                  var C = Vec3.subtract(axes[3], capsule.center, obb.center);
                  C.normalize();
                  var B = Vec3.subtract(axes[4], capsule.ellipseCenter0, capsule.ellipseCenter1);
                  B.normalize();
                  Vec3.cross(axes[5], a0, B);
                  Vec3.cross(axes[6], a1, B);
                  Vec3.cross(axes[7], a2, B);

                  for (var _i23 = 0; _i23 < 8; ++_i23) {
                    var a = getInterval(v3_verts8, axes[_i23]);
                    var d0 = Vec3.dot(axes[_i23], capsule.ellipseCenter0);
                    var d1 = Vec3.dot(axes[_i23], capsule.ellipseCenter1);
                    var max_d = Math.max(d0, d1);
                    var min_d = Math.min(d0, d1);
                    var d_min = min_d - capsule.radius;
                    var d_max = max_d + capsule.radius;

                    if (d_min > a[1] || a[0] > d_max) {
                      return 0;
                    }
                  }

                  return 1;
                }
              };
            }();

            var spherePlane = function spherePlane(sphere, plane) {
              var dot = Vec3.dot(plane.n, sphere.center);
              var r = sphere.radius * plane.n.length();

              if (dot + r < plane.d) {
                return -1;
              } else if (dot - r > plane.d) {
                return 0;
              }

              return 1;
            };

            var sphereFrustum = function sphereFrustum(sphere, frustum) {
              for (var i = 0; i < frustum.planes.length; i++) {
                if (spherePlane(sphere, frustum.planes[i]) === -1) {
                  return 0;
                }
              }

              return 1;
            };

            var sphereFrustumAccurate = function () {
              var pt = new Vec3(0, 0, 0);
              var map = [1, -1, 1, -1, 1, -1];
              return function (sphere, frustum) {
                for (var i = 0; i < 6; i++) {
                  var plane = frustum.planes[i];
                  var r = sphere.radius;
                  var c = sphere.center;
                  var n = plane.n;
                  var d = plane.d;
                  var dot = Vec3.dot(n, c);

                  if (dot + r < d) {
                    return 0;
                  } else if (dot - r > d) {
                      continue;
                    }

                  Vec3.add(pt, c, Vec3.multiplyScalar(pt, n, r));

                  for (var j = 0; j < 6; j++) {
                    if (j === i || j === i + map[i]) {
                      continue;
                    }

                    var test = frustum.planes[j];

                    if (Vec3.dot(test.n, pt) < test.d) {
                      return 0;
                    }
                  }
                }

                return 1;
              };
            }();

            var sphereWithSphere = function sphereWithSphere(sphere0, sphere1) {
              var r = sphere0.radius + sphere1.radius;
              return Vec3.squaredDistance(sphere0.center, sphere1.center) < r * r;
            };

            var sphereAABB = function () {
              var pt = new Vec3();
              return function (sphere, aabb) {
                pt_point_aabb(pt, sphere.center, aabb);
                return Vec3.squaredDistance(sphere.center, pt) < sphere.radius * sphere.radius;
              };
            }();

            var sphereOBB = function () {
              var pt = new Vec3();
              return function (sphere, obb) {
                pt_point_obb(pt, sphere.center, obb);
                return Vec3.squaredDistance(sphere.center, pt) < sphere.radius * sphere.radius;
              };
            }();

            var sphereCapsule = function () {
              var v3_0 = new Vec3();
              var v3_1 = new Vec3();
              return function (sphere, capsule) {
                var r = sphere.radius + capsule.radius;
                var squaredR = r * r;
                var h = Vec3.squaredDistance(capsule.ellipseCenter0, capsule.ellipseCenter1);

                if (h === 0) {
                  return Vec3.squaredDistance(sphere.center, capsule.center) < squaredR;
                } else {
                  Vec3.subtract(v3_0, sphere.center, capsule.ellipseCenter0);
                  Vec3.subtract(v3_1, capsule.ellipseCenter1, capsule.ellipseCenter0);
                  var t = Vec3.dot(v3_0, v3_1) / h;

                  if (t < 0) {
                    return Vec3.squaredDistance(sphere.center, capsule.ellipseCenter0) < squaredR;
                  } else if (t > 1) {
                    return Vec3.squaredDistance(sphere.center, capsule.ellipseCenter1) < squaredR;
                  } else {
                    Vec3.scaleAndAdd(v3_0, capsule.ellipseCenter0, v3_1, t);
                    return Vec3.squaredDistance(sphere.center, v3_0) < squaredR;
                  }
                }
              };
            }();

            var capsuleWithCapsule = function () {
              var v3_0 = new Vec3();
              var v3_1 = new Vec3();
              var v3_2 = new Vec3();
              var v3_3 = new Vec3();
              var v3_4 = new Vec3();
              var v3_5 = new Vec3();
              return function capsuleWithCapsule(capsuleA, capsuleB) {
                var u = Vec3.subtract(v3_0, capsuleA.ellipseCenter1, capsuleA.ellipseCenter0);
                var v = Vec3.subtract(v3_1, capsuleB.ellipseCenter1, capsuleB.ellipseCenter0);
                var w = Vec3.subtract(v3_2, capsuleA.ellipseCenter0, capsuleB.ellipseCenter0);
                var a = Vec3.dot(u, u);
                var b = Vec3.dot(u, v);
                var c = Vec3.dot(v, v);
                var d = Vec3.dot(u, w);
                var e = Vec3.dot(v, w);
                var D = a * c - b * b;
                var sc;
                var sN;
                var sD = D;
                var tc;
                var tN;
                var tD = D;

                if (D < EPSILON) {
                  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;
                  }
                }

                sc = Math.abs(sN) < EPSILON ? 0.0 : sN / sD;
                tc = Math.abs(tN) < EPSILON ? 0.0 : tN / tD;
                var dP = v3_3;
                dP.set(w);
                dP.add(Vec3.multiplyScalar(v3_4, u, sc));
                dP.subtract(Vec3.multiplyScalar(v3_5, v, tc));
                var radius = capsuleA.radius + capsuleB.radius;
                return dP.lengthSqr() < radius * radius;
              };
            }();

            var intersect = {
              raySphere: raySphere,
              rayAABB: rayAABB,
              rayOBB: rayOBB,
              rayPlane: rayPlane,
              rayTriangle: rayTriangle,
              rayCapsule: rayCapsule,
              raySubMesh: raySubMesh,
              rayMesh: rayMesh,
              rayModel: rayModel,
              lineSphere: lineSphere,
              lineAABB: lineAABB,
              lineOBB: lineOBB,
              linePlane: linePlane,
              lineTriangle: lineTriangle,
              sphereWithSphere: sphereWithSphere,
              sphereAABB: sphereAABB,
              sphereOBB: sphereOBB,
              spherePlane: spherePlane,
              sphereFrustum: sphereFrustum,
              sphereFrustumAccurate: sphereFrustumAccurate,
              sphereCapsule: sphereCapsule,
              aabbWithAABB: aabbWithAABB,
              aabbWithOBB: aabbWithOBB,
              aabbPlane: aabbPlane,
              aabbFrustum: aabbFrustum,
              aabbFrustumAccurate: aabbFrustumAccurate,
              obbWithOBB: obbWithOBB,
              obbPlane: obbPlane,
              obbFrustum: obbFrustum,
              obbFrustumAccurate: obbFrustumAccurate,
              obbPoint: obbPoint,
              obbCapsule: obbCapsule,
              capsuleWithCapsule: capsuleWithCapsule,
              resolve: function resolve(g1, g2, outPt) {
                if (outPt === void 0) {
                  outPt = null;
                }

                var type1 = g1._type;
                var type2 = g2._type;
                var resolver = this[type1 | type2];

                if (type1 < type2) {
                  return resolver(g1, g2, outPt);
                } else {
                  return resolver(g2, g1, outPt);
                }
              }
            };
            intersect[enums.SHAPE_RAY | enums.SHAPE_SPHERE] = raySphere;
            intersect[enums.SHAPE_RAY | enums.SHAPE_AABB] = rayAABB;
            intersect[enums.SHAPE_RAY | enums.SHAPE_OBB] = rayOBB;
            intersect[enums.SHAPE_RAY | enums.SHAPE_PLANE] = rayPlane;
            intersect[enums.SHAPE_RAY | enums.SHAPE_TRIANGLE] = rayTriangle;
            intersect[enums.SHAPE_RAY | enums.SHAPE_CAPSULE] = rayCapsule;
            intersect[enums.SHAPE_LINE | enums.SHAPE_SPHERE] = lineSphere;
            intersect[enums.SHAPE_LINE | enums.SHAPE_AABB] = lineAABB;
            intersect[enums.SHAPE_LINE | enums.SHAPE_OBB] = lineOBB;
            intersect[enums.SHAPE_LINE | enums.SHAPE_PLANE] = linePlane;
            intersect[enums.SHAPE_LINE | enums.SHAPE_TRIANGLE] = lineTriangle;
            intersect[enums.SHAPE_SPHERE] = sphereWithSphere;
            intersect[enums.SHAPE_SPHERE | enums.SHAPE_AABB] = sphereAABB;
            intersect[enums.SHAPE_SPHERE | enums.SHAPE_OBB] = sphereOBB;
            intersect[enums.SHAPE_SPHERE | enums.SHAPE_PLANE] = spherePlane;
            intersect[enums.SHAPE_SPHERE | enums.SHAPE_FRUSTUM] = sphereFrustum;
            intersect[enums.SHAPE_SPHERE | enums.SHAPE_FRUSTUM_ACCURATE] = sphereFrustumAccurate;
            intersect[enums.SHAPE_SPHERE | enums.SHAPE_CAPSULE] = sphereCapsule;
            intersect[enums.SHAPE_AABB] = aabbWithAABB;
            intersect[enums.SHAPE_AABB | enums.SHAPE_OBB] = aabbWithOBB;
            intersect[enums.SHAPE_AABB | enums.SHAPE_PLANE] = aabbPlane;
            intersect[enums.SHAPE_AABB | enums.SHAPE_FRUSTUM] = aabbFrustum;
            intersect[enums.SHAPE_AABB | enums.SHAPE_FRUSTUM_ACCURATE] = aabbFrustumAccurate;
            intersect[enums.SHAPE_OBB] = obbWithOBB;
            intersect[enums.SHAPE_OBB | enums.SHAPE_PLANE] = obbPlane;
            intersect[enums.SHAPE_OBB | enums.SHAPE_FRUSTUM] = obbFrustum;
            intersect[enums.SHAPE_OBB | enums.SHAPE_FRUSTUM_ACCURATE] = obbFrustumAccurate;
            intersect[enums.SHAPE_OBB | enums.SHAPE_CAPSULE] = obbCapsule;
            intersect[enums.SHAPE_CAPSULE] = capsuleWithCapsule;

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

            var v1 = new Vec3(0, 0, 0);
            var v2$1 = new Vec3(0, 0, 0);
            var temp_mat = legacyCC.mat4();
            var temp_vec4 = legacyCC.v4();
            var Plane = function () {
              Plane.create = function create(nx, ny, nz, d) {
                return new Plane(nx, ny, nz, d);
              };

              Plane.clone = function clone(p) {
                return new Plane(p.n.x, p.n.y, p.n.z, p.d);
              };

              Plane.copy = function copy(out, p) {
                Vec3.copy(out.n, p.n);
                out.d = p.d;
                return out;
              };

              Plane.fromPoints = function fromPoints(out, a, b, c) {
                Vec3.subtract(v1, b, a);
                Vec3.subtract(v2$1, c, a);
                Vec3.normalize(out.n, Vec3.cross(out.n, v1, v2$1));
                out.d = Vec3.dot(out.n, a);
                return out;
              };

              Plane.set = function set(out, nx, ny, nz, d) {
                out.n.x = nx;
                out.n.y = ny;
                out.n.z = nz;
                out.d = d;
                return out;
              };

              Plane.fromNormalAndPoint = function fromNormalAndPoint(out, normal, point) {
                Vec3.copy(out.n, normal);
                out.d = Vec3.dot(normal, point);
                return out;
              };

              Plane.normalize = function normalize(out, a) {
                var len = a.n.length();
                Vec3.normalize(out.n, a.n);

                if (len > 0) {
                  out.d = a.d / len;
                }

                return out;
              };

              function Plane(nx, ny, nz, d) {
                if (nx === void 0) {
                  nx = 0;
                }

                if (ny === void 0) {
                  ny = 1;
                }

                if (nz === void 0) {
                  nz = 0;
                }

                if (d === void 0) {
                  d = 0;
                }

                this.n = void 0;
                this.d = void 0;
                this._type = void 0;
                this._type = enums.SHAPE_PLANE;
                this.n = new Vec3(nx, ny, nz);
                this.d = d;
              }

              var _proto = Plane.prototype;

              _proto.transform = function transform(mat) {
                Mat4.invert(temp_mat, mat);
                Mat4.transpose(temp_mat, temp_mat);
                Vec4.set(temp_vec4, this.n.x, this.n.y, this.n.z, this.d);
                Vec4.transformMat4(temp_vec4, temp_vec4, temp_mat);
                Vec3.set(this.n, temp_vec4.x, temp_vec4.y, temp_vec4.z);
                this.d = temp_vec4.w;
              };

              _createClass(Plane, [{
                key: "type",
                get: function get() {
                  return this._type;
                }
              }, {
                key: "x",
                get: function get() {
                  return this.n.x;
                },
                set: function set(val) {
                  this.n.x = val;
                }
              }, {
                key: "y",
                get: function get() {
                  return this.n.y;
                },
                set: function set(val) {
                  this.n.y = val;
                }
              }, {
                key: "z",
                get: function get() {
                  return this.n.z;
                },
                set: function set(val) {
                  this.n.z = val;
                }
              }, {
                key: "w",
                get: function get() {
                  return this.d;
                },
                set: function set(val) {
                  this.d = val;
                }
              }]);

              return Plane;
            }();

            var _v3_tmp$1 = new Vec3();

            var _v3_tmp2 = new Vec3();

            var _v3_tmp3 = new Vec3();

            var _v3_tmp4 = new Vec3();

            var _m3_tmp = new Mat3();

            var transform_extent_m4 = function transform_extent_m4(out, extent, m4) {
              _m3_tmp.m00 = Math.abs(m4.m00);
              _m3_tmp.m01 = Math.abs(m4.m01);
              _m3_tmp.m02 = Math.abs(m4.m02);
              _m3_tmp.m03 = Math.abs(m4.m04);
              _m3_tmp.m04 = Math.abs(m4.m05);
              _m3_tmp.m05 = Math.abs(m4.m06);
              _m3_tmp.m06 = Math.abs(m4.m08);
              _m3_tmp.m07 = Math.abs(m4.m09);
              _m3_tmp.m08 = Math.abs(m4.m10);
              Vec3.transformMat3(out, extent, _m3_tmp);
            };

            var AABB = function () {
              AABB.create = function create(px, py, pz, hw, hh, hl) {
                return new AABB(px, py, pz, hw, hh, hl);
              };

              AABB.clone = function clone(a) {
                return new AABB(a.center.x, a.center.y, a.center.z, a.halfExtents.x, a.halfExtents.y, a.halfExtents.z);
              };

              AABB.copy = function copy(out, a) {
                Vec3.copy(out.center, a.center);
                Vec3.copy(out.halfExtents, a.halfExtents);
                return out;
              };

              AABB.fromPoints = function fromPoints(out, minPos, maxPos) {
                Vec3.add(_v3_tmp$1, maxPos, minPos);
                Vec3.subtract(_v3_tmp2, maxPos, minPos);
                Vec3.multiplyScalar(out.center, _v3_tmp$1, 0.5);
                Vec3.multiplyScalar(out.halfExtents, _v3_tmp2, 0.5);
                return out;
              };

              AABB.set = function set(out, px, py, pz, hw, hh, hl) {
                Vec3.set(out.center, px, py, pz);
                Vec3.set(out.halfExtents, hw, hh, hl);
                return out;
              };

              AABB.merge = function merge(out, a, b) {
                Vec3.subtract(_v3_tmp$1, a.center, a.halfExtents);
                Vec3.subtract(_v3_tmp2, 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);
                return AABB.fromPoints(out, _v3_tmp3, _v3_tmp4);
              };

              AABB.toBoundingSphere = function toBoundingSphere(out, a) {
                a.getBoundary(_v3_tmp$1, _v3_tmp2);
                out.center.set(_v3_tmp$1);
                out.radius = 0.0;
                Vec3.subtract(_v3_tmp3, _v3_tmp2, out.center);

                var dist = _v3_tmp3.length();

                var half = dist * 0.5;
                out.radius += half;
                Vec3.multiplyScalar(_v3_tmp3, _v3_tmp3, half / dist);
                Vec3.add(out.center, out.center, _v3_tmp3);
                return out;
              };

              AABB.transform = function transform(out, a, matrix) {
                Vec3.transformMat4(out.center, a.center, matrix);
                transform_extent_m4(out.halfExtents, a.halfExtents, matrix);
                return out;
              };

              function AABB(px, py, pz, hw, hh, hl) {
                if (px === void 0) {
                  px = 0;
                }

                if (py === void 0) {
                  py = 0;
                }

                if (pz === void 0) {
                  pz = 0;
                }

                if (hw === void 0) {
                  hw = 1;
                }

                if (hh === void 0) {
                  hh = 1;
                }

                if (hl === void 0) {
                  hl = 1;
                }

                this.center = void 0;
                this.halfExtents = void 0;
                this._type = void 0;
                this._type = enums.SHAPE_AABB;
                this.center = new Vec3(px, py, pz);
                this.halfExtents = new Vec3(hw, hh, hl);
              }

              var _proto = AABB.prototype;

              _proto.getBoundary = function getBoundary(minPos, maxPos) {
                Vec3.subtract(minPos, this.center, this.halfExtents);
                Vec3.add(maxPos, this.center, this.halfExtents);
              };

              _proto.transform = function transform(m, pos, rot, scale, out) {
                Vec3.transformMat4(out.center, this.center, m);
                transform_extent_m4(out.halfExtents, this.halfExtents, m);
              };

              _proto.clone = function clone() {
                return AABB.clone(this);
              };

              _proto.copy = function copy(a) {
                return AABB.copy(this, a);
              };

              _createClass(AABB, [{
                key: "type",
                get: function get() {
                  return this._type;
                }
              }]);

              return AABB;
            }();

            var _v3_tmp$2 = new Vec3();

            var _v3_tmp2$1 = new Vec3();

            var _m3_tmp$1 = new Mat3();

            var transform_extent_m3 = function transform_extent_m3(out, extent, m3) {
              _m3_tmp$1.m00 = Math.abs(m3.m00);
              _m3_tmp$1.m01 = Math.abs(m3.m01);
              _m3_tmp$1.m02 = Math.abs(m3.m02);
              _m3_tmp$1.m03 = Math.abs(m3.m03);
              _m3_tmp$1.m04 = Math.abs(m3.m04);
              _m3_tmp$1.m05 = Math.abs(m3.m05);
              _m3_tmp$1.m06 = Math.abs(m3.m06);
              _m3_tmp$1.m07 = Math.abs(m3.m07);
              _m3_tmp$1.m08 = Math.abs(m3.m08);
              Vec3.transformMat3(out, extent, _m3_tmp$1);
            };

            var OBB = function () {
              OBB.create = function create(cx, cy, cz, hw, hh, hl, ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3) {
                return new OBB(cx, cy, cz, hw, hh, hl, ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3);
              };

              OBB.clone = function clone(a) {
                return new OBB(a.center.x, a.center.y, a.center.z, a.halfExtents.x, a.halfExtents.y, a.halfExtents.z, a.orientation.m00, a.orientation.m01, a.orientation.m02, a.orientation.m03, a.orientation.m04, a.orientation.m05, a.orientation.m06, a.orientation.m07, a.orientation.m08);
              };

              OBB.copy = function copy(out, a) {
                Vec3.copy(out.center, a.center);
                Vec3.copy(out.halfExtents, a.halfExtents);
                Mat3.copy(out.orientation, a.orientation);
                return out;
              };

              OBB.fromPoints = function fromPoints(out, minPos, maxPos) {
                Vec3.multiplyScalar(out.center, Vec3.add(_v3_tmp$2, minPos, maxPos), 0.5);
                Vec3.multiplyScalar(out.halfExtents, Vec3.subtract(_v3_tmp2$1, maxPos, minPos), 0.5);
                Mat3.identity(out.orientation);
                return out;
              };

              OBB.set = function set(out, cx, cy, cz, hw, hh, hl, ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3) {
                Vec3.set(out.center, cx, cy, cz);
                Vec3.set(out.halfExtents, hw, hh, hl);
                Mat3.set(out.orientation, ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3);
                return out;
              };

              function OBB(cx, cy, cz, hw, hh, hl, ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3) {
                if (cx === void 0) {
                  cx = 0;
                }

                if (cy === void 0) {
                  cy = 0;
                }

                if (cz === void 0) {
                  cz = 0;
                }

                if (hw === void 0) {
                  hw = 1;
                }

                if (hh === void 0) {
                  hh = 1;
                }

                if (hl === void 0) {
                  hl = 1;
                }

                if (ox_1 === void 0) {
                  ox_1 = 1;
                }

                if (ox_2 === void 0) {
                  ox_2 = 0;
                }

                if (ox_3 === void 0) {
                  ox_3 = 0;
                }

                if (oy_1 === void 0) {
                  oy_1 = 0;
                }

                if (oy_2 === void 0) {
                  oy_2 = 1;
                }

                if (oy_3 === void 0) {
                  oy_3 = 0;
                }

                if (oz_1 === void 0) {
                  oz_1 = 0;
                }

                if (oz_2 === void 0) {
                  oz_2 = 0;
                }

                if (oz_3 === void 0) {
                  oz_3 = 1;
                }

                this.center = void 0;
                this.halfExtents = void 0;
                this.orientation = void 0;
                this._type = void 0;
                this._type = enums.SHAPE_OBB;
                this.center = new Vec3(cx, cy, cz);
                this.halfExtents = new Vec3(hw, hh, hl);
                this.orientation = new Mat3(ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3);
              }

              var _proto = OBB.prototype;

              _proto.getBoundary = function getBoundary(minPos, maxPos) {
                transform_extent_m3(_v3_tmp$2, this.halfExtents, this.orientation);
                Vec3.subtract(minPos, this.center, _v3_tmp$2);
                Vec3.add(maxPos, this.center, _v3_tmp$2);
              };

              _proto.transform = function transform(m, pos, rot, scale, out) {
                Vec3.transformMat4(out.center, this.center, m);
                Mat3.fromQuat(out.orientation, rot);
                Vec3.multiply(out.halfExtents, this.halfExtents, scale);
              };

              _proto.translateAndRotate = function translateAndRotate(m, rot, out) {
                Vec3.transformMat4(out.center, this.center, m);
                Mat3.fromQuat(out.orientation, rot);
              };

              _proto.setScale = function setScale(scale, out) {
                Vec3.multiply(out.halfExtents, this.halfExtents, scale);
              };

              _createClass(OBB, [{
                key: "type",
                get: function get() {
                  return this._type;
                }
              }]);

              return OBB;
            }();

            var Capsule = function () {
              function Capsule(radius, halfHeight, axis) {
                if (radius === void 0) {
                  radius = 0.5;
                }

                if (halfHeight === void 0) {
                  halfHeight = 0.5;
                }

                if (axis === void 0) {
                  axis = 1;
                }

                this._type = void 0;
                this.radius = void 0;
                this.halfHeight = void 0;
                this.axis = void 0;
                this.center = void 0;
                this.rotation = void 0;
                this.ellipseCenter0 = void 0;
                this.ellipseCenter1 = void 0;
                this._type = enums.SHAPE_CAPSULE;
                this.radius = radius;
                this.halfHeight = halfHeight;
                this.axis = axis;
                this.center = new Vec3();
                this.rotation = new Quat();
                this.ellipseCenter0 = new Vec3(0, halfHeight, 0);
                this.ellipseCenter1 = new Vec3(0, -halfHeight, 0);
                this.updateCache();
              }

              var _proto = Capsule.prototype;

              _proto.transform = function transform(m, pos, rot, scale, out) {
                var ws = scale;
                var s = absMaxComponent(ws);
                out.radius = this.radius * Math.abs(s);
                var halfTotalWorldHeight = (this.halfHeight + this.radius) * Math.abs(ws.y);
                var halfWorldHeight = halfTotalWorldHeight - out.radius;
                if (halfWorldHeight < 0) halfWorldHeight = 0;
                out.halfHeight = halfWorldHeight;
                Vec3.transformMat4(out.center, this.center, m);
                Quat.multiply(out.rotation, this.rotation, rot);
                out.updateCache();
              };

              _proto.updateCache = function updateCache() {
                this.updateLocalCenter();
                Vec3.transformQuat(this.ellipseCenter0, this.ellipseCenter0, this.rotation);
                Vec3.transformQuat(this.ellipseCenter1, this.ellipseCenter1, this.rotation);
                this.ellipseCenter0.add(this.center);
                this.ellipseCenter1.add(this.center);
              };

              _proto.updateLocalCenter = function updateLocalCenter() {
                var halfHeight = this.halfHeight;
                var axis = this.axis;

                switch (axis) {
                  case 0:
                    this.ellipseCenter0.set(halfHeight, 0, 0);
                    this.ellipseCenter1.set(-halfHeight, 0, 0);
                    break;

                  case 1:
                    this.ellipseCenter0.set(0, halfHeight, 0);
                    this.ellipseCenter1.set(0, -halfHeight, 0);
                    break;

                  case 2:
                    this.ellipseCenter0.set(0, 0, halfHeight);
                    this.ellipseCenter1.set(0, 0, -halfHeight);
                    break;
                }
              };

              _createClass(Capsule, [{
                key: "type",
                get: function get() {
                  return this._type;
                }
              }]);

              return Capsule;
            }();

            var _v = new Array(8);

            _v[0] = new Vec3(1, 1, 1);
            _v[1] = new Vec3(-1, 1, 1);
            _v[2] = new Vec3(-1, -1, 1);
            _v[3] = new Vec3(1, -1, 1);
            _v[4] = new Vec3(1, 1, -1);
            _v[5] = new Vec3(-1, 1, -1);
            _v[6] = new Vec3(-1, -1, -1);
            _v[7] = new Vec3(1, -1, -1);
            var Frustum = function () {
              Frustum.create = function create() {
                return new Frustum();
              };

              Frustum.clone = function clone(f) {
                return Frustum.copy(new Frustum(), f);
              };

              Frustum.copy = function copy(out, f) {
                out._type = f._type;

                for (var i = 0; i < 6; ++i) {
                  Plane.copy(out.planes[i], f.planes[i]);
                }

                for (var _i = 0; _i < 8; ++_i) {
                  Vec3.copy(out.vertices[_i], f.vertices[_i]);
                }

                return out;
              };

              function Frustum() {
                this._type = void 0;
                this.planes = void 0;
                this.vertices = void 0;
                this._type = enums.SHAPE_FRUSTUM;
                this.planes = new Array(6);

                for (var i = 0; i < 6; ++i) {
                  this.planes[i] = Plane.create(0, 0, 0, 0);
                }

                this.vertices = new Array(8);

                for (var _i2 = 0; _i2 < 8; ++_i2) {
                  this.vertices[_i2] = new Vec3();
                }
              }

              var _proto = Frustum.prototype;

              _proto.update = function update(m, inv) {
                Vec3.set(this.planes[0].n, m.m03 + m.m00, m.m07 + m.m04, m.m11 + m.m08);
                this.planes[0].d = -(m.m15 + m.m12);
                Vec3.set(this.planes[1].n, m.m03 - m.m00, m.m07 - m.m04, m.m11 - m.m08);
                this.planes[1].d = -(m.m15 - m.m12);
                Vec3.set(this.planes[2].n, m.m03 + m.m01, m.m07 + m.m05, m.m11 + m.m09);
                this.planes[2].d = -(m.m15 + m.m13);
                Vec3.set(this.planes[3].n, m.m03 - m.m01, m.m07 - m.m05, m.m11 - m.m09);
                this.planes[3].d = -(m.m15 - m.m13);
                Vec3.set(this.planes[4].n, m.m03 + m.m02, m.m07 + m.m06, m.m11 + m.m10);
                this.planes[4].d = -(m.m15 + m.m14);
                Vec3.set(this.planes[5].n, m.m03 - m.m02, m.m07 - m.m06, m.m11 - m.m10);
                this.planes[5].d = -(m.m15 - m.m14);

                if (this._type !== enums.SHAPE_FRUSTUM_ACCURATE) {
                  return;
                }

                for (var i = 0; i < 6; i++) {
                  var pl = this.planes[i];
                  var invDist = 1 / pl.n.length();
                  Vec3.multiplyScalar(pl.n, pl.n, invDist);
                  pl.d *= invDist;
                }

                for (var _i3 = 0; _i3 < 8; _i3++) {
                  Vec3.transformMat4(this.vertices[_i3], _v[_i3], inv);
                }
              };

              _proto.transform = function transform(mat) {
                if (this._type !== enums.SHAPE_FRUSTUM_ACCURATE) {
                  return;
                }

                for (var i = 0; i < 8; i++) {
                  Vec3.transformMat4(this.vertices[i], this.vertices[i], mat);
                }

                Plane.fromPoints(this.planes[0], this.vertices[1], this.vertices[5], this.vertices[6]);
                Plane.fromPoints(this.planes[1], this.vertices[3], this.vertices[7], this.vertices[4]);
                Plane.fromPoints(this.planes[2], this.vertices[6], this.vertices[7], this.vertices[3]);
                Plane.fromPoints(this.planes[3], this.vertices[0], this.vertices[4], this.vertices[5]);
                Plane.fromPoints(this.planes[4], this.vertices[2], this.vertices[3], this.vertices[0]);
                Plane.fromPoints(this.planes[0], this.vertices[7], this.vertices[6], this.vertices[5]);
              };

              _createClass(Frustum, [{
                key: "accurate",
                set: function set(b) {
                  this._type = b ? enums.SHAPE_FRUSTUM_ACCURATE : enums.SHAPE_FRUSTUM;
                }
              }, {
                key: "type",
                get: function get() {
                  return this._type;
                }
              }]);

              return Frustum;
            }();

            Frustum.createOrtho = function () {
              var _temp_v3 = new Vec3();

              return function (out, width, height, near, far, transform) {
                var halfWidth = width / 2;
                var halfHeight = height / 2;
                Vec3.set(_temp_v3, halfWidth, halfHeight, near);
                Vec3.transformMat4(out.vertices[0], _temp_v3, transform);
                Vec3.set(_temp_v3, -halfWidth, halfHeight, near);
                Vec3.transformMat4(out.vertices[1], _temp_v3, transform);
                Vec3.set(_temp_v3, -halfWidth, -halfHeight, near);
                Vec3.transformMat4(out.vertices[2], _temp_v3, transform);
                Vec3.set(_temp_v3, halfWidth, -halfHeight, near);
                Vec3.transformMat4(out.vertices[3], _temp_v3, transform);
                Vec3.set(_temp_v3, halfWidth, halfHeight, far);
                Vec3.transformMat4(out.vertices[4], _temp_v3, transform);
                Vec3.set(_temp_v3, -halfWidth, halfHeight, far);
                Vec3.transformMat4(out.vertices[5], _temp_v3, transform);
                Vec3.set(_temp_v3, -halfWidth, -halfHeight, far);
                Vec3.transformMat4(out.vertices[6], _temp_v3, transform);
                Vec3.set(_temp_v3, halfWidth, -halfHeight, far);
                Vec3.transformMat4(out.vertices[7], _temp_v3, transform);
                Plane.fromPoints(out.planes[0], out.vertices[1], out.vertices[6], out.vertices[5]);
                Plane.fromPoints(out.planes[1], out.vertices[3], out.vertices[4], out.vertices[7]);
                Plane.fromPoints(out.planes[2], out.vertices[6], out.vertices[3], out.vertices[7]);
                Plane.fromPoints(out.planes[3], out.vertices[0], out.vertices[5], out.vertices[4]);
                Plane.fromPoints(out.planes[4], out.vertices[2], out.vertices[0], out.vertices[3]);
                Plane.fromPoints(out.planes[0], out.vertices[7], out.vertices[5], out.vertices[6]);
              };
            }();

            function recordFrustumToSharedMemory(handle, frstm) {
              if (!frstm || handle === NULL_HANDLE) {
                return;
              }

              var vertices = frstm.vertices;
              var vertexOffset = FrustumView.VERTICES;

              for (var i = 0; i < 8; ++i) {
                FrustumPool.setVec3(handle, vertexOffset, vertices[i]);
                vertexOffset += 3;
              }

              var planes = frstm.planes;
              var planeOffset = FrustumView.PLANES;

              for (var _i4 = 0; _i4 < 6; _i4++, planeOffset += 4) {
                FrustumPool.setVec4(handle, planeOffset, planes[_i4]);
              }
            }

            var WrapModeMask;

            (function (WrapModeMask) {
              WrapModeMask[WrapModeMask["Default"] = 0] = "Default";
              WrapModeMask[WrapModeMask["Normal"] = 1] = "Normal";
              WrapModeMask[WrapModeMask["Loop"] = 2] = "Loop";
              WrapModeMask[WrapModeMask["ShouldWrap"] = 4] = "ShouldWrap";
              WrapModeMask[WrapModeMask["Clamp"] = 8] = "Clamp";
              WrapModeMask[WrapModeMask["PingPong"] = 22] = "PingPong";
              WrapModeMask[WrapModeMask["Reverse"] = 36] = "Reverse";
            })(WrapModeMask || (WrapModeMask = {}));

            var WrapMode;

            (function (WrapMode) {
              WrapMode[WrapMode["Default"] = WrapModeMask.Default] = "Default";
              WrapMode[WrapMode["Normal"] = WrapModeMask.Normal] = "Normal";
              WrapMode[WrapMode["Reverse"] = WrapModeMask.Reverse] = "Reverse";
              WrapMode[WrapMode["Loop"] = WrapModeMask.Loop] = "Loop";
              WrapMode[WrapMode["LoopReverse"] = WrapModeMask.Loop | WrapModeMask.Reverse] = "LoopReverse";
              WrapMode[WrapMode["PingPong"] = WrapModeMask.PingPong] = "PingPong";
              WrapMode[WrapMode["PingPongReverse"] = WrapModeMask.PingPong | WrapModeMask.Reverse] = "PingPongReverse";
            })(WrapMode || (WrapMode = {}));

            ccenum(WrapMode);
            var WrappedInfo = function () {
              function WrappedInfo(info) {
                this.ratio = 0;
                this.time = 0;
                this.direction = 1;
                this.stopped = true;
                this.iterations = 0;
                this.frameIndex = undefined;

                if (info) {
                  this.set(info);
                }
              }

              var _proto = WrappedInfo.prototype;

              _proto.set = function set(info) {
                this.ratio = info.ratio;
                this.time = info.time;
                this.direction = info.direction;
                this.stopped = info.stopped;
                this.iterations = info.iterations;
                this.frameIndex = info.frameIndex;
              };

              return WrappedInfo;
            }();
            function isLerpable(object) {
              return typeof object.lerp === 'function';
            }

            var LOOK_FORWARD = 3;
            var WrapMode$1 = Enum({
              Default: WrapModeMask.Default,
              Normal: WrapModeMask.Normal,
              Clamp: WrapModeMask.Clamp,
              Loop: WrapModeMask.Loop,
              PingPong: WrapModeMask.PingPong
            });
            var Keyframe = function Keyframe() {
              this.time = 0;
              this.value = 0;
              this.inTangent = 0;
              this.outTangent = 0;
            };
            CCClass.fastDefine('cc.Keyframe', Keyframe, {
              time: 0,
              value: 0,
              inTangent: 0,
              outTangent: 0
            });
            var OptimizedKey = function () {
              function OptimizedKey() {
                this.index = void 0;
                this.time = void 0;
                this.endTime = void 0;
                this.coefficient = void 0;
                this.index = -1;
                this.time = 0;
                this.endTime = 0;
                this.coefficient = new Float32Array(4);
              }

              var _proto = OptimizedKey.prototype;

              _proto.evaluate = function evaluate(T) {
                var t = T - this.time;
                return evalOptCurve(t, this.coefficient);
              };

              return OptimizedKey;
            }();
            function evalOptCurve(t, coefs) {
              return t * (t * (t * coefs[0] + coefs[1]) + coefs[2]) + coefs[3];
            }
            var AnimationCurve = function () {
              function AnimationCurve(keyFrames) {
                if (keyFrames === void 0) {
                  keyFrames = null;
                }

                this.keyFrames = void 0;
                this.preWrapMode = WrapMode$1.Loop;
                this.postWrapMode = WrapMode$1.Clamp;
                this.cachedKey = void 0;
                this.keyFrames = keyFrames || [].concat(AnimationCurve.defaultKF);
                this.cachedKey = new OptimizedKey();
              }

              var _proto2 = AnimationCurve.prototype;

              _proto2.addKey = function addKey(keyFrame) {
                if (this.keyFrames == null) {
                  this.keyFrames = [];
                }

                this.keyFrames.push(keyFrame);
              };

              _proto2.evaluate_slow = function evaluate_slow(time) {
                var wrappedTime = time;
                var wrapMode = time < 0 ? this.preWrapMode : this.postWrapMode;
                var startTime = this.keyFrames[0].time;
                var endTime = this.keyFrames[this.keyFrames.length - 1].time;

                switch (wrapMode) {
                  case WrapMode$1.Loop:
                    wrappedTime = repeat(time - startTime, endTime - startTime) + startTime;
                    break;

                  case WrapMode$1.PingPong:
                    wrappedTime = pingPong(time - startTime, endTime - startTime) + startTime;
                    break;

                  case WrapMode$1.Default:
                  case WrapMode$1.Normal:
                  case WrapMode$1.Clamp:
                    wrappedTime = clamp(time, startTime, endTime);
                    break;

                  default:
                    wrappedTime = clamp(time, startTime, endTime);
                    break;
                }

                var preKFIndex = 0;

                if (wrappedTime > this.keyFrames[0].time) {
                  if (wrappedTime >= this.keyFrames[this.keyFrames.length - 1].time) {
                    preKFIndex = this.keyFrames.length - 2;
                  } else {
                    for (var i = 0; i < this.keyFrames.length - 1; i++) {
                      if (wrappedTime >= this.keyFrames[0].time && wrappedTime <= this.keyFrames[i + 1].time) {
                        preKFIndex = i;
                        break;
                      }
                    }
                  }
                }

                var keyframe0 = this.keyFrames[preKFIndex];
                var keyframe1 = this.keyFrames[preKFIndex + 1];
                var t = inverseLerp(keyframe0.time, keyframe1.time, wrappedTime);
                var dt = keyframe1.time - keyframe0.time;
                var m0 = keyframe0.outTangent * dt;
                var m1 = keyframe1.inTangent * dt;
                var t2 = t * t;
                var t3 = t2 * t;
                var a = 2 * t3 - 3 * t2 + 1;
                var b = t3 - 2 * t2 + t;
                var c = t3 - t2;
                var d = -2 * t3 + 3 * t2;
                return a * keyframe0.value + b * m0 + c * m1 + d * keyframe1.value;
              };

              _proto2.evaluate = function evaluate(time) {
                var wrappedTime = time;
                var wrapMode = time < 0 ? this.preWrapMode : this.postWrapMode;
                var startTime = this.keyFrames[0].time;
                var endTime = this.keyFrames[this.keyFrames.length - 1].time;

                switch (wrapMode) {
                  case WrapMode$1.Loop:
                    wrappedTime = repeat(time - startTime, endTime - startTime) + startTime;
                    break;

                  case WrapMode$1.PingPong:
                    wrappedTime = pingPong(time - startTime, endTime - startTime) + startTime;
                    break;

                  case WrapMode$1.Default:
                  case WrapMode$1.Normal:
                  case WrapMode$1.Clamp:
                    wrappedTime = clamp(time, startTime, endTime);
                    break;

                  default:
                    wrappedTime = clamp(time, startTime, endTime);
                    break;
                }

                if (wrappedTime >= this.cachedKey.time && wrappedTime < this.cachedKey.endTime) {
                  return this.cachedKey.evaluate(wrappedTime);
                }

                var leftIndex = this.findIndex(this.cachedKey, wrappedTime);
                var rightIndex = Math.min(leftIndex + 1, this.keyFrames.length - 1);
                this.calcOptimizedKey(this.cachedKey, leftIndex, rightIndex);
                return this.cachedKey.evaluate(wrappedTime);
              };

              _proto2.calcOptimizedKey = function calcOptimizedKey(optKey, leftIndex, rightIndex) {
                var lhs = this.keyFrames[leftIndex];
                var rhs = this.keyFrames[rightIndex];
                optKey.index = leftIndex;
                optKey.time = lhs.time;
                optKey.endTime = rhs.time;
                var dx = rhs.time - lhs.time;
                var dy = rhs.value - lhs.value;
                var length = 1 / (dx * dx);
                var d1 = lhs.outTangent * dx;
                var d2 = rhs.inTangent * dx;
                optKey.coefficient[0] = (d1 + d2 - dy - dy) * length / dx;
                optKey.coefficient[1] = (dy + dy + dy - d1 - d1 - d2) * length;
                optKey.coefficient[2] = lhs.outTangent;
                optKey.coefficient[3] = lhs.value;
              };

              _proto2.findIndex = function findIndex(optKey, t) {
                var cachedIndex = optKey.index;

                if (cachedIndex !== -1) {
                  var cachedTime = this.keyFrames[cachedIndex].time;

                  if (t > cachedTime) {
                    for (var i = 0; i < LOOK_FORWARD; i++) {
                      var currIndex = cachedIndex + i;

                      if (currIndex + 1 < this.keyFrames.length && this.keyFrames[currIndex + 1].time > t) {
                        return currIndex;
                      }
                    }
                  } else {
                    for (var _i = 0; _i < LOOK_FORWARD; _i++) {
                      var _currIndex = cachedIndex - _i;

                      if (_currIndex >= 0 && this.keyFrames[_currIndex - 1].time <= t) {
                        return _currIndex - 1;
                      }
                    }
                  }
                }

                var left = 0;
                var right = this.keyFrames.length;
                var mid;

                while (right - left > 1) {
                  mid = Math.floor((left + right) / 2);

                  if (this.keyFrames[mid].time >= t) {
                    right = mid;
                  } else {
                    left = mid;
                  }
                }

                return left;
              };

              return AnimationCurve;
            }();
            AnimationCurve.defaultKF = [{
              time: 0,
              value: 1,
              inTangent: 0,
              outTangent: 0
            }, {
              time: 1,
              value: 1,
              inTangent: 0,
              outTangent: 0
            }];
            CCClass.fastDefine('cc.AnimationCurve', AnimationCurve, {
              preWrapMode: WrapMode$1.Default,
              postWrapMode: WrapMode$1.Default,
              keyFrames: []
            });

            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) {
              console.warn(oldClassName + " is deprecated, please use " + newClassName + " instead.");
            }

            var line = function (_Line) {
              _inheritsLoose(line, _Line);

              function line() {
                var _this;

                _this = _Line.call(this) || this;
                deprecatedClassMessage('line', 'Line');
                return _this;
              }

              return line;
            }(Line);
            var plane = function (_Plane) {
              _inheritsLoose(plane, _Plane);

              function plane() {
                var _this2;

                _this2 = _Plane.call(this) || this;
                deprecatedClassMessage('plane', 'Plane');
                return _this2;
              }

              return plane;
            }(Plane);
            var ray = function (_Ray) {
              _inheritsLoose(ray, _Ray);

              function ray() {
                var _this3;

                _this3 = _Ray.call(this) || this;
                deprecatedClassMessage('ray', 'Ray');
                return _this3;
              }

              return ray;
            }(Ray);
            var triangle = function (_Triangle) {
              _inheritsLoose(triangle, _Triangle);

              function triangle() {
                var _this4;

                _this4 = _Triangle.call(this) || this;
                deprecatedClassMessage('triangle', 'Triangle');
                return _this4;
              }

              return triangle;
            }(Triangle);
            var sphere = function (_Sphere) {
              _inheritsLoose(sphere, _Sphere);

              function sphere() {
                var _this5;

                _this5 = _Sphere.call(this) || this;
                deprecatedClassMessage('sphere', 'Sphere');
                return _this5;
              }

              return sphere;
            }(Sphere);
            var aabb = function (_AABB) {
              _inheritsLoose(aabb, _AABB);

              function aabb() {
                var _this6;

                _this6 = _AABB.call(this) || this;
                deprecatedClassMessage('aabb', 'AABB');
                return _this6;
              }

              return aabb;
            }(AABB);
            var obb = function (_OBB) {
              _inheritsLoose(obb, _OBB);

              function obb() {
                var _this7;

                _this7 = _OBB.call(this) || this;
                deprecatedClassMessage('obb', 'OBB');
                return _this7;
              }

              return obb;
            }(OBB);
            var capsule = function (_Capsule) {
              _inheritsLoose(capsule, _Capsule);

              function capsule() {
                var _this8;

                _this8 = _Capsule.call(this) || this;
                deprecatedClassMessage('capsule', 'Capsule');
                return _this8;
              }

              return capsule;
            }(Capsule);
            var frustum = function (_Frustum) {
              _inheritsLoose(frustum, _Frustum);

              function frustum() {
                var _this9;

                _this9 = _Frustum.call(this) || this;
                deprecatedClassMessage('frustum', 'Frustum');
                return _this9;
              }

              return frustum;
            }(Frustum);

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

            var layerList = {
              NONE: 0,
              IGNORE_RAYCAST: 1 << 20,
              GIZMOS: 1 << 21,
              EDITOR: 1 << 22,
              UI_3D: 1 << 23,
              SCENE_GIZMO: 1 << 24,
              UI_2D: 1 << 25,
              PROFILER: 1 << 28,
              DEFAULT: 1 << 30,
              ALL: 0xffffffff
            };
            var Layers = exports('Layers', function () {
              function Layers() {}

              Layers.makeMaskInclude = function makeMaskInclude(includes) {
                var mask = 0;

                for (var _iterator = _createForOfIteratorHelperLoose(includes), _step; !(_step = _iterator()).done;) {
                  var inc = _step.value;
                  mask |= inc;
                }

                return mask;
              };

              Layers.makeMaskExclude = function makeMaskExclude(excludes) {
                return ~Layers.makeMaskInclude(excludes);
              };

              Layers.addLayer = function addLayer(name, bitNum) {
                if (bitNum === undefined) {
                  console.warn('bitNum can\'t be undefined');
                  return;
                }

                if (bitNum > 19 || bitNum < 0) {
                  console.warn('maximum layers reached.');
                  return;
                }

                Layers.Enum[name] = 1 << bitNum;
                Layers.Enum[bitNum] = name;
                Layers.BitMask[name] = 1 << bitNum;
                Layers.BitMask[bitNum] = name;
              };

              Layers.deleteLayer = function deleteLayer(bitNum) {
                if (bitNum > 19 || bitNum < 0) {
                  console.warn('do not change buildin layers.');
                  return;
                }

                delete Layers.Enum[Layers.Enum[bitNum]];
                delete Layers.Enum[bitNum];
                delete Layers.BitMask[Layers.BitMask[bitNum]];
                delete Layers.BitMask[bitNum];
              };

              return Layers;
            }());
            Layers.Enum = Enum(layerList);
            Layers.BitMask = BitMask(_extends({}, layerList));
            legacyCC.Layers = Layers;

            var PIPELINE_FLOW_GBUFFER = 'GbufferFlow';
            var PIPELINE_FLOW_LIGHTING = 'LightingFlow';
            var PIPELINE_FLOW_FORWARD = 'ForwardFlow';
            var PIPELINE_FLOW_SHADOW = 'ShadowFlow';
            var PIPELINE_FLOW_SMAA = 'SMAAFlow';
            var PIPELINE_FLOW_TONEMAP = 'ToneMapFlow';
            var RenderPassStage;

            (function (RenderPassStage) {
              RenderPassStage[RenderPassStage["DEFAULT"] = 100] = "DEFAULT";
              RenderPassStage[RenderPassStage["UI"] = 200] = "UI";
            })(RenderPassStage || (RenderPassStage = {}));

            legacyCC.RenderPassStage = RenderPassStage;
            var RenderPriority;

            (function (RenderPriority) {
              RenderPriority[RenderPriority["MIN"] = 0] = "MIN";
              RenderPriority[RenderPriority["MAX"] = 255] = "MAX";
              RenderPriority[RenderPriority["DEFAULT"] = 128] = "DEFAULT";
            })(RenderPriority || (RenderPriority = {}));

            var globalDescriptorSetLayout = {
              bindings: [],
              layouts: {}
            };
            var localDescriptorSetLayout = {
              bindings: [],
              layouts: {}
            };
            var PipelineGlobalBindings;

            (function (PipelineGlobalBindings) {
              PipelineGlobalBindings[PipelineGlobalBindings["UBO_GLOBAL"] = 0] = "UBO_GLOBAL";
              PipelineGlobalBindings[PipelineGlobalBindings["UBO_CAMERA"] = 1] = "UBO_CAMERA";
              PipelineGlobalBindings[PipelineGlobalBindings["UBO_SHADOW"] = 2] = "UBO_SHADOW";
              PipelineGlobalBindings[PipelineGlobalBindings["SAMPLER_SHADOWMAP"] = 3] = "SAMPLER_SHADOWMAP";
              PipelineGlobalBindings[PipelineGlobalBindings["SAMPLER_ENVIRONMENT"] = 4] = "SAMPLER_ENVIRONMENT";
              PipelineGlobalBindings[PipelineGlobalBindings["SAMPLER_SPOT_LIGHTING_MAP"] = 5] = "SAMPLER_SPOT_LIGHTING_MAP";
              PipelineGlobalBindings[PipelineGlobalBindings["SAMPLER_GBUFFER_ALBEDOMAP"] = 6] = "SAMPLER_GBUFFER_ALBEDOMAP";
              PipelineGlobalBindings[PipelineGlobalBindings["SAMPLER_GBUFFER_POSITIONMAP"] = 7] = "SAMPLER_GBUFFER_POSITIONMAP";
              PipelineGlobalBindings[PipelineGlobalBindings["SAMPLER_GBUFFER_NORMALMAP"] = 8] = "SAMPLER_GBUFFER_NORMALMAP";
              PipelineGlobalBindings[PipelineGlobalBindings["SAMPLER_GBUFFER_EMISSIVEMAP"] = 9] = "SAMPLER_GBUFFER_EMISSIVEMAP";
              PipelineGlobalBindings[PipelineGlobalBindings["SAMPLER_LIGHTING_RESULTMAP"] = 10] = "SAMPLER_LIGHTING_RESULTMAP";
              PipelineGlobalBindings[PipelineGlobalBindings["COUNT"] = 11] = "COUNT";
            })(PipelineGlobalBindings || (PipelineGlobalBindings = {}));

            var GLOBAL_UBO_COUNT = PipelineGlobalBindings.SAMPLER_SHADOWMAP;
            var GLOBAL_SAMPLER_COUNT = PipelineGlobalBindings.COUNT - GLOBAL_UBO_COUNT;
            var ModelLocalBindings;

            (function (ModelLocalBindings) {
              ModelLocalBindings[ModelLocalBindings["UBO_LOCAL"] = 0] = "UBO_LOCAL";
              ModelLocalBindings[ModelLocalBindings["UBO_FORWARD_LIGHTS"] = 1] = "UBO_FORWARD_LIGHTS";
              ModelLocalBindings[ModelLocalBindings["UBO_SKINNING_ANIMATION"] = 2] = "UBO_SKINNING_ANIMATION";
              ModelLocalBindings[ModelLocalBindings["UBO_SKINNING_TEXTURE"] = 3] = "UBO_SKINNING_TEXTURE";
              ModelLocalBindings[ModelLocalBindings["UBO_MORPH"] = 4] = "UBO_MORPH";
              ModelLocalBindings[ModelLocalBindings["SAMPLER_JOINTS"] = 5] = "SAMPLER_JOINTS";
              ModelLocalBindings[ModelLocalBindings["SAMPLER_MORPH_POSITION"] = 6] = "SAMPLER_MORPH_POSITION";
              ModelLocalBindings[ModelLocalBindings["SAMPLER_MORPH_NORMAL"] = 7] = "SAMPLER_MORPH_NORMAL";
              ModelLocalBindings[ModelLocalBindings["SAMPLER_MORPH_TANGENT"] = 8] = "SAMPLER_MORPH_TANGENT";
              ModelLocalBindings[ModelLocalBindings["SAMPLER_LIGHTMAP"] = 9] = "SAMPLER_LIGHTMAP";
              ModelLocalBindings[ModelLocalBindings["SAMPLER_SPRITE"] = 10] = "SAMPLER_SPRITE";
              ModelLocalBindings[ModelLocalBindings["COUNT"] = 11] = "COUNT";
            })(ModelLocalBindings || (ModelLocalBindings = {}));

            var LOCAL_UBO_COUNT = ModelLocalBindings.SAMPLER_JOINTS;
            var LOCAL_SAMPLER_COUNT = ModelLocalBindings.COUNT - LOCAL_UBO_COUNT;
            var SetIndex;

            (function (SetIndex) {
              SetIndex[SetIndex["GLOBAL"] = 0] = "GLOBAL";
              SetIndex[SetIndex["MATERIAL"] = 1] = "MATERIAL";
              SetIndex[SetIndex["LOCAL"] = 2] = "LOCAL";
            })(SetIndex || (SetIndex = {}));

            var bindingMappingInfo = new BindingMappingInfo();
            bindingMappingInfo.bufferOffsets = [0, GLOBAL_UBO_COUNT + LOCAL_UBO_COUNT, GLOBAL_UBO_COUNT];
            bindingMappingInfo.samplerOffsets = [-GLOBAL_UBO_COUNT, GLOBAL_SAMPLER_COUNT + LOCAL_SAMPLER_COUNT, GLOBAL_SAMPLER_COUNT - LOCAL_UBO_COUNT];
            bindingMappingInfo.flexibleSet = 1;
            var UBOGlobal = function UBOGlobal() {};
            UBOGlobal.TIME_OFFSET = 0;
            UBOGlobal.NATIVE_SIZE_OFFSET = UBOGlobal.TIME_OFFSET + 4;
            UBOGlobal.SCREEN_SIZE_OFFSET = UBOGlobal.NATIVE_SIZE_OFFSET + 4;
            UBOGlobal.COUNT = UBOGlobal.SCREEN_SIZE_OFFSET + 4;
            UBOGlobal.SIZE = UBOGlobal.COUNT * 4;
            UBOGlobal.NAME = 'CCGlobal';
            UBOGlobal.BINDING = PipelineGlobalBindings.UBO_GLOBAL;
            UBOGlobal.DESCRIPTOR = new DescriptorSetLayoutBinding(UBOGlobal.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.ALL);
            UBOGlobal.LAYOUT = new UniformBlock(SetIndex.GLOBAL, UBOGlobal.BINDING, UBOGlobal.NAME, [new Uniform('cc_time', Type.FLOAT4, 1), new Uniform('cc_screenSize', Type.FLOAT4, 1), new Uniform('cc_nativeSize', Type.FLOAT4, 1)], 1);
            globalDescriptorSetLayout.layouts[UBOGlobal.NAME] = UBOGlobal.LAYOUT;
            globalDescriptorSetLayout.bindings[UBOGlobal.BINDING] = UBOGlobal.DESCRIPTOR;
            var UBOCamera = function UBOCamera() {};
            UBOCamera.MAT_VIEW_OFFSET = 0;
            UBOCamera.MAT_VIEW_INV_OFFSET = UBOCamera.MAT_VIEW_OFFSET + 16;
            UBOCamera.MAT_PROJ_OFFSET = UBOCamera.MAT_VIEW_INV_OFFSET + 16;
            UBOCamera.MAT_PROJ_INV_OFFSET = UBOCamera.MAT_PROJ_OFFSET + 16;
            UBOCamera.MAT_VIEW_PROJ_OFFSET = UBOCamera.MAT_PROJ_INV_OFFSET + 16;
            UBOCamera.MAT_VIEW_PROJ_INV_OFFSET = UBOCamera.MAT_VIEW_PROJ_OFFSET + 16;
            UBOCamera.CAMERA_POS_OFFSET = UBOCamera.MAT_VIEW_PROJ_INV_OFFSET + 16;
            UBOCamera.SCREEN_SCALE_OFFSET = UBOCamera.CAMERA_POS_OFFSET + 4;
            UBOCamera.EXPOSURE_OFFSET = UBOCamera.SCREEN_SCALE_OFFSET + 4;
            UBOCamera.MAIN_LIT_DIR_OFFSET = UBOCamera.EXPOSURE_OFFSET + 4;
            UBOCamera.MAIN_LIT_COLOR_OFFSET = UBOCamera.MAIN_LIT_DIR_OFFSET + 4;
            UBOCamera.AMBIENT_SKY_OFFSET = UBOCamera.MAIN_LIT_COLOR_OFFSET + 4;
            UBOCamera.AMBIENT_GROUND_OFFSET = UBOCamera.AMBIENT_SKY_OFFSET + 4;
            UBOCamera.GLOBAL_FOG_COLOR_OFFSET = UBOCamera.AMBIENT_GROUND_OFFSET + 4;
            UBOCamera.GLOBAL_FOG_BASE_OFFSET = UBOCamera.GLOBAL_FOG_COLOR_OFFSET + 4;
            UBOCamera.GLOBAL_FOG_ADD_OFFSET = UBOCamera.GLOBAL_FOG_BASE_OFFSET + 4;
            UBOCamera.COUNT = UBOCamera.GLOBAL_FOG_ADD_OFFSET + 4;
            UBOCamera.SIZE = UBOCamera.COUNT * 4;
            UBOCamera.NAME = 'CCCamera';
            UBOCamera.BINDING = PipelineGlobalBindings.UBO_CAMERA;
            UBOCamera.DESCRIPTOR = new DescriptorSetLayoutBinding(UBOCamera.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.ALL);
            UBOCamera.LAYOUT = new UniformBlock(SetIndex.GLOBAL, UBOCamera.BINDING, UBOCamera.NAME, [new Uniform('cc_matView', Type.MAT4, 1), new Uniform('cc_matViewInv', Type.MAT4, 1), new Uniform('cc_matProj', Type.MAT4, 1), new Uniform('cc_matProjInv', Type.MAT4, 1), new Uniform('cc_matViewProj', Type.MAT4, 1), new Uniform('cc_matViewProjInv', Type.MAT4, 1), new Uniform('cc_cameraPos', Type.FLOAT4, 1), new Uniform('cc_screenScale', Type.FLOAT4, 1), new Uniform('cc_exposure', Type.FLOAT4, 1), new Uniform('cc_mainLitDir', Type.FLOAT4, 1), new Uniform('cc_mainLitColor', Type.FLOAT4, 1), new Uniform('cc_ambientSky', Type.FLOAT4, 1), new Uniform('cc_ambientGround', Type.FLOAT4, 1), new Uniform('cc_fogColor', Type.FLOAT4, 1), new Uniform('cc_fogBase', Type.FLOAT4, 1), new Uniform('cc_fogAdd', Type.FLOAT4, 1)], 1);
            globalDescriptorSetLayout.layouts[UBOCamera.NAME] = UBOCamera.LAYOUT;
            globalDescriptorSetLayout.bindings[UBOCamera.BINDING] = UBOCamera.DESCRIPTOR;
            var UBOShadow = function UBOShadow() {};
            UBOShadow.MAT_LIGHT_PLANE_PROJ_OFFSET = 0;
            UBOShadow.MAT_LIGHT_VIEW_OFFSET = UBOShadow.MAT_LIGHT_PLANE_PROJ_OFFSET + 16;
            UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET = UBOShadow.MAT_LIGHT_VIEW_OFFSET + 16;
            UBOShadow.SHADOW_NEAR_FAR_LINEAR_SELF_INFO_OFFSET = UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET + 16;
            UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET = UBOShadow.SHADOW_NEAR_FAR_LINEAR_SELF_INFO_OFFSET + 4;
            UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET = UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 4;
            UBOShadow.SHADOW_COLOR_OFFSET = UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 4;
            UBOShadow.COUNT = UBOShadow.SHADOW_COLOR_OFFSET + 4;
            UBOShadow.SIZE = UBOShadow.COUNT * 4;
            UBOShadow.NAME = 'CCShadow';
            UBOShadow.BINDING = PipelineGlobalBindings.UBO_SHADOW;
            UBOShadow.DESCRIPTOR = new DescriptorSetLayoutBinding(UBOShadow.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.ALL);
            UBOShadow.LAYOUT = new UniformBlock(SetIndex.GLOBAL, UBOShadow.BINDING, UBOShadow.NAME, [new Uniform('cc_matLightPlaneProj', Type.MAT4, 1), new Uniform('cc_matLightView', Type.MAT4, 1), new Uniform('cc_matLightViewProj', Type.MAT4, 1), new Uniform('cc_shadowNFLSInfo', Type.FLOAT4, 1), new Uniform('cc_shadowWHPBInfo', Type.FLOAT4, 1), new Uniform('cc_shadowLPNNInfo', Type.FLOAT4, 1), new Uniform('cc_shadowColor', Type.FLOAT4, 1)], 1);
            globalDescriptorSetLayout.layouts[UBOShadow.NAME] = UBOShadow.LAYOUT;
            globalDescriptorSetLayout.bindings[UBOShadow.BINDING] = UBOShadow.DESCRIPTOR;
            var UNIFORM_SHADOWMAP_NAME = 'cc_shadowMap';
            var UNIFORM_SHADOWMAP_BINDING = PipelineGlobalBindings.SAMPLER_SHADOWMAP;
            var UNIFORM_SHADOWMAP_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_SHADOWMAP_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT);
            var UNIFORM_SHADOWMAP_LAYOUT = new UniformSamplerTexture(SetIndex.GLOBAL, UNIFORM_SHADOWMAP_BINDING, UNIFORM_SHADOWMAP_NAME, Type.SAMPLER2D, 1);
            globalDescriptorSetLayout.layouts[UNIFORM_SHADOWMAP_NAME] = UNIFORM_SHADOWMAP_LAYOUT;
            globalDescriptorSetLayout.bindings[UNIFORM_SHADOWMAP_BINDING] = UNIFORM_SHADOWMAP_DESCRIPTOR;
            var UNIFORM_GBUFFER_ALBEDOMAP_NAME = 'cc_gbuffer_albedoMap';
            var UNIFORM_GBUFFER_ALBEDOMAP_BINDING = PipelineGlobalBindings.SAMPLER_GBUFFER_ALBEDOMAP;
            var UNIFORM_GBUFFER_ALBEDOMAP_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_GBUFFER_ALBEDOMAP_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT);
            var UNIFORM_GBUFFER_ALBEDOMAP_LAYOUT = new UniformSamplerTexture(SetIndex.GLOBAL, UNIFORM_GBUFFER_ALBEDOMAP_BINDING, UNIFORM_GBUFFER_ALBEDOMAP_NAME, Type.SAMPLER2D, 1);
            globalDescriptorSetLayout.layouts[UNIFORM_GBUFFER_ALBEDOMAP_NAME] = UNIFORM_GBUFFER_ALBEDOMAP_LAYOUT;
            globalDescriptorSetLayout.bindings[UNIFORM_GBUFFER_ALBEDOMAP_BINDING] = UNIFORM_GBUFFER_ALBEDOMAP_DESCRIPTOR;
            var UNIFORM_GBUFFER_POSITIONMAP_NAME = 'cc_gbuffer_positionMap';
            var UNIFORM_GBUFFER_POSITIONMAP_BINDING = PipelineGlobalBindings.SAMPLER_GBUFFER_POSITIONMAP;
            var UNIFORM_GBUFFER_POSITIONMAP_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_GBUFFER_POSITIONMAP_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT);
            var UNIFORM_GBUFFER_POSITIONMAP_LAYOUT = new UniformSamplerTexture(SetIndex.GLOBAL, UNIFORM_GBUFFER_POSITIONMAP_BINDING, UNIFORM_GBUFFER_POSITIONMAP_NAME, Type.SAMPLER2D, 1);
            globalDescriptorSetLayout.layouts[UNIFORM_GBUFFER_POSITIONMAP_NAME] = UNIFORM_GBUFFER_POSITIONMAP_LAYOUT;
            globalDescriptorSetLayout.bindings[UNIFORM_GBUFFER_POSITIONMAP_BINDING] = UNIFORM_GBUFFER_POSITIONMAP_DESCRIPTOR;
            var UNIFORM_GBUFFER_NORMALMAP_NAME = 'cc_gbuffer_normalMap';
            var UNIFORM_GBUFFER_NORMALMAP_BINDING = PipelineGlobalBindings.SAMPLER_GBUFFER_NORMALMAP;
            var UNIFORM_GBUFFER_NORMALMAP_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_GBUFFER_NORMALMAP_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT);
            var UNIFORM_GBUFFER_NORMALMAP_LAYOUT = new UniformSamplerTexture(SetIndex.GLOBAL, UNIFORM_GBUFFER_NORMALMAP_BINDING, UNIFORM_GBUFFER_NORMALMAP_NAME, Type.SAMPLER2D, 1);
            globalDescriptorSetLayout.layouts[UNIFORM_GBUFFER_NORMALMAP_NAME] = UNIFORM_GBUFFER_NORMALMAP_LAYOUT;
            globalDescriptorSetLayout.bindings[UNIFORM_GBUFFER_NORMALMAP_BINDING] = UNIFORM_GBUFFER_NORMALMAP_DESCRIPTOR;
            var UNIFORM_LIGHTING_RESULTMAP_NAME = 'cc_lighting_resultMap';
            var UNIFORM_LIGHTING_RESULTMAP_BINDING = PipelineGlobalBindings.SAMPLER_LIGHTING_RESULTMAP;
            var UNIFORM_LIGHTING_RESULTMAP_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_LIGHTING_RESULTMAP_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT);
            var UNIFORM_LIGHTING_RESULTMAP_LAYOUT = new UniformSamplerTexture(SetIndex.GLOBAL, UNIFORM_LIGHTING_RESULTMAP_BINDING, UNIFORM_LIGHTING_RESULTMAP_NAME, Type.SAMPLER2D, 1);
            globalDescriptorSetLayout.layouts[UNIFORM_LIGHTING_RESULTMAP_NAME] = UNIFORM_LIGHTING_RESULTMAP_LAYOUT;
            globalDescriptorSetLayout.bindings[UNIFORM_LIGHTING_RESULTMAP_BINDING] = UNIFORM_LIGHTING_RESULTMAP_DESCRIPTOR;
            var UNIFORM_GBUFFER_EMISSIVEMAP_NAME = 'cc_gbuffer_emissiveMap';
            var UNIFORM_GBUFFER_EMISSIVEMAP_BINDING = PipelineGlobalBindings.SAMPLER_GBUFFER_EMISSIVEMAP;
            var UNIFORM_GBUFFER_EMISSIVEMAP_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_GBUFFER_EMISSIVEMAP_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT);
            var UNIFORM_GBUFFER_EMISSIVEMAP_LAYOUT = new UniformSamplerTexture(SetIndex.GLOBAL, UNIFORM_GBUFFER_EMISSIVEMAP_BINDING, UNIFORM_GBUFFER_EMISSIVEMAP_NAME, Type.SAMPLER2D, 1);
            globalDescriptorSetLayout.layouts[UNIFORM_GBUFFER_EMISSIVEMAP_NAME] = UNIFORM_GBUFFER_EMISSIVEMAP_LAYOUT;
            globalDescriptorSetLayout.bindings[UNIFORM_GBUFFER_EMISSIVEMAP_BINDING] = UNIFORM_GBUFFER_EMISSIVEMAP_DESCRIPTOR;
            var UNIFORM_ENVIRONMENT_NAME = 'cc_environment';
            var UNIFORM_ENVIRONMENT_BINDING = PipelineGlobalBindings.SAMPLER_ENVIRONMENT;
            var UNIFORM_ENVIRONMENT_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_ENVIRONMENT_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT);
            var UNIFORM_ENVIRONMENT_LAYOUT = new UniformSamplerTexture(SetIndex.GLOBAL, UNIFORM_ENVIRONMENT_BINDING, UNIFORM_ENVIRONMENT_NAME, Type.SAMPLER_CUBE, 1);
            globalDescriptorSetLayout.layouts[UNIFORM_ENVIRONMENT_NAME] = UNIFORM_ENVIRONMENT_LAYOUT;
            globalDescriptorSetLayout.bindings[UNIFORM_ENVIRONMENT_BINDING] = UNIFORM_ENVIRONMENT_DESCRIPTOR;
            var UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_NAME = 'cc_spotLightingMap';
            var UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING = PipelineGlobalBindings.SAMPLER_SPOT_LIGHTING_MAP;
            var UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT);
            var UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.GLOBAL, UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING, UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_NAME, Type.SAMPLER2D, 1);
            globalDescriptorSetLayout.layouts[UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_NAME] = UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_LAYOUT;
            globalDescriptorSetLayout.bindings[UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING] = UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_DESCRIPTOR;
            var UBOLocal = function UBOLocal() {};
            UBOLocal.MAT_WORLD_OFFSET = 0;
            UBOLocal.MAT_WORLD_IT_OFFSET = UBOLocal.MAT_WORLD_OFFSET + 16;
            UBOLocal.LIGHTINGMAP_UVPARAM = UBOLocal.MAT_WORLD_IT_OFFSET + 16;
            UBOLocal.COUNT = UBOLocal.LIGHTINGMAP_UVPARAM + 4;
            UBOLocal.SIZE = UBOLocal.COUNT * 4;
            UBOLocal.NAME = 'CCLocal';
            UBOLocal.BINDING = ModelLocalBindings.UBO_LOCAL;
            UBOLocal.DESCRIPTOR = new DescriptorSetLayoutBinding(UBOLocal.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.VERTEX);
            UBOLocal.LAYOUT = new UniformBlock(SetIndex.LOCAL, UBOLocal.BINDING, UBOLocal.NAME, [new Uniform('cc_matWorld', Type.MAT4, 1), new Uniform('cc_matWorldIT', Type.MAT4, 1), new Uniform('cc_lightingMapUVParam', Type.FLOAT4, 1)], 1);
            localDescriptorSetLayout.layouts[UBOLocal.NAME] = UBOLocal.LAYOUT;
            localDescriptorSetLayout.bindings[UBOLocal.BINDING] = UBOLocal.DESCRIPTOR;
            var INST_MAT_WORLD = 'a_matWorld0';
            var UBOLocalBatched = function UBOLocalBatched() {};
            UBOLocalBatched.BATCHING_COUNT = 10;
            UBOLocalBatched.MAT_WORLDS_OFFSET = 0;
            UBOLocalBatched.COUNT = 16 * UBOLocalBatched.BATCHING_COUNT;
            UBOLocalBatched.SIZE = UBOLocalBatched.COUNT * 4;
            UBOLocalBatched.NAME = 'CCLocalBatched';
            UBOLocalBatched.BINDING = ModelLocalBindings.UBO_LOCAL;
            UBOLocalBatched.DESCRIPTOR = new DescriptorSetLayoutBinding(UBOLocalBatched.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.VERTEX);
            UBOLocalBatched.LAYOUT = new UniformBlock(SetIndex.LOCAL, UBOLocalBatched.BINDING, UBOLocalBatched.NAME, [new Uniform('cc_matWorlds', Type.MAT4, UBOLocalBatched.BATCHING_COUNT)], 1);
            localDescriptorSetLayout.layouts[UBOLocalBatched.NAME] = UBOLocalBatched.LAYOUT;
            localDescriptorSetLayout.bindings[UBOLocalBatched.BINDING] = UBOLocalBatched.DESCRIPTOR;
            var UBOForwardLight = function UBOForwardLight() {};
            UBOForwardLight.LIGHTS_PER_PASS = 1;
            UBOForwardLight.LIGHT_POS_OFFSET = 0;
            UBOForwardLight.LIGHT_COLOR_OFFSET = UBOForwardLight.LIGHT_POS_OFFSET + UBOForwardLight.LIGHTS_PER_PASS * 4;
            UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET = UBOForwardLight.LIGHT_COLOR_OFFSET + UBOForwardLight.LIGHTS_PER_PASS * 4;
            UBOForwardLight.LIGHT_DIR_OFFSET = UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET + UBOForwardLight.LIGHTS_PER_PASS * 4;
            UBOForwardLight.COUNT = UBOForwardLight.LIGHT_DIR_OFFSET + UBOForwardLight.LIGHTS_PER_PASS * 4;
            UBOForwardLight.SIZE = UBOForwardLight.COUNT * 4;
            UBOForwardLight.NAME = 'CCForwardLight';
            UBOForwardLight.BINDING = ModelLocalBindings.UBO_FORWARD_LIGHTS;
            UBOForwardLight.DESCRIPTOR = new DescriptorSetLayoutBinding(UBOForwardLight.BINDING, DescriptorType.DYNAMIC_UNIFORM_BUFFER, 1, ShaderStageFlagBit.FRAGMENT);
            UBOForwardLight.LAYOUT = new UniformBlock(SetIndex.LOCAL, UBOForwardLight.BINDING, UBOForwardLight.NAME, [new Uniform('cc_lightPos', Type.FLOAT4, UBOForwardLight.LIGHTS_PER_PASS), new Uniform('cc_lightColor', Type.FLOAT4, UBOForwardLight.LIGHTS_PER_PASS), new Uniform('cc_lightSizeRangeAngle', Type.FLOAT4, UBOForwardLight.LIGHTS_PER_PASS), new Uniform('cc_lightDir', Type.FLOAT4, UBOForwardLight.LIGHTS_PER_PASS)], 1);
            localDescriptorSetLayout.layouts[UBOForwardLight.NAME] = UBOForwardLight.LAYOUT;
            localDescriptorSetLayout.bindings[UBOForwardLight.BINDING] = UBOForwardLight.DESCRIPTOR;
            var UBODeferredLight = function UBODeferredLight() {};
            UBODeferredLight.LIGHTS_PER_PASS = 10;
            var JOINT_UNIFORM_CAPACITY = 30;
            var UBOSkinningTexture = function UBOSkinningTexture() {};
            UBOSkinningTexture.JOINTS_TEXTURE_INFO_OFFSET = 0;
            UBOSkinningTexture.COUNT = UBOSkinningTexture.JOINTS_TEXTURE_INFO_OFFSET + 4;
            UBOSkinningTexture.SIZE = UBOSkinningTexture.COUNT * 4;
            UBOSkinningTexture.NAME = 'CCSkinningTexture';
            UBOSkinningTexture.BINDING = ModelLocalBindings.UBO_SKINNING_TEXTURE;
            UBOSkinningTexture.DESCRIPTOR = new DescriptorSetLayoutBinding(UBOSkinningTexture.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.VERTEX);
            UBOSkinningTexture.LAYOUT = new UniformBlock(SetIndex.LOCAL, UBOSkinningTexture.BINDING, UBOSkinningTexture.NAME, [new Uniform('cc_jointTextureInfo', Type.FLOAT4, 1)], 1);
            localDescriptorSetLayout.layouts[UBOSkinningTexture.NAME] = UBOSkinningTexture.LAYOUT;
            localDescriptorSetLayout.bindings[UBOSkinningTexture.BINDING] = UBOSkinningTexture.DESCRIPTOR;
            var UBOSkinningAnimation = function UBOSkinningAnimation() {};
            UBOSkinningAnimation.JOINTS_ANIM_INFO_OFFSET = 0;
            UBOSkinningAnimation.COUNT = UBOSkinningAnimation.JOINTS_ANIM_INFO_OFFSET + 4;
            UBOSkinningAnimation.SIZE = UBOSkinningAnimation.COUNT * 4;
            UBOSkinningAnimation.NAME = 'CCSkinningAnimation';
            UBOSkinningAnimation.BINDING = ModelLocalBindings.UBO_SKINNING_ANIMATION;
            UBOSkinningAnimation.DESCRIPTOR = new DescriptorSetLayoutBinding(UBOSkinningAnimation.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.VERTEX);
            UBOSkinningAnimation.LAYOUT = new UniformBlock(SetIndex.LOCAL, UBOSkinningAnimation.BINDING, UBOSkinningAnimation.NAME, [new Uniform('cc_jointAnimInfo', Type.FLOAT4, 1)], 1);
            localDescriptorSetLayout.layouts[UBOSkinningAnimation.NAME] = UBOSkinningAnimation.LAYOUT;
            localDescriptorSetLayout.bindings[UBOSkinningAnimation.BINDING] = UBOSkinningAnimation.DESCRIPTOR;
            var INST_JOINT_ANIM_INFO = 'a_jointAnimInfo';
            var UBOSkinning = function UBOSkinning() {};
            UBOSkinning.JOINTS_OFFSET = 0;
            UBOSkinning.COUNT = UBOSkinning.JOINTS_OFFSET + JOINT_UNIFORM_CAPACITY * 12;
            UBOSkinning.SIZE = UBOSkinning.COUNT * 4;
            UBOSkinning.NAME = 'CCSkinning';
            UBOSkinning.BINDING = ModelLocalBindings.UBO_SKINNING_TEXTURE;
            UBOSkinning.DESCRIPTOR = new DescriptorSetLayoutBinding(UBOSkinning.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.VERTEX);
            UBOSkinning.LAYOUT = new UniformBlock(SetIndex.LOCAL, UBOSkinning.BINDING, UBOSkinning.NAME, [new Uniform('cc_joints', Type.FLOAT4, JOINT_UNIFORM_CAPACITY * 3)], 1);
            localDescriptorSetLayout.layouts[UBOSkinning.NAME] = UBOSkinning.LAYOUT;
            localDescriptorSetLayout.bindings[UBOSkinning.BINDING] = UBOSkinning.DESCRIPTOR;
            var UBOMorph = function UBOMorph() {};
            UBOMorph.MAX_MORPH_TARGET_COUNT = 60;
            UBOMorph.OFFSET_OF_WEIGHTS = 0;
            UBOMorph.OFFSET_OF_DISPLACEMENT_TEXTURE_WIDTH = 4 * UBOMorph.MAX_MORPH_TARGET_COUNT;
            UBOMorph.OFFSET_OF_DISPLACEMENT_TEXTURE_HEIGHT = UBOMorph.OFFSET_OF_DISPLACEMENT_TEXTURE_WIDTH + 4;
            UBOMorph.OFFSET_OF_VERTICES_COUNT = UBOMorph.OFFSET_OF_DISPLACEMENT_TEXTURE_HEIGHT + 4;
            UBOMorph.COUNT_BASE_4_BYTES = 4 * Math.ceil(UBOMorph.MAX_MORPH_TARGET_COUNT / 4) + 4;
            UBOMorph.SIZE = UBOMorph.COUNT_BASE_4_BYTES * 4;
            UBOMorph.NAME = 'CCMorph';
            UBOMorph.BINDING = ModelLocalBindings.UBO_MORPH;
            UBOMorph.DESCRIPTOR = new DescriptorSetLayoutBinding(UBOMorph.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.VERTEX);
            UBOMorph.LAYOUT = new UniformBlock(SetIndex.LOCAL, UBOMorph.BINDING, UBOMorph.NAME, [new Uniform('cc_displacementWeights', Type.FLOAT4, UBOMorph.MAX_MORPH_TARGET_COUNT / 4), new Uniform('cc_displacementTextureInfo', Type.FLOAT4, 1)], 1);
            localDescriptorSetLayout.layouts[UBOMorph.NAME] = UBOMorph.LAYOUT;
            localDescriptorSetLayout.bindings[UBOMorph.BINDING] = UBOMorph.DESCRIPTOR;
            var UNIFORM_JOINT_TEXTURE_NAME = 'cc_jointTexture';
            var UNIFORM_JOINT_TEXTURE_BINDING = ModelLocalBindings.SAMPLER_JOINTS;
            var UNIFORM_JOINT_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_JOINT_TEXTURE_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.VERTEX);
            var UNIFORM_JOINT_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_JOINT_TEXTURE_BINDING, UNIFORM_JOINT_TEXTURE_NAME, Type.SAMPLER2D, 1);
            localDescriptorSetLayout.layouts[UNIFORM_JOINT_TEXTURE_NAME] = UNIFORM_JOINT_TEXTURE_LAYOUT;
            localDescriptorSetLayout.bindings[UNIFORM_JOINT_TEXTURE_BINDING] = UNIFORM_JOINT_TEXTURE_DESCRIPTOR;
            var UNIFORM_POSITION_MORPH_TEXTURE_NAME = 'cc_PositionDisplacements';
            var UNIFORM_POSITION_MORPH_TEXTURE_BINDING = ModelLocalBindings.SAMPLER_MORPH_POSITION;
            var UNIFORM_POSITION_MORPH_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_POSITION_MORPH_TEXTURE_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.VERTEX);
            var UNIFORM_POSITION_MORPH_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_POSITION_MORPH_TEXTURE_BINDING, UNIFORM_POSITION_MORPH_TEXTURE_NAME, Type.SAMPLER2D, 1);
            localDescriptorSetLayout.layouts[UNIFORM_POSITION_MORPH_TEXTURE_NAME] = UNIFORM_POSITION_MORPH_TEXTURE_LAYOUT;
            localDescriptorSetLayout.bindings[UNIFORM_POSITION_MORPH_TEXTURE_BINDING] = UNIFORM_POSITION_MORPH_TEXTURE_DESCRIPTOR;
            var UNIFORM_NORMAL_MORPH_TEXTURE_NAME = 'cc_NormalDisplacements';
            var UNIFORM_NORMAL_MORPH_TEXTURE_BINDING = ModelLocalBindings.SAMPLER_MORPH_NORMAL;
            var UNIFORM_NORMAL_MORPH_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_NORMAL_MORPH_TEXTURE_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.VERTEX);
            var UNIFORM_NORMAL_MORPH_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_NORMAL_MORPH_TEXTURE_BINDING, UNIFORM_NORMAL_MORPH_TEXTURE_NAME, Type.SAMPLER2D, 1);
            localDescriptorSetLayout.layouts[UNIFORM_NORMAL_MORPH_TEXTURE_NAME] = UNIFORM_NORMAL_MORPH_TEXTURE_LAYOUT;
            localDescriptorSetLayout.bindings[UNIFORM_NORMAL_MORPH_TEXTURE_BINDING] = UNIFORM_NORMAL_MORPH_TEXTURE_DESCRIPTOR;
            var UNIFORM_TANGENT_MORPH_TEXTURE_NAME = 'cc_TangentDisplacements';
            var UNIFORM_TANGENT_MORPH_TEXTURE_BINDING = ModelLocalBindings.SAMPLER_MORPH_TANGENT;
            var UNIFORM_TANGENT_MORPH_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_TANGENT_MORPH_TEXTURE_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.VERTEX);
            var UNIFORM_TANGENT_MORPH_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_TANGENT_MORPH_TEXTURE_BINDING, UNIFORM_TANGENT_MORPH_TEXTURE_NAME, Type.SAMPLER2D, 1);
            localDescriptorSetLayout.layouts[UNIFORM_TANGENT_MORPH_TEXTURE_NAME] = UNIFORM_TANGENT_MORPH_TEXTURE_LAYOUT;
            localDescriptorSetLayout.bindings[UNIFORM_TANGENT_MORPH_TEXTURE_BINDING] = UNIFORM_TANGENT_MORPH_TEXTURE_DESCRIPTOR;
            var UNIFORM_LIGHTMAP_TEXTURE_NAME = 'cc_lightingMap';
            var UNIFORM_LIGHTMAP_TEXTURE_BINDING = ModelLocalBindings.SAMPLER_LIGHTMAP;
            var UNIFORM_LIGHTMAP_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_LIGHTMAP_TEXTURE_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT);
            var UNIFORM_LIGHTMAP_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_LIGHTMAP_TEXTURE_BINDING, UNIFORM_LIGHTMAP_TEXTURE_NAME, Type.SAMPLER2D, 1);
            localDescriptorSetLayout.layouts[UNIFORM_LIGHTMAP_TEXTURE_NAME] = UNIFORM_LIGHTMAP_TEXTURE_LAYOUT;
            localDescriptorSetLayout.bindings[UNIFORM_LIGHTMAP_TEXTURE_BINDING] = UNIFORM_LIGHTMAP_TEXTURE_DESCRIPTOR;
            var UNIFORM_SPRITE_TEXTURE_NAME = 'cc_spriteTexture';
            var UNIFORM_SPRITE_TEXTURE_BINDING = ModelLocalBindings.SAMPLER_SPRITE;
            var UNIFORM_SPRITE_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_SPRITE_TEXTURE_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT);
            var UNIFORM_SPRITE_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_SPRITE_TEXTURE_BINDING, UNIFORM_SPRITE_TEXTURE_NAME, Type.SAMPLER2D, 1);
            localDescriptorSetLayout.layouts[UNIFORM_SPRITE_TEXTURE_NAME] = UNIFORM_SPRITE_TEXTURE_LAYOUT;
            localDescriptorSetLayout.bindings[UNIFORM_SPRITE_TEXTURE_BINDING] = UNIFORM_SPRITE_TEXTURE_DESCRIPTOR;
            var CAMERA_DEFAULT_MASK = Layers.makeMaskExclude([Layers.BitMask.UI_2D, Layers.BitMask.GIZMOS, Layers.BitMask.EDITOR, Layers.BitMask.SCENE_GIZMO, Layers.BitMask.PROFILER]);
            var CAMERA_EDITOR_MASK = Layers.makeMaskExclude([Layers.BitMask.UI_2D, Layers.BitMask.PROFILER]);
            var MODEL_ALWAYS_MASK = Layers.Enum.ALL;
            function supportsHalfFloatTexture(device) {
              return device.hasFeature(Feature.COLOR_HALF_FLOAT) && device.hasFeature(Feature.TEXTURE_HALF_FLOAT) && !(device.gfxAPI === API.WEBGL);
            }

            var define$1 = /*#__PURE__*/Object.freeze({
                __proto__: null,
                PIPELINE_FLOW_GBUFFER: PIPELINE_FLOW_GBUFFER,
                PIPELINE_FLOW_LIGHTING: PIPELINE_FLOW_LIGHTING,
                PIPELINE_FLOW_FORWARD: PIPELINE_FLOW_FORWARD,
                PIPELINE_FLOW_SHADOW: PIPELINE_FLOW_SHADOW,
                PIPELINE_FLOW_SMAA: PIPELINE_FLOW_SMAA,
                PIPELINE_FLOW_TONEMAP: PIPELINE_FLOW_TONEMAP,
                get RenderPassStage () { return RenderPassStage; },
                get RenderPriority () { return RenderPriority; },
                globalDescriptorSetLayout: globalDescriptorSetLayout,
                localDescriptorSetLayout: localDescriptorSetLayout,
                get PipelineGlobalBindings () { return PipelineGlobalBindings; },
                get ModelLocalBindings () { return ModelLocalBindings; },
                get SetIndex () { return SetIndex; },
                bindingMappingInfo: bindingMappingInfo,
                UBOGlobal: UBOGlobal,
                UBOCamera: UBOCamera,
                UBOShadow: UBOShadow,
                UNIFORM_SHADOWMAP_BINDING: UNIFORM_SHADOWMAP_BINDING,
                UNIFORM_GBUFFER_ALBEDOMAP_BINDING: UNIFORM_GBUFFER_ALBEDOMAP_BINDING,
                UNIFORM_GBUFFER_POSITIONMAP_BINDING: UNIFORM_GBUFFER_POSITIONMAP_BINDING,
                UNIFORM_GBUFFER_NORMALMAP_BINDING: UNIFORM_GBUFFER_NORMALMAP_BINDING,
                UNIFORM_LIGHTING_RESULTMAP_BINDING: UNIFORM_LIGHTING_RESULTMAP_BINDING,
                UNIFORM_GBUFFER_EMISSIVEMAP_BINDING: UNIFORM_GBUFFER_EMISSIVEMAP_BINDING,
                UNIFORM_ENVIRONMENT_BINDING: UNIFORM_ENVIRONMENT_BINDING,
                UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING: UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING,
                UBOLocal: UBOLocal,
                INST_MAT_WORLD: INST_MAT_WORLD,
                UBOLocalBatched: UBOLocalBatched,
                UBOForwardLight: UBOForwardLight,
                UBODeferredLight: UBODeferredLight,
                JOINT_UNIFORM_CAPACITY: JOINT_UNIFORM_CAPACITY,
                UBOSkinningTexture: UBOSkinningTexture,
                UBOSkinningAnimation: UBOSkinningAnimation,
                INST_JOINT_ANIM_INFO: INST_JOINT_ANIM_INFO,
                UBOSkinning: UBOSkinning,
                UBOMorph: UBOMorph,
                UNIFORM_JOINT_TEXTURE_BINDING: UNIFORM_JOINT_TEXTURE_BINDING,
                UNIFORM_POSITION_MORPH_TEXTURE_BINDING: UNIFORM_POSITION_MORPH_TEXTURE_BINDING,
                UNIFORM_NORMAL_MORPH_TEXTURE_BINDING: UNIFORM_NORMAL_MORPH_TEXTURE_BINDING,
                UNIFORM_TANGENT_MORPH_TEXTURE_BINDING: UNIFORM_TANGENT_MORPH_TEXTURE_BINDING,
                UNIFORM_LIGHTMAP_TEXTURE_BINDING: UNIFORM_LIGHTMAP_TEXTURE_BINDING,
                UNIFORM_SPRITE_TEXTURE_BINDING: UNIFORM_SPRITE_TEXTURE_BINDING,
                CAMERA_DEFAULT_MASK: CAMERA_DEFAULT_MASK,
                CAMERA_EDITOR_MASK: CAMERA_EDITOR_MASK,
                MODEL_ALWAYS_MASK: MODEL_ALWAYS_MASK,
                supportsHalfFloatTexture: supportsHalfFloatTexture
            });
            exports('pipeline', define$1);

            var CameraFOVAxis;

            (function (CameraFOVAxis) {
              CameraFOVAxis[CameraFOVAxis["VERTICAL"] = 0] = "VERTICAL";
              CameraFOVAxis[CameraFOVAxis["HORIZONTAL"] = 1] = "HORIZONTAL";
            })(CameraFOVAxis || (CameraFOVAxis = {}));

            var CameraProjection;

            (function (CameraProjection) {
              CameraProjection[CameraProjection["ORTHO"] = 0] = "ORTHO";
              CameraProjection[CameraProjection["PERSPECTIVE"] = 1] = "PERSPECTIVE";
            })(CameraProjection || (CameraProjection = {}));

            var CameraAperture;

            (function (CameraAperture) {
              CameraAperture[CameraAperture["F1_8"] = 0] = "F1_8";
              CameraAperture[CameraAperture["F2_0"] = 1] = "F2_0";
              CameraAperture[CameraAperture["F2_2"] = 2] = "F2_2";
              CameraAperture[CameraAperture["F2_5"] = 3] = "F2_5";
              CameraAperture[CameraAperture["F2_8"] = 4] = "F2_8";
              CameraAperture[CameraAperture["F3_2"] = 5] = "F3_2";
              CameraAperture[CameraAperture["F3_5"] = 6] = "F3_5";
              CameraAperture[CameraAperture["F4_0"] = 7] = "F4_0";
              CameraAperture[CameraAperture["F4_5"] = 8] = "F4_5";
              CameraAperture[CameraAperture["F5_0"] = 9] = "F5_0";
              CameraAperture[CameraAperture["F5_6"] = 10] = "F5_6";
              CameraAperture[CameraAperture["F6_3"] = 11] = "F6_3";
              CameraAperture[CameraAperture["F7_1"] = 12] = "F7_1";
              CameraAperture[CameraAperture["F8_0"] = 13] = "F8_0";
              CameraAperture[CameraAperture["F9_0"] = 14] = "F9_0";
              CameraAperture[CameraAperture["F10_0"] = 15] = "F10_0";
              CameraAperture[CameraAperture["F11_0"] = 16] = "F11_0";
              CameraAperture[CameraAperture["F13_0"] = 17] = "F13_0";
              CameraAperture[CameraAperture["F14_0"] = 18] = "F14_0";
              CameraAperture[CameraAperture["F16_0"] = 19] = "F16_0";
              CameraAperture[CameraAperture["F18_0"] = 20] = "F18_0";
              CameraAperture[CameraAperture["F20_0"] = 21] = "F20_0";
              CameraAperture[CameraAperture["F22_0"] = 22] = "F22_0";
            })(CameraAperture || (CameraAperture = {}));

            var CameraISO;

            (function (CameraISO) {
              CameraISO[CameraISO["ISO100"] = 0] = "ISO100";
              CameraISO[CameraISO["ISO200"] = 1] = "ISO200";
              CameraISO[CameraISO["ISO400"] = 2] = "ISO400";
              CameraISO[CameraISO["ISO800"] = 3] = "ISO800";
            })(CameraISO || (CameraISO = {}));

            var CameraShutter;

            (function (CameraShutter) {
              CameraShutter[CameraShutter["D1"] = 0] = "D1";
              CameraShutter[CameraShutter["D2"] = 1] = "D2";
              CameraShutter[CameraShutter["D4"] = 2] = "D4";
              CameraShutter[CameraShutter["D8"] = 3] = "D8";
              CameraShutter[CameraShutter["D15"] = 4] = "D15";
              CameraShutter[CameraShutter["D30"] = 5] = "D30";
              CameraShutter[CameraShutter["D60"] = 6] = "D60";
              CameraShutter[CameraShutter["D125"] = 7] = "D125";
              CameraShutter[CameraShutter["D250"] = 8] = "D250";
              CameraShutter[CameraShutter["D500"] = 9] = "D500";
              CameraShutter[CameraShutter["D1000"] = 10] = "D1000";
              CameraShutter[CameraShutter["D2000"] = 11] = "D2000";
              CameraShutter[CameraShutter["D4000"] = 12] = "D4000";
            })(CameraShutter || (CameraShutter = {}));

            var FSTOPS = [1.8, 2.0, 2.2, 2.5, 2.8, 3.2, 3.5, 4.0, 4.5, 5.0, 5.6, 6.3, 7.1, 8.0, 9.0, 10.0, 11.0, 13.0, 14.0, 16.0, 18.0, 20.0, 22.0];
            var SHUTTERS = [1.0, 1.0 / 2.0, 1.0 / 4.0, 1.0 / 8.0, 1.0 / 15.0, 1.0 / 30.0, 1.0 / 60.0, 1.0 / 125.0, 1.0 / 250.0, 1.0 / 500.0, 1.0 / 1000.0, 1.0 / 2000.0, 1.0 / 4000.0];
            var ISOS = [100.0, 200.0, 400.0, 800.0];
            var v_a = new Vec3();
            var v_b = new Vec3();

            var _tempMat1 = new Mat4();

            var SKYBOX_FLAG = ClearFlagBit.STENCIL << 1;
            var correctionMatrices = [];
            var Camera = function () {
              function Camera(device) {
                this.isWindowSize = true;
                this.screenScale = void 0;
                this._device = void 0;
                this._scene = null;
                this._node = null;
                this._name = null;
                this._enabled = false;
                this._proj = -1;
                this._aspect = void 0;
                this._orthoHeight = 10.0;
                this._fovAxis = CameraFOVAxis.VERTICAL;
                this._fov = toRadian(45);
                this._nearClip = 1.0;
                this._farClip = 1000.0;
                this._clearColor = new Color$1(0.2, 0.2, 0.2, 1);
                this._viewport = new Rect(0, 0, 1, 1);
                this._curTransform = SurfaceTransform.IDENTITY;
                this._isProjDirty = true;
                this._matView = new Mat4();
                this._matViewInv = null;
                this._matProj = new Mat4();
                this._matProjInv = new Mat4();
                this._matViewProj = new Mat4();
                this._matViewProjInv = new Mat4();
                this._frustum = new Frustum();
                this._forward = new Vec3();
                this._position = new Vec3();
                this._priority = 0;
                this._aperture = CameraAperture.F16_0;
                this._apertureValue = void 0;
                this._shutter = CameraShutter.D125;
                this._shutterValue = 0.0;
                this._iso = CameraISO.ISO100;
                this._isoValue = 0.0;
                this._ec = 0.0;
                this._poolHandle = NULL_HANDLE;
                this._frustumHandle = NULL_HANDLE;
                this._window = null;
                this._device = device;
                this._apertureValue = FSTOPS[this._aperture];
                this._shutterValue = SHUTTERS[this._shutter];
                this._isoValue = ISOS[this._iso];
                this._aspect = this.screenScale = 1;

                if (!correctionMatrices.length) {
                  var ySign = device.capabilities.clipSpaceSignY;
                  correctionMatrices[SurfaceTransform.IDENTITY] = new Mat4(1, 0, 0, 0, 0, ySign);
                  correctionMatrices[SurfaceTransform.ROTATE_90] = new Mat4(0, 1, 0, 0, -ySign, 0);
                  correctionMatrices[SurfaceTransform.ROTATE_180] = new Mat4(-1, 0, 0, 0, 0, -ySign);
                  correctionMatrices[SurfaceTransform.ROTATE_270] = new Mat4(0, -1, 0, 0, ySign, 0);
                }
              }

              var _proto = Camera.prototype;

              _proto.initialize = function initialize(info) {
                this._name = info.name;
                this._node = info.node;
                this._proj = info.projection;
                this._priority = info.priority || 0;
                this._aspect = this.screenScale = 1;
                var handle = this._poolHandle = CameraPool.alloc();
                CameraPool.set(handle, CameraView.WIDTH, 1);
                CameraPool.set(handle, CameraView.HEIGHT, 1);
                CameraPool.set(handle, CameraView.CLEAR_FLAGS, ClearFlagBit.NONE);
                CameraPool.set(handle, CameraView.CLEAR_DEPTH, 1.0);
                CameraPool.set(handle, CameraView.NODE, this._node.handle);
                CameraPool.set(handle, CameraView.VISIBILITY, CAMERA_DEFAULT_MASK);
                if (this._scene) CameraPool.set(handle, CameraView.SCENE, this._scene.handle);

                this.updateExposure();
                this.changeTargetWindow(info.window);
                console.log("Created Camera: " + this._name + " " + CameraPool.get(handle, CameraView.WIDTH) + "x" + CameraPool.get(handle, CameraView.HEIGHT));
              };

              _proto.destroy = function destroy() {
                if (this._window) {
                  this._window.detachCamera(this);
                }

                this._name = null;

                if (this._poolHandle) {
                  CameraPool.free(this._poolHandle);
                  this._poolHandle = NULL_HANDLE;

                  if (this._frustumHandle) {
                    FrustumPool.free(this._frustumHandle);
                    this._frustumHandle = NULL_HANDLE;
                  }
                }
              };

              _proto.attachToScene = function attachToScene(scene) {
                this._scene = scene;
                this._enabled = true;
                CameraPool.set(this._poolHandle, CameraView.SCENE, scene.handle);
              };

              _proto.detachFromScene = function detachFromScene() {
                this._scene = null;
                this._enabled = false;
                CameraPool.set(this._poolHandle, CameraView.SCENE, 0);
              };

              _proto.resize = function resize(width, height) {
                var handle = this._poolHandle;
                CameraPool.set(handle, CameraView.WIDTH, width);
                CameraPool.set(handle, CameraView.HEIGHT, height);
                this._aspect = width * this._viewport.width / (height * this._viewport.height);
                this._isProjDirty = true;
              };

              _proto.setFixedSize = function setFixedSize(width, height) {
                var handle = this._poolHandle;
                CameraPool.set(handle, CameraView.WIDTH, width);
                CameraPool.set(handle, CameraView.HEIGHT, height);
                this._aspect = width * this._viewport.width / (height * this._viewport.height);
                this.isWindowSize = false;
              };

              _proto.update = function update(forceUpdate) {
                if (forceUpdate === void 0) {
                  forceUpdate = false;
                }

                if (!this._node) return;
                var viewProjDirty = false;

                if (this._node.hasChangedFlags || forceUpdate) {
                  Mat4.invert(this._matView, this._node.worldMatrix);
                  CameraPool.setMat4(this._poolHandle, CameraView.MAT_VIEW, this._matView);
                  this._forward.x = -this._matView.m02;
                  this._forward.y = -this._matView.m06;
                  this._forward.z = -this._matView.m10;

                  this._node.getWorldPosition(this._position);

                  CameraPool.setVec3(this._poolHandle, CameraView.POSITION, this._position);
                  CameraPool.setVec3(this._poolHandle, CameraView.FORWARD, this._forward);
                  viewProjDirty = true;
                }

                var orientation = this._device.surfaceTransform;

                if (this._isProjDirty || this._curTransform !== orientation) {
                  var _this$window;

                  this._curTransform = orientation;
                  var projectionSignY = this._device.capabilities.clipSpaceSignY;

                  if ((_this$window = this.window) === null || _this$window === void 0 ? void 0 : _this$window.hasOffScreenAttachments) {
                    orientation = SurfaceTransform.IDENTITY;
                  }

                  if (this._proj === CameraProjection.PERSPECTIVE) {
                    Mat4.perspective(this._matProj, this._fov, this._aspect, this._nearClip, this._farClip, this._fovAxis === CameraFOVAxis.VERTICAL, this._device.capabilities.clipSpaceMinZ, projectionSignY, orientation);
                  } else {
                    var x = this._orthoHeight * this._aspect;
                    var y = this._orthoHeight;
                    Mat4.ortho(this._matProj, -x, x, -y, y, this._nearClip, this._farClip, this._device.capabilities.clipSpaceMinZ, projectionSignY, orientation);
                  }

                  Mat4.invert(this._matProjInv, this._matProj);
                  CameraPool.setMat4(this._poolHandle, CameraView.MAT_PROJ, this._matProj);
                  CameraPool.setMat4(this._poolHandle, CameraView.MAT_PROJ_INV, this._matProjInv);
                  viewProjDirty = true;
                  this._isProjDirty = false;
                }

                if (viewProjDirty) {
                  Mat4.multiply(this._matViewProj, this._matProj, this._matView);
                  Mat4.invert(this._matViewProjInv, this._matViewProj);

                  this._frustum.update(this._matViewProj, this._matViewProjInv);

                  CameraPool.setMat4(this._poolHandle, CameraView.MAT_VIEW_PROJ, this._matViewProj);
                  CameraPool.setMat4(this._poolHandle, CameraView.MAT_VIEW_PROJ_INV, this._matViewProjInv);
                  recordFrustumToSharedMemory(this._frustumHandle, this._frustum);
                }
              };

              _proto.changeTargetWindow = function changeTargetWindow(window) {
                if (window === void 0) {
                  window = null;
                }

                if (this._window) {
                  this._window.detachCamera(this);
                }

                var win = window || legacyCC.director.root.mainWindow;

                if (win) {
                  win.attachCamera(this);
                  this.resize(win.width, win.height);
                  this._window = win;
                  CameraPool.set(this._poolHandle, CameraView.WINDOW, win.handle);
                }
              };

              _proto.detachCamera = function detachCamera() {
                if (this._window) {
                  this._window.detachCamera(this);
                }
              };

              _proto.screenPointToRay = function screenPointToRay(out, x, y) {
                if (!this._node) return null;
                var handle = this._poolHandle;
                var width = CameraPool.get(handle, CameraView.WIDTH);
                var height = CameraPool.get(handle, CameraView.HEIGHT);
                var cx = this._viewport.x * width;
                var cy = this._viewport.y * height;
                var cw = this._viewport.width * width;
                var ch = this._viewport.height * height;
                var isProj = this._proj === CameraProjection.PERSPECTIVE;
                var ySign = this._device.capabilities.clipSpaceSignY;
                var preTransform = preTransforms[this._curTransform];
                Vec3.set(v_a, (x - cx) / cw * 2 - 1, (y - cy) / ch * 2 - 1, isProj ? 1 : -1);
                var ox = v_a.x,
                    oy = v_a.y;
                v_a.x = ox * preTransform[0] + oy * preTransform[2] * ySign;
                v_a.y = ox * preTransform[1] + oy * preTransform[3] * ySign;
                Vec3.transformMat4(isProj ? v_a : out.o, v_a, this._matViewProjInv);

                if (isProj) {
                  this._node.getWorldPosition(v_b);

                  Ray.fromPoints(out, v_b, v_a);
                } else {
                  Vec3.transformQuat(out.d, Vec3.FORWARD, this._node.worldRotation);
                }

                return out;
              };

              _proto.screenToWorld = function screenToWorld(out, screenPos) {
                var handle = this._poolHandle;
                var width = CameraPool.get(handle, CameraView.WIDTH);
                var height = CameraPool.get(handle, CameraView.HEIGHT);
                var cx = this._viewport.x * width;
                var cy = this._viewport.y * height;
                var cw = this._viewport.width * width;
                var ch = this._viewport.height * height;
                var ySign = this._device.capabilities.clipSpaceSignY;
                var preTransform = preTransforms[this._curTransform];

                if (this._proj === CameraProjection.PERSPECTIVE) {
                  Vec3.set(out, (screenPos.x - cx) / cw * 2 - 1, (screenPos.y - cy) / ch * 2 - 1, 1.0);
                  var x = out.x,
                      y = out.y;
                  out.x = x * preTransform[0] + y * preTransform[2] * ySign;
                  out.y = x * preTransform[1] + y * preTransform[3] * ySign;
                  Vec3.transformMat4(out, out, this._matViewProjInv);

                  if (this._node) {
                    this._node.getWorldPosition(v_a);
                  }

                  Vec3.lerp(out, v_a, out, lerp(this._nearClip / this._farClip, 1, screenPos.z));
                } else {
                  Vec3.set(out, (screenPos.x - cx) / cw * 2 - 1, (screenPos.y - cy) / ch * 2 - 1, screenPos.z * 2 - 1);
                  var _x = out.x,
                      _y = out.y;
                  out.x = _x * preTransform[0] + _y * preTransform[2] * ySign;
                  out.y = _x * preTransform[1] + _y * preTransform[3] * ySign;
                  Vec3.transformMat4(out, out, this._matViewProjInv);
                }

                return out;
              };

              _proto.worldToScreen = function worldToScreen(out, worldPos) {
                var handle = this._poolHandle;
                var width = CameraPool.get(handle, CameraView.WIDTH);
                var height = CameraPool.get(handle, CameraView.HEIGHT);
                var cx = this._viewport.x * width;
                var cy = this._viewport.y * height;
                var cw = this._viewport.width * width;
                var ch = this._viewport.height * height;
                var ySign = this._device.capabilities.clipSpaceSignY;
                var preTransform = preTransforms[this._curTransform];
                Vec3.transformMat4(out, worldPos, this._matViewProj);
                var x = out.x,
                    y = out.y;
                out.x = x * preTransform[0] + y * preTransform[2] * ySign;
                out.y = x * preTransform[1] + y * preTransform[3] * ySign;
                out.x = cx + (out.x + 1) * 0.5 * cw;
                out.y = cy + (out.y + 1) * 0.5 * ch;
                out.z = out.z * 0.5 + 0.5;
                return out;
              };

              _proto.worldMatrixToScreen = function worldMatrixToScreen(out, worldMatrix, width, height) {
                Mat4.multiply(out, this._matViewProj, worldMatrix);
                Mat4.multiply(out, correctionMatrices[this._curTransform], out);
                var halfWidth = width / 2;
                var halfHeight = height / 2;
                Mat4.identity(_tempMat1);
                Mat4.transform(_tempMat1, _tempMat1, Vec3.set(v_a, halfWidth, halfHeight, 0));
                Mat4.scale(_tempMat1, _tempMat1, Vec3.set(v_a, halfWidth, halfHeight, 1));
                Mat4.multiply(out, _tempMat1, out);
                return out;
              };

              _proto.updateExposure = function updateExposure() {
                var ev100 = Math.log2(this._apertureValue * this._apertureValue / this._shutterValue * 100.0 / this._isoValue);
                CameraPool.set(this._poolHandle, CameraView.EXPOSURE, 0.833333 / Math.pow(2.0, ev100));
              };

              _createClass(Camera, [{
                key: "node",
                get: function get() {
                  return this._node;
                },
                set: function set(val) {
                  this._node = val;
                }
              }, {
                key: "enabled",
                get: function get() {
                  return this._enabled;
                },
                set: function set(val) {
                  this._enabled = val;
                }
              }, {
                key: "orthoHeight",
                get: function get() {
                  return this._orthoHeight;
                },
                set: function set(val) {
                  this._orthoHeight = val;
                  this._isProjDirty = true;
                }
              }, {
                key: "projectionType",
                get: function get() {
                  return this._proj;
                },
                set: function set(val) {
                  this._proj = val;
                  this._isProjDirty = true;
                }
              }, {
                key: "fovAxis",
                get: function get() {
                  return this._fovAxis;
                },
                set: function set(axis) {
                  this._fovAxis = axis;
                  this._isProjDirty = true;
                }
              }, {
                key: "fov",
                get: function get() {
                  return this._fov;
                },
                set: function set(fov) {
                  this._fov = fov;
                  this._isProjDirty = true;
                }
              }, {
                key: "nearClip",
                get: function get() {
                  return this._nearClip;
                },
                set: function set(nearClip) {
                  this._nearClip = nearClip;
                  this._isProjDirty = true;
                }
              }, {
                key: "farClip",
                get: function get() {
                  return this._farClip;
                },
                set: function set(farClip) {
                  this._farClip = farClip;
                  this._isProjDirty = true;
                }
              }, {
                key: "clearColor",
                get: function get() {
                  return this._clearColor;
                },
                set: function set(val) {
                  this._clearColor.x = val.x;
                  this._clearColor.y = val.y;
                  this._clearColor.z = val.z;
                  this._clearColor.w = val.w;
                  CameraPool.setVec4(this._poolHandle, CameraView.CLEAR_COLOR, val);
                }
              }, {
                key: "viewport",
                get: function get() {
                  return this._viewport;
                },
                set: function set(val) {
                  var x = val.x,
                      width = val.width,
                      height = val.height;
                  var y = this._device.capabilities.clipSpaceSignY < 0 ? 1 - val.y - height : val.y;

                  switch (this._device.surfaceTransform) {
                    case SurfaceTransform.ROTATE_90:
                      this._viewport.x = 1 - y - height;
                      this._viewport.y = x;
                      this._viewport.width = height;
                      this._viewport.height = width;
                      break;

                    case SurfaceTransform.ROTATE_180:
                      this._viewport.x = 1 - x - width;
                      this._viewport.y = 1 - y - height;
                      this._viewport.width = width;
                      this._viewport.height = height;
                      break;

                    case SurfaceTransform.ROTATE_270:
                      this._viewport.x = y;
                      this._viewport.y = 1 - x - width;
                      this._viewport.width = height;
                      this._viewport.height = width;
                      break;

                    case SurfaceTransform.IDENTITY:
                      this._viewport.x = x;
                      this._viewport.y = y;
                      this._viewport.width = width;
                      this._viewport.height = height;
                      break;
                  }

                  CameraPool.setVec4(this._poolHandle, CameraView.VIEW_PORT, this._viewport);
                  this.resize(this.width, this.height);
                }
              }, {
                key: "scene",
                get: function get() {
                  return this._scene;
                }
              }, {
                key: "name",
                get: function get() {
                  return this._name;
                }
              }, {
                key: "width",
                get: function get() {
                  return CameraPool.get(this._poolHandle, CameraView.WIDTH);
                }
              }, {
                key: "height",
                get: function get() {
                  return CameraPool.get(this._poolHandle, CameraView.HEIGHT);
                }
              }, {
                key: "aspect",
                get: function get() {
                  return this._aspect;
                }
              }, {
                key: "matView",
                get: function get() {
                  return this._matView;
                },
                set: function set(val) {
                  this._matView = val;
                  CameraPool.setMat4(this._poolHandle, CameraView.MAT_VIEW, this._matView);
                }
              }, {
                key: "matViewInv",
                get: function get() {
                  return this._matViewInv || this._node.worldMatrix;
                },
                set: function set(val) {
                  this._matViewInv = val;
                }
              }, {
                key: "matProj",
                get: function get() {
                  return this._matProj;
                },
                set: function set(val) {
                  this._matProj = val;
                  CameraPool.setMat4(this._poolHandle, CameraView.MAT_PROJ, this._matProj);
                }
              }, {
                key: "matProjInv",
                get: function get() {
                  return this._matProjInv;
                },
                set: function set(val) {
                  this._matProjInv = val;
                  CameraPool.setMat4(this._poolHandle, CameraView.MAT_PROJ_INV, this._matProjInv);
                }
              }, {
                key: "matViewProj",
                get: function get() {
                  return this._matViewProj;
                },
                set: function set(val) {
                  this._matViewProj = val;
                  CameraPool.setMat4(this._poolHandle, CameraView.MAT_VIEW_PROJ, this._matViewProj);
                }
              }, {
                key: "matViewProjInv",
                get: function get() {
                  return this._matViewProjInv;
                },
                set: function set(val) {
                  this._matViewProjInv = val;
                  CameraPool.setMat4(this._poolHandle, CameraView.MAT_VIEW_PROJ_INV, this._matViewProjInv);
                }
              }, {
                key: "frustum",
                get: function get() {
                  return this._frustum;
                },
                set: function set(val) {
                  this._frustum = val;
                  recordFrustumToSharedMemory(this._frustumHandle, val);
                }
              }, {
                key: "window",
                get: function get() {
                  return this._window;
                },
                set: function set(val) {
                  this._window = val;
                  if (val) CameraPool.set(this._poolHandle, CameraView.WINDOW, val.handle);
                }
              }, {
                key: "forward",
                get: function get() {
                  return this._forward;
                },
                set: function set(val) {
                  this._forward = val;
                  CameraPool.setVec3(this._poolHandle, CameraView.FORWARD, this._forward);
                }
              }, {
                key: "position",
                get: function get() {
                  return this._position;
                },
                set: function set(val) {
                  this._position = val;
                  CameraPool.setVec3(this._poolHandle, CameraView.POSITION, this._position);
                }
              }, {
                key: "visibility",
                get: function get() {
                  return CameraPool.get(this._poolHandle, CameraView.VISIBILITY);
                },
                set: function set(vis) {
                  CameraPool.set(this._poolHandle, CameraView.VISIBILITY, vis);
                }
              }, {
                key: "priority",
                get: function get() {
                  return this._priority;
                },
                set: function set(val) {
                  this._priority = val;
                }
              }, {
                key: "aperture",
                get: function get() {
                  return this._aperture;
                },
                set: function set(val) {
                  this._aperture = val;
                  this._apertureValue = FSTOPS[this._aperture];
                  this.updateExposure();
                }
              }, {
                key: "apertureValue",
                get: function get() {
                  return this._apertureValue;
                }
              }, {
                key: "shutter",
                get: function get() {
                  return this._shutter;
                },
                set: function set(val) {
                  this._shutter = val;
                  this._shutterValue = SHUTTERS[this._shutter];
                  this.updateExposure();
                }
              }, {
                key: "shutterValue",
                get: function get() {
                  return this._shutterValue;
                }
              }, {
                key: "iso",
                get: function get() {
                  return this._iso;
                },
                set: function set(val) {
                  this._iso = val;
                  this._isoValue = ISOS[this._iso];
                  this.updateExposure();
                }
              }, {
                key: "isoValue",
                get: function get() {
                  return this._isoValue;
                }
              }, {
                key: "ec",
                get: function get() {
                  return this._ec;
                },
                set: function set(val) {
                  this._ec = val;
                }
              }, {
                key: "exposure",
                get: function get() {
                  return CameraPool.get(this._poolHandle, CameraView.EXPOSURE);
                }
              }, {
                key: "clearFlag",
                get: function get() {
                  return CameraPool.get(this._poolHandle, CameraView.CLEAR_FLAGS);
                },
                set: function set(flag) {
                  CameraPool.set(this._poolHandle, CameraView.CLEAR_FLAGS, flag);
                }
              }, {
                key: "clearDepth",
                get: function get() {
                  return CameraPool.get(this._poolHandle, CameraView.CLEAR_DEPTH);
                },
                set: function set(depth) {
                  CameraPool.set(this._poolHandle, CameraView.CLEAR_DEPTH, depth);
                }
              }, {
                key: "clearStencil",
                get: function get() {
                  return CameraPool.get(this._poolHandle, CameraView.CLEAR_STENCIL);
                },
                set: function set(stencil) {
                  CameraPool.set(this._poolHandle, CameraView.CLEAR_STENCIL, stencil);
                }
              }, {
                key: "handle",
                get: function get() {
                  return this._poolHandle;
                }
              }]);

              return Camera;
            }();

            var NodeSpace;

            (function (NodeSpace) {
              NodeSpace[NodeSpace["LOCAL"] = 0] = "LOCAL";
              NodeSpace[NodeSpace["WORLD"] = 1] = "WORLD";
            })(NodeSpace || (NodeSpace = {}));

            var TransformBit;

            (function (TransformBit) {
              TransformBit[TransformBit["NONE"] = 0] = "NONE";
              TransformBit[TransformBit["POSITION"] = 1] = "POSITION";
              TransformBit[TransformBit["ROTATION"] = 2] = "ROTATION";
              TransformBit[TransformBit["SCALE"] = 4] = "SCALE";
              TransformBit[TransformBit["RS"] = TransformBit.ROTATION | TransformBit.SCALE] = "RS";
              TransformBit[TransformBit["TRS"] = TransformBit.POSITION | TransformBit.ROTATION | TransformBit.SCALE] = "TRS";
              TransformBit[TransformBit["TRS_MASK"] = ~TransformBit.TRS] = "TRS_MASK";
            })(TransformBit || (TransformBit = {}));

            legacyCC.internal.TransformBit = TransformBit;

            var RenderScene = function () {
              RenderScene.registerCreateFunc = function registerCreateFunc(root) {
                root._createSceneFun = function (_root) {
                  return new RenderScene(_root);
                };
              };

              function RenderScene(root) {
                this._root = void 0;
                this._name = '';
                this._cameras = [];
                this._models = [];
                this._batches = [];
                this._directionalLights = [];
                this._sphereLights = [];
                this._spotLights = [];
                this._mainLight = null;
                this._modelId = 0;
                this._scenePoolHandle = NULL_HANDLE;
                this._modelArrayHandle = NULL_HANDLE;
                this._batchArrayHandle = NULL_HANDLE;
                this._sphereLightsHandle = NULL_HANDLE;
                this._spotLightsHandle = NULL_HANDLE;
                this._root = root;

                this._createHandles();
              }

              var _proto = RenderScene.prototype;

              _proto.initialize = function initialize(info) {
                this._name = info.name;

                this._createHandles();

                return true;
              };

              _proto.update = function update(stamp) {
                var mainLight = this._mainLight;

                if (mainLight) {
                  mainLight.update();
                }

                var sphereLights = this._sphereLights;

                for (var i = 0; i < sphereLights.length; i++) {
                  var light = sphereLights[i];
                  light.update();
                }

                var spotLights = this._spotLights;

                for (var _i = 0; _i < spotLights.length; _i++) {
                  var _light = spotLights[_i];

                  _light.update();
                }

                var models = this._models;

                for (var _i2 = 0; _i2 < models.length; _i2++) {
                  var model = models[_i2];

                  if (model.enabled) {
                    model.updateTransform(stamp);
                    model.updateUBOs(stamp);
                  }
                }
              };

              _proto.destroy = function destroy() {
                this.removeCameras();
                this.removeSphereLights();
                this.removeSpotLights();
                this.removeModels();

                if (this._modelArrayHandle) {
                  ModelArrayPool.free(this._modelArrayHandle);
                  this._modelArrayHandle = NULL_HANDLE;
                }

                if (this._scenePoolHandle) {
                  ScenePool.free(this._scenePoolHandle);
                  this._scenePoolHandle = NULL_HANDLE;
                }

                if (this._sphereLightsHandle) {
                  LightArrayPool.free(this._sphereLightsHandle);
                  this._sphereLightsHandle = NULL_HANDLE;
                }

                if (this._spotLightsHandle) {
                  LightArrayPool.free(this._spotLightsHandle);
                  this._spotLightsHandle = NULL_HANDLE;
                }

                if (this._batchArrayHandle) {
                  UIBatchArrayPool.free(this._batchArrayHandle);
                  this._batchArrayHandle = NULL_HANDLE;
                }
              };

              _proto.addCamera = function addCamera(cam) {
                cam.attachToScene(this);

                this._cameras.push(cam);
              };

              _proto.removeCamera = function removeCamera(camera) {
                for (var i = 0; i < this._cameras.length; ++i) {
                  if (this._cameras[i] === camera) {
                    this._cameras.splice(i, 1);

                    camera.detachFromScene();
                    return;
                  }
                }
              };

              _proto.removeCameras = function removeCameras() {
                for (var _iterator = _createForOfIteratorHelperLoose(this._cameras), _step; !(_step = _iterator()).done;) {
                  var camera = _step.value;
                  camera.detachFromScene();
                }

                this._cameras.splice(0);
              };

              _proto.setMainLight = function setMainLight(dl) {
                this._mainLight = dl;
                ScenePool.set(this._scenePoolHandle, SceneView.MAIN_LIGHT, dl.handle);
              };

              _proto.unsetMainLight = function unsetMainLight(dl) {
                if (this._mainLight === dl) {
                  var dlList = this._directionalLights;

                  if (dlList.length) {
                    this._mainLight = dlList[dlList.length - 1];

                    if (this._mainLight.node) {
                      this._mainLight.node.hasChangedFlags |= TransformBit.ROTATION;
                    }
                  } else {
                    this._mainLight = null;
                  }
                }
              };

              _proto.addDirectionalLight = function addDirectionalLight(dl) {
                dl.attachToScene(this);

                this._directionalLights.push(dl);
              };

              _proto.removeDirectionalLight = function removeDirectionalLight(dl) {
                for (var i = 0; i < this._directionalLights.length; ++i) {
                  if (this._directionalLights[i] === dl) {
                    dl.detachFromScene();

                    this._directionalLights.splice(i, 1);

                    return;
                  }
                }
              };

              _proto.addSphereLight = function addSphereLight(pl) {
                pl.attachToScene(this);

                this._sphereLights.push(pl);

                LightArrayPool.push(this._sphereLightsHandle, pl.handle);
              };

              _proto.removeSphereLight = function removeSphereLight(pl) {
                for (var i = 0; i < this._sphereLights.length; ++i) {
                  if (this._sphereLights[i] === pl) {
                    pl.detachFromScene();

                    this._sphereLights.splice(i, 1);

                    LightArrayPool.erase(this._sphereLightsHandle, i);
                    return;
                  }
                }
              };

              _proto.addSpotLight = function addSpotLight(sl) {
                sl.attachToScene(this);

                this._spotLights.push(sl);

                LightArrayPool.push(this._spotLightsHandle, sl.handle);
              };

              _proto.removeSpotLight = function removeSpotLight(sl) {
                for (var i = 0; i < this._spotLights.length; ++i) {
                  if (this._spotLights[i] === sl) {
                    sl.detachFromScene();

                    this._spotLights.splice(i, 1);

                    LightArrayPool.erase(this._spotLightsHandle, i);
                    return;
                  }
                }
              };

              _proto.removeSphereLights = function removeSphereLights() {
                for (var i = 0; i < this._sphereLights.length; ++i) {
                  this._sphereLights[i].detachFromScene();
                }

                this._sphereLights.length = 0;
                LightArrayPool.clear(this._sphereLightsHandle);
              };

              _proto.removeSpotLights = function removeSpotLights() {
                for (var i = 0; i < this._spotLights.length; ++i) {
                  this._spotLights[i].detachFromScene();
                }

                this._spotLights = [];
                LightArrayPool.clear(this._spotLightsHandle);
              };

              _proto.addModel = function addModel(m) {
                m.attachToScene(this);

                this._models.push(m);

                ModelArrayPool.push(this._modelArrayHandle, m.handle);
              };

              _proto.removeModel = function removeModel(model) {
                for (var i = 0; i < this._models.length; ++i) {
                  if (this._models[i] === model) {
                    model.detachFromScene();

                    this._models.splice(i, 1);

                    ModelArrayPool.erase(this._modelArrayHandle, i);
                    return;
                  }
                }
              };

              _proto.removeModels = function removeModels() {
                for (var _iterator2 = _createForOfIteratorHelperLoose(this._models), _step2; !(_step2 = _iterator2()).done;) {
                  var m = _step2.value;
                  m.detachFromScene();
                  m.destroy();
                }

                this._models.length = 0;
                ModelArrayPool.clear(this._modelArrayHandle);
              };

              _proto.addBatch = function addBatch(batch) {
                this._batches.push(batch);

                UIBatchArrayPool.push(this._batchArrayHandle, batch.handle);
              };

              _proto.removeBatch = function removeBatch(batch) {
                for (var i = 0; i < this._batches.length; ++i) {
                  if (this._batches[i] === batch) {
                    this._batches.splice(i, 1);

                    UIBatchArrayPool.erase(this._batchArrayHandle, i);
                    return;
                  }
                }
              };

              _proto.removeBatches = function removeBatches() {
                this._batches.length = 0;
                UIBatchArrayPool.clear(this._batchArrayHandle);
              };

              _proto.onGlobalPipelineStateChanged = function onGlobalPipelineStateChanged() {
                for (var _iterator3 = _createForOfIteratorHelperLoose(this._models), _step3; !(_step3 = _iterator3()).done;) {
                  var m = _step3.value;
                  m.onGlobalPipelineStateChanged();
                }
              };

              _proto.generateModelId = function generateModelId() {
                return this._modelId++;
              };

              _proto._createHandles = function _createHandles() {
                if (!this._modelArrayHandle) {
                  this._modelArrayHandle = ModelArrayPool.alloc();
                  this._scenePoolHandle = ScenePool.alloc();
                  ScenePool.set(this._scenePoolHandle, SceneView.MODEL_ARRAY, this._modelArrayHandle);
                  this._spotLightsHandle = LightArrayPool.alloc();
                  ScenePool.set(this._scenePoolHandle, SceneView.SPOT_LIGHT_ARRAY, this._spotLightsHandle);
                  this._sphereLightsHandle = LightArrayPool.alloc();
                  ScenePool.set(this._scenePoolHandle, SceneView.SPHERE_LIGHT_ARRAY, this._sphereLightsHandle);
                }

                if (!this._batchArrayHandle) {
                  this._batchArrayHandle = UIBatchArrayPool.alloc();
                  ScenePool.set(this._scenePoolHandle, SceneView.BATCH_ARRAY_2D, this._batchArrayHandle);
                }
              };

              _createClass(RenderScene, [{
                key: "root",
                get: function get() {
                  return this._root;
                }
              }, {
                key: "name",
                get: function get() {
                  return this._name;
                }
              }, {
                key: "cameras",
                get: function get() {
                  return this._cameras;
                }
              }, {
                key: "mainLight",
                get: function get() {
                  return this._mainLight;
                }
              }, {
                key: "sphereLights",
                get: function get() {
                  return this._sphereLights;
                }
              }, {
                key: "spotLights",
                get: function get() {
                  return this._spotLights;
                }
              }, {
                key: "models",
                get: function get() {
                  return this._models;
                }
              }, {
                key: "handle",
                get: function get() {
                  return this._scenePoolHandle;
                }
              }, {
                key: "batches",
                get: function get() {
                  return this._batches;
                }
              }]);

              return RenderScene;
            }();

            var emptyDecorator = function emptyDecorator() {};
            var emptyDecoratorFn = function emptyDecoratorFn() {
              return emptyDecorator;
            };
            var emptySmartClassDecorator = makeSmartClassDecorator(function () {});
            function makeSmartClassDecorator(decorate) {
              return proxyFn;

              function proxyFn(target) {
                if (typeof target === 'function') {
                  return decorate(target);
                } else {
                  return function (constructor) {
                    return decorate(constructor, target);
                  };
                }
              }
            }

            function writeEditorClassProperty(constructor, propertyName, value) {
              var cache = getClassCache(constructor);

              if (cache) {
                var proto = getSubDict(cache, 'proto');
                getSubDict(proto, 'editor')[propertyName] = value;
              }
            }

            function makeEditorClassDecoratorFn(propertyName) {
              return function (value) {
                return function (constructor) {
                  writeEditorClassProperty(constructor, propertyName, value);
                };
              };
            }
            var CACHE_KEY = '__ccclassCache__';
            function getClassCache(ctor, decoratorName) {

              return getSubDict(ctor, CACHE_KEY);
            }
            function getSubDict(obj, key) {
              return obj[key] || (obj[key] = {});
            }

            var ccclass = makeSmartClassDecorator(function (constructor, name) {
              var base = js.getSuper(constructor);

              if (base === Object) {
                base = null;
              }

              var proto = {
                name: name,
                "extends": base,
                ctor: constructor
              };
              var cache = constructor[CACHE_KEY];

              if (cache) {
                var decoratedProto = cache.proto;

                if (decoratedProto) {
                  js.mixin(proto, decoratedProto);
                }

                constructor[CACHE_KEY] = undefined;
              }

              var res = CCClass(proto);

              return res;
            });

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

            function property(target, propertyKey, descriptor) {
              var options = null;

              function normalized(target, propertyKey, descriptor) {
                var cache = getClassCache(target.constructor);

                if (cache) {
                  var ccclassProto = getSubDict(cache, 'proto');
                  var properties = getSubDict(ccclassProto, 'properties');
                  genProperty(target.constructor, properties, propertyKey, options, descriptor, cache);
                }
              }

              if (target === undefined) {
                return property({
                  type: undefined
                });
              } else if (typeof propertyKey === 'undefined') {
                options = target;
                return normalized;
              } else {
                normalized(target, propertyKey, descriptor);
              }
            }

            function getDefaultFromInitializer(initializer) {
              var value;

              try {
                value = initializer();
              } catch (e) {
                return initializer;
              }

              if (typeof value !== 'object' || value === null) {
                return value;
              } else {
                return initializer;
              }
            }

            function extractActualDefaultValues(ctor) {
              var dummyObj;

              try {
                dummyObj = new ctor();
              } catch (e) {

                return {};
              }

              return dummyObj;
            }

            function genProperty(ctor, properties, propertyKey, options, descriptor, cache) {
              var fullOptions;
              var isGetset = descriptor && (descriptor.get || descriptor.set);

              if (options) {
                fullOptions = getFullFormOfProperty(options, isGetset);
              }

              var existsPropertyRecord = properties[propertyKey];
              var propertyRecord = js.mixin(existsPropertyRecord || {}, fullOptions || options || {});

              if (isGetset) {

                if (descriptor.get) {
                  propertyRecord.get = descriptor.get;
                }

                if (descriptor.set) {
                  propertyRecord.set = descriptor.set;
                }
              } else {

                if (descriptor) {
                  if (descriptor.initializer) {
                    propertyRecord["default"] = getDefaultFromInitializer(descriptor.initializer);
                  }
                } else {
                  var actualDefaultValues = cache["default"] || (cache["default"] = extractActualDefaultValues(ctor));

                  if (actualDefaultValues.hasOwnProperty(propertyKey)) {
                    propertyRecord["default"] = actualDefaultValues[propertyKey];
                  }
                }
              }

              properties[propertyKey] = propertyRecord;
            }

            var serializable = function serializable(target, propertyKey, descriptor) {
              return property(makeSerializable({}))(target, propertyKey, descriptor);
            };
            function formerlySerializedAs(name) {
              return property(makeSerializable({
                formerlySerializedAs: name
              }));
            }
            var editorOnly = function editorOnly(target, propertyKey, descriptor) {
              return property({
                editorOnly: true
              })(target, propertyKey, descriptor);
            };

            function makeSerializable(options) {
              options.__noImplicit = true;

              if (!('serializable' in options)) {
                options.serializable = true;
              }

              return options;
            }

            var executeInEditMode =  emptySmartClassDecorator;
            var menu =  emptyDecoratorFn;
            var playOnFocus =  emptySmartClassDecorator;
            var inspector =  emptyDecoratorFn;
            var icon =  emptyDecoratorFn;
            var help =  emptyDecoratorFn;
            var editable =  emptyDecorator ;
            var visible =  emptyDecoratorFn ;
            var displayName =  emptyDecoratorFn ;
            var tooltip =  emptyDecoratorFn ;
            var range =  emptyDecoratorFn ;
            var rangeMin =  emptyDecoratorFn ;
            var rangeMax =  emptyDecoratorFn ;
            var rangeStep =  emptyDecoratorFn ;
            var slide =  emptyDecorator ;
            var displayOrder =  emptyDecoratorFn ;
            var multiline =  emptyDecorator ;
            var disallowAnimation =  emptyDecorator ;

            var integer = type(CCInteger);

            var _float = type(CCFloat);

            var _boolean = type(CCBoolean);
            var string = type(CCString);
            function type(type) {
              return property({
                type: type
              });
            }

            var override = function override(target, propertyKey, descriptor) {
              return property({
                __noImplicit: true,
                override: true
              })(target, propertyKey, descriptor);
            };

            var Cache = function () {
              function Cache(map) {
                this._map = null;
                this._count = 0;

                if (map) {
                  this._map = map;
                  this._count = Object.keys(map).length;
                } else {
                  this._map = js.createMap(true);
                  this._count = 0;
                }
              }

              var _proto = Cache.prototype;

              _proto.add = function add(key, val) {
                if (!(key in this._map)) {
                  this._count++;
                }

                return this._map[key] = val;
              };

              _proto.get = function get(key) {
                return this._map[key];
              };

              _proto.has = function has(key) {
                return key in this._map;
              };

              _proto.remove = function remove(key) {
                var out = this._map[key];

                if (key in this._map) {
                  delete this._map[key];
                  this._count--;
                }

                return out;
              };

              _proto.clear = function clear() {
                if (this._count !== 0) {
                  this._map = js.createMap(true);
                  this._count = 0;
                }
              };

              _proto.forEach = function forEach(func) {
                for (var _key in this._map) {
                  func(this._map[_key], _key);
                }
              };

              _proto.find = function find(predicate) {
                for (var _key2 in this._map) {
                  if (predicate(this._map[_key2], _key2)) {
                    return this._map[_key2];
                  }
                }

                return null;
              };

              _proto.destroy = function destroy() {
                this._map = null;
              };

              _createClass(Cache, [{
                key: "count",
                get: function get() {
                  return this._count;
                }
              }]);

              return Cache;
            }();

            var Pipeline = function () {
              function Pipeline(name, funcs) {
                this.id = Pipeline._pipelineId++;
                this.name = '';
                this.pipes = [];
                this.name = name;

                for (var i = 0, l = funcs.length; i < l; i++) {
                  this.pipes.push(funcs[i]);
                }
              }

              var _proto = Pipeline.prototype;

              _proto.insert = function insert(func, index) {
                if (index > this.pipes.length) {
                  warnID(4921);
                  return this;
                }

                this.pipes.splice(index, 0, func);
                return this;
              };

              _proto.append = function append(func) {
                this.pipes.push(func);
                return this;
              };

              _proto.remove = function remove(index) {
                this.pipes.splice(index, 1);
                return this;
              };

              _proto.sync = function sync(task) {
                var pipes = this.pipes;

                if (pipes.length === 0) {
                  return null;
                }

                task.isFinish = false;

                for (var i = 0, l = pipes.length; i < l;) {
                  var pipe = pipes[i];
                  var result = pipe(task);

                  if (result) {
                    task.isFinish = true;
                    return result;
                  }

                  i++;

                  if (i !== l) {
                    task.input = task.output;
                    task.output = null;
                  }
                }

                task.isFinish = true;
                return task.output;
              };

              _proto.async = function async(task) {
                var pipes = this.pipes;

                if (pipes.length === 0) {
                  return;
                }

                task.isFinish = false;

                this._flow(0, task);
              };

              _proto._flow = function _flow(index, task) {
                var _this = this;

                var pipe = this.pipes[index];
                pipe(task, function (result) {
                  if (result) {
                    task.isFinish = 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.isFinish = true;
                      task.dispatch('complete', result, task.output);
                    }
                  }
                });
              };

              return Pipeline;
            }();
            Pipeline._pipelineId = 0;

            var assets = new Cache();
            var files = new Cache();
            var parsed = new Cache();
            var bundles = new Cache();
            var pipeline = new Pipeline('normal load', []);
            var fetchPipeline = new Pipeline('fetch', []);
            var transformPipeline = new Pipeline('transform url', []);
            var references =  null;
            var RequestType;

            (function (RequestType) {
              RequestType["UUID"] = "uuid";
              RequestType["PATH"] = "path";
              RequestType["DIR"] = "dir";
              RequestType["URL"] = "url";
              RequestType["SCENE"] = "scene";
            })(RequestType || (RequestType = {}));

            var presets = {
              "default": {
                priority: 0
              },
              preload: {
                maxConcurrency: 6,
                maxRequestsPerFrame: 2,
                priority: -1
              },
              scene: {
                maxConcurrency: 20,
                maxRequestsPerFrame: 20,
                priority: 1
              },
              bundle: {
                maxConcurrency: 20,
                maxRequestsPerFrame: 20,
                priority: 2
              },
              remote: {
                maxRetryCount: 4
              }
            };
            var BuiltinBundleName;

            (function (BuiltinBundleName) {
              BuiltinBundleName["RESOURCES"] = "resources";
              BuiltinBundleName["MAIN"] = "main";
              BuiltinBundleName["START_SCENE"] = "start-scene";
            })(BuiltinBundleName || (BuiltinBundleName = {}));

            var Task = function () {
              Task.create = function create(options) {
                var out;

                if (Task._deadPool.length !== 0) {
                  out = Task._deadPool.pop();
                  out.set(options);
                } else {
                  out = new Task(options);
                }

                return out;
              };

              function Task(options) {
                this.id = Task._taskId++;
                this.onComplete = null;
                this.onProgress = null;
                this.onError = null;
                this.source = null;
                this.output = null;
                this.input = null;
                this.progress = null;
                this.options = null;
                this.isFinish = true;
                this.set(options);
              }

              var _proto = Task.prototype;

              _proto.set = function set(options) {
                if (options === void 0) {
                  options = Object.create(null);
                }

                this.onComplete = options.onComplete || null;
                this.onProgress = options.onProgress || null;
                this.onError = options.onError || null;
                this.source = this.input = options.input;
                this.output = null;
                this.progress = options.progress;
                this.options = options.options || Object.create(null);
              };

              _proto.dispatch = function dispatch(event, param1, param2, param3, param4) {
                switch (event) {
                  case 'complete':
                    if (this.onComplete) {
                      this.onComplete(param1, param2);
                    }

                    break;

                  case 'progress':
                    if (this.onProgress) {
                      this.onProgress(param1, param2, param3, param4);
                    }

                    break;

                  case 'error':
                    if (this.onError) {
                      this.onError(param1, param2, param3, param4);
                    }

                    break;

                  default:
                    {
                      var str = "on" + event[0].toUpperCase() + event.substr(1);

                      if (typeof this[str] === 'function') {
                        this[str](param1, param2, param3, param4);
                      }

                      break;
                    }
                }
              };

              _proto.recycle = function recycle() {
                if (Task._deadPool.length === Task.MAX_DEAD_NUM) {
                  return;
                }

                this.onComplete = null;
                this.onProgress = null;
                this.onError = null;
                this.source = this.output = this.input = null;
                this.progress = null;
                this.options = null;

                Task._deadPool.push(this);
              };

              return Task;
            }();

            Task.MAX_DEAD_NUM = 500;
            Task._taskId = 0;
            Task._deadPool = [];

            var HexChars = '0123456789abcdef'.split('');
            var _t = ['', '', '', ''];

            var UuidTemplate = _t.concat(_t, '-', _t, '-', _t, '-', _t, '-', _t, _t, _t);

            var Indices = UuidTemplate.map(function (x, i) {
              return x === '-' ? NaN : i;
            }).filter(isFinite);
            function decodeUuid(base64) {
              var strs = base64.split('@');
              var uuid = strs[0];

              if (uuid.length !== 22) {
                return base64;
              }

              UuidTemplate[0] = base64[0];
              UuidTemplate[1] = base64[1];

              for (var i = 2, j = 2; i < 22; i += 2) {
                var lhs = BASE64_VALUES[base64.charCodeAt(i)];
                var rhs = BASE64_VALUES[base64.charCodeAt(i + 1)];
                UuidTemplate[Indices[j++]] = HexChars[lhs >> 2];
                UuidTemplate[Indices[j++]] = HexChars[(lhs & 3) << 2 | rhs >> 4];
                UuidTemplate[Indices[j++]] = HexChars[rhs & 0xF];
              }

              return base64.replace(uuid, UuidTemplate.join(''));
            }

            var _uuidRegex = /.*[/\\][0-9a-fA-F]{2}[/\\]([0-9a-fA-F-@]{8,}).*/;
            function getUuidFromURL(url) {
              var matches = _uuidRegex.exec(url);

              if (matches) {
                return matches[1];
              }

              return '';
            }
            function getUrlWithUuid(uuid, options) {
              options = options || Object.create(null);
              options.__isNative__ = options.isNative;
              options.ext = options.nativeExt;
              var bundle = bundles.find(function (b) {
                return !!b.getAssetInfo(uuid);
              });

              if (bundle) {
                options.bundle = bundle.name;
              }

              return transform(uuid, options);
            }
            function isScene(asset) {
              return asset && (asset instanceof legacyCC.SceneAsset || asset instanceof legacyCC.Scene);
            }
            function normalize(url) {
              if (url) {
                if (url.charCodeAt(0) === 46 && url.charCodeAt(1) === 47) {
                  url = url.slice(2);
                } else if (url.charCodeAt(0) === 47) {
                  url = url.slice(1);
                }
              }

              return url;
            }
            function transform(input, options) {
              var subTask = Task.create({
                input: input,
                options: options
              });
              var urls = [];

              try {
                var result = transformPipeline.sync(subTask);

                for (var _iterator = _createForOfIteratorHelperLoose(result), _step; !(_step = _iterator()).done;) {
                  var requestItem = _step.value;
                  var url = requestItem.url;
                  requestItem.recycle();
                  urls.push(url);
                }
              } catch (e) {
                for (var _iterator2 = _createForOfIteratorHelperLoose(subTask.output), _step2; !(_step2 = _iterator2()).done;) {
                  var item = _step2.value;
                  item.recycle();
                }

                error(e.message, e.stack);
              }

              subTask.recycle();
              return urls.length > 1 ? urls : urls[0];
            }

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

            var Event = exports('Event', function () {
              function Event(type, bubbles) {
                this.type = void 0;
                this.bubbles = void 0;
                this.target = null;
                this.currentTarget = null;
                this.eventPhase = 0;
                this.propagationStopped = false;
                this.propagationImmediateStopped = false;
                this.type = type;
                this.bubbles = !!bubbles;
              }

              var _proto = Event.prototype;

              _proto.unuse = function unuse() {
                this.type = Event.NO_TYPE;
                this.target = null;
                this.currentTarget = null;
                this.eventPhase = Event.NONE;
                this.propagationStopped = false;
                this.propagationImmediateStopped = false;
              };

              _proto.reuse = function reuse(type, bubbles) {
                this.type = type;
                this.bubbles = bubbles || false;
              };

              _proto.isStopped = function isStopped() {
                return this.propagationStopped || this.propagationImmediateStopped;
              };

              _proto.getCurrentTarget = function getCurrentTarget() {
                return this.currentTarget;
              };

              _proto.getType = function getType() {
                return this.type;
              };

              return Event;
            }());

            Event.NO_TYPE = 'no_type';
            Event.TOUCH = 'touch';
            Event.MOUSE = 'mouse';
            Event.KEYBOARD = 'keyboard';
            Event.ACCELERATION = 'acceleration';
            Event.NONE = 0;
            Event.CAPTURING_PHASE = 1;
            Event.AT_TARGET = 2;
            Event.BUBBLING_PHASE = 3;
            legacyCC.Event = Event;

            var _dec, _class, _class2, _descriptor, _temp;
            var Asset = exports('Asset', (_dec = ccclass('cc.Asset'), _dec(_class = (_class2 = (_temp = function (_Eventify) {
              _inheritsLoose(Asset, _Eventify);

              Asset.deserialize = function deserialize(data) {
                return legacyCC.deserialize(data);
              };

              function Asset() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Eventify.call.apply(_Eventify, [this].concat(args)) || this;
                _this.loaded = true;

                _initializerDefineProperty(_this, "_native", _descriptor, _assertThisInitialized(_this));

                _this._nativeUrl = '';
                _this.__onLoadedInvoked__ = false;
                _this.__nativeDepend__ = null;
                _this.__depends__ = null;
                _this._file = null;
                _this._ref = 0;
                Object.defineProperty(_assertThisInitialized(_this), '_uuid', {
                  value: '',
                  writable: true
                });

                return _this;
              }

              var _proto = Asset.prototype;

              _proto.toString = function toString() {
                return this.nativeUrl;
              };

              _proto.serialize = function serialize() {};

              _proto._setRawAsset = function _setRawAsset(filename, inLibrary) {
                if (inLibrary === void 0) {
                  inLibrary = true;
                }

                if (inLibrary !== false) {
                  this._native = filename || '';
                } else {
                  this._native = "/" + filename;
                }
              };

              _proto.addRef = function addRef() {
                this._ref++;
                return this;
              };

              _proto.decRef = function decRef(autoRelease) {
                if (autoRelease === void 0) {
                  autoRelease = true;
                }

                if (this._ref > 0) {
                  this._ref--;
                }

                if (autoRelease) {
                  legacyCC.assetManager._releaseManager.tryRelease(this);
                }

                return this;
              };

              _proto.onLoaded = function onLoaded() {};

              _proto.initDefault = function initDefault(uuid) {
                if (uuid) {
                  this._uuid = uuid;
                }

                this.isDefault = true;
              };

              _proto.validate = function validate() {
                return true;
              };

              _createClass(Asset, [{
                key: "nativeUrl",
                get: function get() {
                  if (!this._nativeUrl) {
                    if (!this._native) return '';
                    var name = this._native;

                    if (name.charCodeAt(0) === 47) {
                      return name.slice(1);
                    }

                    if (name.charCodeAt(0) === 46) {
                      this._nativeUrl = getUrlWithUuid(this._uuid, {
                        nativeExt: name,
                        isNative: true
                      });
                    } else {
                      this._nativeUrl = getUrlWithUuid(this._uuid, {
                        __nativeName__: name,
                        nativeExt: extname(name),
                        isNative: true
                      });
                    }
                  }

                  return this._nativeUrl;
                }
              }, {
                key: "_nativeAsset",
                get: function get() {
                  return this._file;
                },
                set: function set(obj) {
                  this._file = obj;
                }
              }, {
                key: "_nativeDep",
                get: function get() {
                  if (this._native) {
                    return {
                      __isNative__: true,
                      uuid: this._uuid,
                      ext: this._native
                    };
                  }

                  return undefined;
                }
              }, {
                key: "refCount",
                get: function get() {
                  return this._ref;
                }
              }]);

              return Asset;
            }(Eventify(CCObject)), _temp), (_descriptor = _applyDecoratedDescriptor(_class2.prototype, "_native", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return '';
              }
            }), _applyDecoratedDescriptor(_class2.prototype, "_nativeAsset", [property], Object.getOwnPropertyDescriptor(_class2.prototype, "_nativeAsset"), _class2.prototype)), _class2)) || _class));
            Asset.prototype.createNode = null;
            legacyCC.Asset = Asset;

            var CUSTOM_PIXEL_FORMAT = 1024;
            var PixelFormat;

            (function (PixelFormat) {
              PixelFormat[PixelFormat["RGB565"] = Format.R5G6B5] = "RGB565";
              PixelFormat[PixelFormat["RGB5A1"] = Format.RGB5A1] = "RGB5A1";
              PixelFormat[PixelFormat["RGBA4444"] = Format.RGBA4] = "RGBA4444";
              PixelFormat[PixelFormat["RGB888"] = Format.RGB8] = "RGB888";
              PixelFormat[PixelFormat["RGB32F"] = Format.RGB32F] = "RGB32F";
              PixelFormat[PixelFormat["RGBA8888"] = Format.RGBA8] = "RGBA8888";
              PixelFormat[PixelFormat["RGBA32F"] = Format.RGBA32F] = "RGBA32F";
              PixelFormat[PixelFormat["A8"] = Format.A8] = "A8";
              PixelFormat[PixelFormat["I8"] = Format.L8] = "I8";
              PixelFormat[PixelFormat["AI8"] = Format.LA8] = "AI8";
              PixelFormat[PixelFormat["RGB_PVRTC_2BPPV1"] = Format.PVRTC_RGB2] = "RGB_PVRTC_2BPPV1";
              PixelFormat[PixelFormat["RGBA_PVRTC_2BPPV1"] = Format.PVRTC_RGBA2] = "RGBA_PVRTC_2BPPV1";
              PixelFormat[PixelFormat["RGB_A_PVRTC_2BPPV1"] = CUSTOM_PIXEL_FORMAT++] = "RGB_A_PVRTC_2BPPV1";
              PixelFormat[PixelFormat["RGB_PVRTC_4BPPV1"] = Format.PVRTC_RGB4] = "RGB_PVRTC_4BPPV1";
              PixelFormat[PixelFormat["RGBA_PVRTC_4BPPV1"] = Format.PVRTC_RGBA4] = "RGBA_PVRTC_4BPPV1";
              PixelFormat[PixelFormat["RGB_A_PVRTC_4BPPV1"] = CUSTOM_PIXEL_FORMAT++] = "RGB_A_PVRTC_4BPPV1";
              PixelFormat[PixelFormat["RGB_ETC1"] = Format.ETC_RGB8] = "RGB_ETC1";
              PixelFormat[PixelFormat["RGBA_ETC1"] = CUSTOM_PIXEL_FORMAT++] = "RGBA_ETC1";
              PixelFormat[PixelFormat["RGB_ETC2"] = Format.ETC2_RGB8] = "RGB_ETC2";
              PixelFormat[PixelFormat["RGBA_ETC2"] = Format.ETC2_RGBA8] = "RGBA_ETC2";
              PixelFormat[PixelFormat["RGBA_ASTC_4x4"] = Format.ASTC_RGBA_4x4] = "RGBA_ASTC_4x4";
              PixelFormat[PixelFormat["RGBA_ASTC_5x4"] = Format.ASTC_RGBA_5x4] = "RGBA_ASTC_5x4";
              PixelFormat[PixelFormat["RGBA_ASTC_5x5"] = Format.ASTC_RGBA_5x5] = "RGBA_ASTC_5x5";
              PixelFormat[PixelFormat["RGBA_ASTC_6x5"] = Format.ASTC_RGBA_6x5] = "RGBA_ASTC_6x5";
              PixelFormat[PixelFormat["RGBA_ASTC_6x6"] = Format.ASTC_RGBA_6x6] = "RGBA_ASTC_6x6";
              PixelFormat[PixelFormat["RGBA_ASTC_8x5"] = Format.ASTC_RGBA_8x5] = "RGBA_ASTC_8x5";
              PixelFormat[PixelFormat["RGBA_ASTC_8x6"] = Format.ASTC_RGBA_8x6] = "RGBA_ASTC_8x6";
              PixelFormat[PixelFormat["RGBA_ASTC_8x8"] = Format.ASTC_RGBA_8x8] = "RGBA_ASTC_8x8";
              PixelFormat[PixelFormat["RGBA_ASTC_10x5"] = Format.ASTC_RGBA_10x5] = "RGBA_ASTC_10x5";
              PixelFormat[PixelFormat["RGBA_ASTC_10x6"] = Format.ASTC_RGBA_10x6] = "RGBA_ASTC_10x6";
              PixelFormat[PixelFormat["RGBA_ASTC_10x8"] = Format.ASTC_RGBA_10x8] = "RGBA_ASTC_10x8";
              PixelFormat[PixelFormat["RGBA_ASTC_10x10"] = Format.ASTC_RGBA_10x10] = "RGBA_ASTC_10x10";
              PixelFormat[PixelFormat["RGBA_ASTC_12x10"] = Format.ASTC_RGBA_12x10] = "RGBA_ASTC_12x10";
              PixelFormat[PixelFormat["RGBA_ASTC_12x12"] = Format.ASTC_RGBA_12x12] = "RGBA_ASTC_12x12";
            })(PixelFormat || (PixelFormat = {}));

            var WrapMode$2;

            (function (WrapMode) {
              WrapMode[WrapMode["REPEAT"] = Address.WRAP] = "REPEAT";
              WrapMode[WrapMode["CLAMP_TO_EDGE"] = Address.CLAMP] = "CLAMP_TO_EDGE";
              WrapMode[WrapMode["MIRRORED_REPEAT"] = Address.MIRROR] = "MIRRORED_REPEAT";
              WrapMode[WrapMode["CLAMP_TO_BORDER"] = Address.BORDER] = "CLAMP_TO_BORDER";
            })(WrapMode$2 || (WrapMode$2 = {}));

            var Filter$1;

            (function (Filter$1) {
              Filter$1[Filter$1["NONE"] = Filter.NONE] = "NONE";
              Filter$1[Filter$1["LINEAR"] = Filter.LINEAR] = "LINEAR";
              Filter$1[Filter$1["NEAREST"] = Filter.POINT] = "NEAREST";
            })(Filter$1 || (Filter$1 = {}));

            var _dec$1, _class$1, _class2$1, _class3, _temp$1;

            function isImageBitmap(imageSource) {
              return legacyCC.sys.capabilities.imageBitmap && imageSource instanceof ImageBitmap;
            }

            function isNativeImage(imageSource) {

              return imageSource instanceof HTMLImageElement || imageSource instanceof HTMLCanvasElement || isImageBitmap(imageSource);
            }

            var ImageAsset = exports('ImageAsset', (_dec$1 = ccclass('cc.ImageAsset'), _dec$1(_class$1 = (_class2$1 = (_temp$1 = _class3 = function (_Asset) {
              _inheritsLoose(ImageAsset, _Asset);

              function ImageAsset(nativeAsset) {
                var _this;

                _this = _Asset.call(this) || this;
                _this._nativeData = void 0;
                _this._tex = void 0;
                _this._exportedExts = undefined;
                _this._format = PixelFormat.RGBA8888;
                _this._width = 0;
                _this._height = 0;
                _this.loaded = false;
                _this._nativeData = {
                  _data: null,
                  width: 0,
                  height: 0,
                  format: 0,
                  _compressed: false
                };

                if (nativeAsset !== undefined) {
                  _this.reset(nativeAsset);
                }

                return _this;
              }

              var _proto = ImageAsset.prototype;

              _proto.reset = function reset(data) {
                var _this2 = this;

                if (isImageBitmap(data)) {
                  this._nativeData = data;

                  this._onDataComplete();
                } else if (!(data instanceof HTMLElement)) {
                  this._nativeData = data;
                  this._format = data.format;

                  this._onDataComplete();
                } else {
                  this._nativeData = data;

                  if ( data.complete || data instanceof HTMLCanvasElement) {
                    this._onDataComplete();
                  } else {
                    this.loaded = false;
                    data.addEventListener('load', function () {
                      _this2._onDataComplete();
                    });
                    data.addEventListener('error', function (err) {
                      warnID(3119, err.message);
                    });
                  }
                }
              };

              _proto.destroy = function destroy() {
                if (this.data && this.data instanceof HTMLImageElement) {
                  this.data.src = '';

                  this._setRawAsset('');
                } else if (isImageBitmap(this.data)) {
                  this.data.close && this.data.close();
                }

                return _Asset.prototype.destroy.call(this);
              };

              _proto._serialize = function _serialize() {
              };

              _proto._deserialize = function _deserialize(data) {
                var fmtStr = '';

                if (typeof data === 'string') {
                  fmtStr = data;
                } else {
                  this._width = data.w;
                  this._height = data.h;
                  fmtStr = data.fmt;
                }

                var device = _getGlobalDevice();

                var extensionIDs = fmtStr.split('_');
                var defaultExt = '';
                var preferedExtensionIndex = Number.MAX_VALUE;
                var format = this._format;
                var ext = '';
                var SupportTextureFormats = legacyCC.macro.SUPPORT_TEXTURE_FORMATS;

                for (var _iterator2 = _createForOfIteratorHelperLoose(extensionIDs), _step2; !(_step2 = _iterator2()).done;) {
                  var extensionID = _step2.value;
                  var extFormat = extensionID.split('@');
                  var i = parseInt(extFormat[0], undefined);
                  var tmpExt = ImageAsset.extnames[i] || extFormat[0];
                  var index = SupportTextureFormats.indexOf(tmpExt);

                  if (index !== -1 && index < preferedExtensionIndex) {
                    var fmt = extFormat[1] ? parseInt(extFormat[1]) : this._format;

                    if (tmpExt === '.astc' && (!device || !device.hasFeature(Feature.FORMAT_ASTC))) {
                      continue;
                    } else if (tmpExt === '.pvr' && (!device || !device.hasFeature(Feature.FORMAT_PVRTC))) {
                      continue;
                    } else if ((fmt === PixelFormat.RGB_ETC1 || fmt === PixelFormat.RGBA_ETC1) && (!device || !device.hasFeature(Feature.FORMAT_ETC1))) {
                      continue;
                    } else if ((fmt === PixelFormat.RGB_ETC2 || fmt === PixelFormat.RGBA_ETC2) && (!device || !device.hasFeature(Feature.FORMAT_ETC2))) {
                      continue;
                    } else if (tmpExt === '.webp' && !legacyCC.sys.capabilities.webp) {
                      continue;
                    }

                    preferedExtensionIndex = index;
                    ext = tmpExt;
                    format = fmt;
                  } else if (!defaultExt) {
                    defaultExt = tmpExt;
                  }
                }

                if (ext) {
                  this._setRawAsset(ext);

                  this._format = format;
                } else if (defaultExt) {
                  this._setRawAsset(defaultExt);

                  warnID(3120, defaultExt, defaultExt);
                } else {
                  warnID(3121);
                }
              };

              _proto._onDataComplete = function _onDataComplete() {
                this.loaded = true;
                this.emit('load');
              };

              _proto.initDefault = function initDefault(uuid) {
                _Asset.prototype.initDefault.call(this, uuid);

                if (!ImageAsset._sharedPlaceHolderCanvas) {
                  var canvas = document.createElement('canvas');
                  var context = canvas.getContext('2d');
                  var l = canvas.width = canvas.height = 2;
                  context.fillStyle = '#ff00ff';
                  context.fillRect(0, 0, l, l);
                  this.reset(canvas);
                  ImageAsset._sharedPlaceHolderCanvas = canvas;
                } else {
                  this.reset(ImageAsset._sharedPlaceHolderCanvas);
                }
              };

              _proto.validate = function validate() {
                return !!this.data;
              };

              _createClass(ImageAsset, [{
                key: "_nativeAsset",
                get: function get() {
                  return this._nativeData;
                },
                set: function set(value) {
                  if (!(value instanceof HTMLElement) && !isImageBitmap(value)) {
                    value.format = value.format || this._format;
                  }

                  this.reset(value);
                }
              }, {
                key: "data",
                get: function get() {
                  if (this._nativeData && isNativeImage(this._nativeData)) {
                    return this._nativeData;
                  }

                  return this._nativeData && this._nativeData._data;
                }
              }, {
                key: "width",
                get: function get() {
                  return this._nativeData.width || this._width;
                }
              }, {
                key: "height",
                get: function get() {
                  return this._nativeData.height || this._height;
                }
              }, {
                key: "format",
                get: function get() {
                  return this._format;
                }
              }, {
                key: "isCompressed",
                get: function get() {
                  return this._format >= PixelFormat.RGB_ETC1 && this._format <= PixelFormat.RGBA_ASTC_12x12 || this._format >= PixelFormat.RGB_A_PVRTC_2BPPV1 && this._format <= PixelFormat.RGBA_ETC1;
                }
              }, {
                key: "url",
                get: function get() {
                  return this.nativeUrl;
                }
              }, {
                key: "_texture",
                get: function get() {
                  if (!this._tex) {
                    var tex = new legacyCC.Texture2D();
                    tex.name = this.nativeUrl;
                    tex.image = this;
                    this._tex = tex;
                  }

                  return this._tex;
                },
                set: function set(tex) {
                  this._tex = tex;
                }
              }]);

              return ImageAsset;
            }(Asset), _class3.extnames = ['.png', '.jpg', '.jpeg', '.bmp', '.webp', '.pvr', '.pkm', '.astc'], _class3._sharedPlaceHolderCanvas = null, _temp$1), (_applyDecoratedDescriptor(_class2$1.prototype, "_nativeAsset", [override], Object.getOwnPropertyDescriptor(_class2$1.prototype, "_nativeAsset"), _class2$1.prototype)), _class2$1)) || _class$1));

            function _getGlobalDevice() {
              if (legacyCC.director.root) {
                return legacyCC.director.root.device;
              }

              return null;
            }

            legacyCC.ImageAsset = ImageAsset;

            var SamplerInfoIndex;

            (function (SamplerInfoIndex) {
              SamplerInfoIndex[SamplerInfoIndex["minFilter"] = 0] = "minFilter";
              SamplerInfoIndex[SamplerInfoIndex["magFilter"] = 1] = "magFilter";
              SamplerInfoIndex[SamplerInfoIndex["mipFilter"] = 2] = "mipFilter";
              SamplerInfoIndex[SamplerInfoIndex["addressU"] = 3] = "addressU";
              SamplerInfoIndex[SamplerInfoIndex["addressV"] = 4] = "addressV";
              SamplerInfoIndex[SamplerInfoIndex["addressW"] = 5] = "addressW";
              SamplerInfoIndex[SamplerInfoIndex["maxAnisotropy"] = 6] = "maxAnisotropy";
              SamplerInfoIndex[SamplerInfoIndex["cmpFunc"] = 7] = "cmpFunc";
              SamplerInfoIndex[SamplerInfoIndex["mipLODBias"] = 8] = "mipLODBias";
              SamplerInfoIndex[SamplerInfoIndex["total"] = 9] = "total";
            })(SamplerInfoIndex || (SamplerInfoIndex = {}));

            var defaultInfo = [Filter.LINEAR, Filter.LINEAR, Filter.NONE, Address.WRAP, Address.WRAP, Address.WRAP, 0, ComparisonFunc.NEVER, 0];
            var defaultSamplerHash = genSamplerHash(defaultInfo);
            var borderColor = new Color$1();

            var _samplerInfo = new SamplerInfo();

            function genSamplerHash(info) {
              var value = 0;
              var hash = 0;

              for (var i = 0; i < defaultInfo.length; i++) {
                value = info[i] || defaultInfo[i];

                switch (i) {
                  case SamplerInfoIndex.minFilter:
                    hash |= value;
                    break;

                  case SamplerInfoIndex.magFilter:
                    hash |= value << 2;
                    break;

                  case SamplerInfoIndex.mipFilter:
                    hash |= value << 4;
                    break;

                  case SamplerInfoIndex.addressU:
                    hash |= value << 6;
                    break;

                  case SamplerInfoIndex.addressV:
                    hash |= value << 8;
                    break;

                  case SamplerInfoIndex.addressW:
                    hash |= value << 10;
                    break;

                  case SamplerInfoIndex.maxAnisotropy:
                    hash |= value << 12;
                    break;

                  case SamplerInfoIndex.cmpFunc:
                    hash |= value << 16;
                    break;

                  case SamplerInfoIndex.mipLODBias:
                    hash |= value << 28;
                    break;
                }
              }

              return hash;
            }

            var SamplerLib = function () {
              function SamplerLib() {
                this._cache = {};
              }

              var _proto = SamplerLib.prototype;

              _proto.getSampler = function getSampler(device, hash) {
                if (!hash) {
                  hash = defaultSamplerHash;
                }

                var cache = this._cache[hash];

                if (cache) {
                  return cache;
                }

                _samplerInfo.minFilter = hash & 3;
                _samplerInfo.magFilter = hash >> 2 & 3;
                _samplerInfo.mipFilter = hash >> 4 & 3;
                _samplerInfo.addressU = hash >> 6 & 3;
                _samplerInfo.addressV = hash >> 8 & 3;
                _samplerInfo.addressW = hash >> 10 & 3;
                _samplerInfo.maxAnisotropy = hash >> 12 & 15;
                _samplerInfo.cmpFunc = hash >> 16 & 15;
                _samplerInfo.mipLODBias = hash >> 28 & 15;
                _samplerInfo.borderColor = borderColor;
                var sampler = this._cache[hash] = device.createSampler(_samplerInfo);
                return sampler;
              };

              return SamplerLib;
            }();

            var samplerLib = new SamplerLib();
            legacyCC.samplerLib = samplerLib;

            var _dec$2, _class$2, _class2$2, _descriptor$1, _descriptor2, _descriptor3, _descriptor4, _descriptor5, _descriptor6, _descriptor7, _descriptor8, _class3$1, _temp$2;
            var idGenerator = new IDGenerator('Tex');
            var TextureBase = (_dec$2 = ccclass('cc.TextureBase'), _dec$2(_class$2 = (_class2$2 = (_temp$2 = _class3$1 = function (_Asset) {
              _inheritsLoose(TextureBase, _Asset);

              function TextureBase() {
                var _this;

                _this = _Asset.call(this) || this;

                _initializerDefineProperty(_this, "_format", _descriptor$1, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_minFilter", _descriptor2, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_magFilter", _descriptor3, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_mipFilter", _descriptor4, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_wrapS", _descriptor5, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_wrapT", _descriptor6, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_wrapR", _descriptor7, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_anisotropy", _descriptor8, _assertThisInitialized(_this));

                _this._width = 1;
                _this._height = 1;
                _this._id = void 0;
                _this._samplerInfo = [];
                _this._samplerHash = 0;
                _this._gfxSampler = null;
                _this._gfxDevice = null;
                _this._textureHash = 0;
                _this._id = idGenerator.getNewId();
                _this.loaded = false;
                _this._gfxDevice = _this._getGFXDevice();
                _this._textureHash = murmurhash2_32_gc(_this._id, 666);
                return _this;
              }

              var _proto = TextureBase.prototype;

              _proto.getId = function getId() {
                return this._id;
              };

              _proto.getPixelFormat = function getPixelFormat() {
                return this._format;
              };

              _proto.getAnisotropy = function getAnisotropy() {
                return this._anisotropy;
              };

              _proto.setWrapMode = function setWrapMode(wrapS, wrapT, wrapR) {
                this._wrapS = wrapS;
                this._samplerInfo[SamplerInfoIndex.addressU] = wrapS;
                this._wrapT = wrapT;
                this._samplerInfo[SamplerInfoIndex.addressV] = wrapT;

                if (wrapR !== undefined) {
                  this._wrapR = wrapR;
                  this._samplerInfo[SamplerInfoIndex.addressW] = wrapR;
                }

                this._samplerHash = genSamplerHash(this._samplerInfo);

                if (this._gfxDevice) {
                  this._gfxSampler = samplerLib.getSampler(this._gfxDevice, this._samplerHash);
                }
              };

              _proto.setFilters = function setFilters(minFilter, magFilter) {
                this._minFilter = minFilter;
                this._samplerInfo[SamplerInfoIndex.minFilter] = minFilter;
                this._magFilter = magFilter;
                this._samplerInfo[SamplerInfoIndex.magFilter] = magFilter;
                this._samplerHash = genSamplerHash(this._samplerInfo);

                if (this._gfxDevice) {
                  this._gfxSampler = samplerLib.getSampler(this._gfxDevice, this._samplerHash);
                }
              };

              _proto.setMipFilter = function setMipFilter(mipFilter) {
                this._mipFilter = mipFilter;
                this._samplerInfo[SamplerInfoIndex.mipFilter] = mipFilter;
                this._samplerHash = genSamplerHash(this._samplerInfo);

                if (this._gfxDevice) {
                  this._gfxSampler = samplerLib.getSampler(this._gfxDevice, this._samplerHash);
                }
              };

              _proto.setAnisotropy = function setAnisotropy(anisotropy) {
                this._anisotropy = anisotropy;
                this._samplerInfo[SamplerInfoIndex.maxAnisotropy] = anisotropy;
                this._samplerHash = genSamplerHash(this._samplerInfo);

                if (this._gfxDevice) {
                  this._gfxSampler = samplerLib.getSampler(this._gfxDevice, this._samplerHash);
                }
              };

              _proto.destroy = function destroy() {
                var destroyed = _Asset.prototype.destroy.call(this);

                if (destroyed && legacyCC.director.root && legacyCC.director.root.batcher2D) {
                  legacyCC.director.root.batcher2D._releaseDescriptorSetCache(this._textureHash);
                }

                return destroyed;
              };

              _proto.getHash = function getHash() {
                return this._textureHash;
              };

              _proto.getGFXTexture = function getGFXTexture() {
                return null;
              };

              _proto.getSamplerHash = function getSamplerHash() {
                return this._samplerHash;
              };

              _proto.getGFXSampler = function getGFXSampler() {
                if (!this._gfxSampler) {
                  if (this._gfxDevice) {
                    this._gfxSampler = samplerLib.getSampler(this._gfxDevice, this._samplerHash);
                  } else {
                    errorID(9302);
                  }
                }

                return this._gfxSampler;
              };

              _proto._serialize = function _serialize(ctxForExporting) {

                return '';
              };

              _proto._deserialize = function _deserialize(serializedData, handle) {
                var data = serializedData;
                var fields = data.split(',');
                fields.unshift('');

                if (fields.length >= 5) {
                  this.setFilters(parseInt(fields[1]), parseInt(fields[2]));
                  this.setWrapMode(parseInt(fields[3]), parseInt(fields[4]));
                }

                if (fields.length >= 7) {
                  this.setMipFilter(parseInt(fields[5]));
                  this.setAnisotropy(parseInt(fields[6]));
                }
              };

              _proto._getGFXDevice = function _getGFXDevice() {
                if (legacyCC.director.root) {
                  return legacyCC.director.root.device;
                }

                return null;
              };

              _proto._getGFXFormat = function _getGFXFormat() {
                return this._getGFXPixelFormat(this._format);
              };

              _proto._setGFXFormat = function _setGFXFormat(format) {
                this._format = format === undefined ? PixelFormat.RGBA8888 : format;
              };

              _proto._getGFXPixelFormat = function _getGFXPixelFormat(format) {
                if (format === PixelFormat.RGBA_ETC1) {
                  format = PixelFormat.RGB_ETC1;
                } else if (format === PixelFormat.RGB_A_PVRTC_4BPPV1) {
                  format = PixelFormat.RGB_PVRTC_4BPPV1;
                } else if (format === PixelFormat.RGB_A_PVRTC_2BPPV1) {
                  format = PixelFormat.RGB_PVRTC_2BPPV1;
                }

                return format;
              };

              _createClass(TextureBase, [{
                key: "isCompressed",
                get: function get() {
                  return this._format >= PixelFormat.RGB_ETC1 && this._format <= PixelFormat.RGBA_ASTC_12x12 || this._format >= PixelFormat.RGB_A_PVRTC_2BPPV1 && this._format <= PixelFormat.RGBA_ETC1;
                }
              }, {
                key: "width",
                get: function get() {
                  return this._width;
                }
              }, {
                key: "height",
                get: function get() {
                  return this._height;
                }
              }]);

              return TextureBase;
            }(Asset), _class3$1.PixelFormat = PixelFormat, _class3$1.WrapMode = WrapMode$2, _class3$1.Filter = Filter$1, _temp$2), (_descriptor$1 = _applyDecoratedDescriptor(_class2$2.prototype, "_format", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return PixelFormat.RGBA8888;
              }
            }), _descriptor2 = _applyDecoratedDescriptor(_class2$2.prototype, "_minFilter", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return Filter$1.LINEAR;
              }
            }), _descriptor3 = _applyDecoratedDescriptor(_class2$2.prototype, "_magFilter", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return Filter$1.LINEAR;
              }
            }), _descriptor4 = _applyDecoratedDescriptor(_class2$2.prototype, "_mipFilter", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return Filter$1.NONE;
              }
            }), _descriptor5 = _applyDecoratedDescriptor(_class2$2.prototype, "_wrapS", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return WrapMode$2.REPEAT;
              }
            }), _descriptor6 = _applyDecoratedDescriptor(_class2$2.prototype, "_wrapT", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return WrapMode$2.REPEAT;
              }
            }), _descriptor7 = _applyDecoratedDescriptor(_class2$2.prototype, "_wrapR", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return WrapMode$2.REPEAT;
              }
            }), _descriptor8 = _applyDecoratedDescriptor(_class2$2.prototype, "_anisotropy", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            })), _class2$2)) || _class$2);
            legacyCC.TextureBase = TextureBase;

            var SUPPORT_MIN_FORMAT_VERSION = 1;
            var EMPTY_PLACEHOLDER = 0;
            var BuiltinValueTypes = [Vec2, Vec3, Vec4, Quat, Color, Size, Rect, Mat4];

            function BuiltinValueTypeParsers_xyzw(obj, data) {
              obj.x = data[1];
              obj.y = data[2];
              obj.z = data[3];
              obj.w = data[4];
            }

            var BuiltinValueTypeSetters = [function (obj, data) {
              obj.x = data[1];
              obj.y = data[2];
            }, function (obj, data) {
              obj.x = data[1];
              obj.y = data[2];
              obj.z = data[3];
            }, BuiltinValueTypeParsers_xyzw, BuiltinValueTypeParsers_xyzw, function (obj, data) {
              obj._val = data[1];
            }, function (obj, data) {
              obj.width = data[1];
              obj.height = data[2];
            }, function (obj, data) {
              obj.x = data[1];
              obj.y = data[2];
              obj.width = data[3];
              obj.height = data[4];
            }, function (obj, data) {
              Mat4.fromArray(obj, data, 1);
            }];

            var DataTypeID = {
              SimpleType: 0,
              InstanceRef: 1,
              Array_InstanceRef: 2,
              Array_AssetRefByInnerObj: 3,
              Class: 4,
              ValueTypeCreated: 5,
              AssetRefByInnerObj: 6,
              TRS: 7,
              ValueType: 8,
              Array_Class: 9,
              CustomizedClass: 10,
              Dict: 11,
              Array: 12,
              ARRAY_LENGTH: 13
            };
            var CLASS_TYPE = 0;
            var CLASS_KEYS = 1;
            var CLASS_PROP_TYPE_OFFSET = 2;
            var MASK_CLASS = 0;
            var OBJ_DATA_MASK = 0;
            var CUSTOM_OBJ_DATA_CLASS = 0;
            var CUSTOM_OBJ_DATA_CONTENT = 1;
            var VALUETYPE_SETTER = 0;
            var DICT_JSON_LAYOUT = 0;
            var ARRAY_ITEM_VALUES = 0;
            var Refs = {
              EACH_RECORD_LENGTH: 3,
              OWNER_OFFSET: 0,
              KEY_OFFSET: 1,
              TARGET_OFFSET: 2
            };
            var File = {
              Version: 0,
              Context: 0,
              SharedUuids: 1,
              SharedStrings: 2,
              SharedClasses: 3,
              SharedMasks: 4,
              Instances: 5,
              InstanceTypes: 6,
              Refs: 7,
              DependObjs: 8,
              DependKeys: 9,
              DependUuidIndices: 10,
              ARRAY_LENGTH: 11
            };
            var PACKED_SECTIONS = File.Instances;
            var Details = exports('Details', function () {
              function Details() {
                this.uuidObjList = null;
                this.uuidPropList = null;
                this.uuidList = null;
                this.uuidTypeList = [];
              }

              var _proto = Details.prototype;

              _proto.init = function init(data) {
                {
                  this.uuidObjList = data[File.DependObjs];
                  this.uuidPropList = data[File.DependKeys];
                  this.uuidList = data[File.DependUuidIndices];
                }
              };

              _proto.reset = function reset() {
                {
                  this.uuidList = null;
                  this.uuidObjList = null;
                  this.uuidPropList = null;
                }
              };

              _proto.push = function push(obj, propName, uuid, type) {
                this.uuidObjList.push(obj);
                this.uuidPropList.push(propName);
                this.uuidList.push(uuid);
                this.uuidTypeList.push(type || '');
              };

              return Details;
            }());
            Details.pool = new Pool(function (obj) {
              obj.reset();
            }, 5);

            Details.pool.get = function () {
              return this._get() || new Details();
            };

            function dereference(refs, instances, strings) {
              var dataLength = refs.length - 1;
              var i = 0;
              var instanceOffset = refs[dataLength] * Refs.EACH_RECORD_LENGTH;

              for (; i < instanceOffset; i += Refs.EACH_RECORD_LENGTH) {
                var _owner = refs[i];
                var target = instances[refs[i + Refs.TARGET_OFFSET]];
                var keyIndex = refs[i + Refs.KEY_OFFSET];

                if (keyIndex >= 0) {
                  _owner[strings[keyIndex]] = target;
                } else {
                  _owner[~keyIndex] = target;
                }
              }

              for (; i < dataLength; i += Refs.EACH_RECORD_LENGTH) {
                var _owner2 = instances[refs[i]];
                var _target = instances[refs[i + Refs.TARGET_OFFSET]];
                var _keyIndex = refs[i + Refs.KEY_OFFSET];

                if (_keyIndex >= 0) {
                  _owner2[strings[_keyIndex]] = _target;
                } else {
                  _owner2[~_keyIndex] = _target;
                }
              }
            }

            function deserializeCCObject(data, objectData) {
              var mask = data[File.SharedMasks][objectData[OBJ_DATA_MASK]];
              var clazz = mask[MASK_CLASS];
              var ctor = clazz[CLASS_TYPE];
              var obj = new ctor();
              var keys = clazz[CLASS_KEYS];
              var classTypeOffset = clazz[CLASS_PROP_TYPE_OFFSET];
              var maskTypeOffset = mask[mask.length - 1];
              var i = MASK_CLASS + 1;

              for (; i < maskTypeOffset; ++i) {
                var _key = keys[mask[i]];
                obj[_key] = objectData[i];
              }

              for (; i < objectData.length; ++i) {
                var _key2 = keys[mask[i]];
                var _type2 = clazz[mask[i] + classTypeOffset];
                var op = ASSIGNMENTS[_type2];
                op(data, obj, _key2, objectData[i]);
              }

              return obj;
            }

            function deserializeCustomCCObject(data, ctor, value) {
              var obj = new ctor();

              if (obj._deserialize) {
                obj._deserialize(value, data[File.Context]);
              } else {
                errorID(5303, getClassName(ctor));
              }

              return obj;
            }

            function assignSimple(data, owner, key, value) {
              owner[key] = value;
            }

            function assignInstanceRef(data, owner, key, value) {
              if (value >= 0) {
                owner[key] = data[File.Instances][value];
              } else {
                data[File.Refs][~value * Refs.EACH_RECORD_LENGTH] = owner;
              }
            }

            function genArrayParser(parser) {
              return function (data, owner, key, value) {
                owner[key] = value;

                for (var i = 0; i < value.length; ++i) {
                  parser(data, value, i, value[i]);
                }
              };
            }

            function parseAssetRefByInnerObj(data, owner, key, value) {
              owner[key] = null;
              data[File.DependObjs][value] = owner;
            }

            function parseClass(data, owner, key, value) {
              owner[key] = deserializeCCObject(data, value);
            }

            function parseCustomClass(data, owner, key, value) {
              var ctor = data[File.SharedClasses][value[CUSTOM_OBJ_DATA_CLASS]];
              owner[key] = deserializeCustomCCObject(data, ctor, value[CUSTOM_OBJ_DATA_CONTENT]);
            }

            function parseValueTypeCreated(data, owner, key, value) {
              BuiltinValueTypeSetters[value[VALUETYPE_SETTER]](owner[key], value);
            }

            function parseValueType(data, owner, key, value) {
              var val = new BuiltinValueTypes[value[VALUETYPE_SETTER]]();
              BuiltinValueTypeSetters[value[VALUETYPE_SETTER]](val, value);
              owner[key] = val;
            }

            function parseTRS(data, owner, key, value) {
              var typedArray = owner[key];
              typedArray.set(value);
            }

            function parseDict(data, owner, key, value) {
              var dict = value[DICT_JSON_LAYOUT];
              owner[key] = dict;

              for (var i = DICT_JSON_LAYOUT + 1; i < value.length; i += 3) {
                var subKey = value[i];
                var subType = value[i + 1];
                var subValue = value[i + 2];
                var op = ASSIGNMENTS[subType];
                op(data, dict, subKey, subValue);
              }
            }

            function parseArray(data, owner, key, value) {
              var array = value[ARRAY_ITEM_VALUES];
              owner[key] = array;

              for (var i = 0; i < array.length; ++i) {
                var subValue = array[i];
                var _type3 = value[i + 1];

                if (_type3 !== DataTypeID.SimpleType) {
                  var op = ASSIGNMENTS[_type3];
                  op(data, array, i, subValue);
                }
              }
            }

            var ASSIGNMENTS = new Array(DataTypeID.ARRAY_LENGTH);
            ASSIGNMENTS[DataTypeID.SimpleType] = assignSimple;
            ASSIGNMENTS[DataTypeID.InstanceRef] = assignInstanceRef;
            ASSIGNMENTS[DataTypeID.Array_InstanceRef] = genArrayParser(assignInstanceRef);
            ASSIGNMENTS[DataTypeID.Array_AssetRefByInnerObj] = genArrayParser(parseAssetRefByInnerObj);
            ASSIGNMENTS[DataTypeID.Class] = parseClass;
            ASSIGNMENTS[DataTypeID.ValueTypeCreated] = parseValueTypeCreated;
            ASSIGNMENTS[DataTypeID.AssetRefByInnerObj] = parseAssetRefByInnerObj;
            ASSIGNMENTS[DataTypeID.TRS] = parseTRS;
            ASSIGNMENTS[DataTypeID.ValueType] = parseValueType;
            ASSIGNMENTS[DataTypeID.Array_Class] = genArrayParser(parseClass);
            ASSIGNMENTS[DataTypeID.CustomizedClass] = parseCustomClass;
            ASSIGNMENTS[DataTypeID.Dict] = parseDict;
            ASSIGNMENTS[DataTypeID.Array] = parseArray;

            function parseInstances(data) {
              var instances = data[File.Instances];
              var instanceTypes = data[File.InstanceTypes];
              var instanceTypesLen = instanceTypes === EMPTY_PLACEHOLDER ? 0 : instanceTypes.length;
              var rootIndex = instances[instances.length - 1];
              var normalObjectCount = instances.length - instanceTypesLen;

              if (typeof rootIndex !== 'number') {
                rootIndex = 0;
              } else {
                if (rootIndex < 0) {
                  rootIndex = ~rootIndex;
                }

                --normalObjectCount;
              }

              var insIndex = 0;

              for (; insIndex < normalObjectCount; ++insIndex) {
                instances[insIndex] = deserializeCCObject(data, instances[insIndex]);
              }

              var classes = data[File.SharedClasses];

              for (var typeIndex = 0; typeIndex < instanceTypesLen; ++typeIndex, ++insIndex) {
                var _type4 = instanceTypes[typeIndex];
                var eachData = instances[insIndex];

                if (_type4 >= 0) {
                  var ctor = classes[_type4];
                  instances[insIndex] = deserializeCustomCCObject(data, ctor, eachData);
                } else {
                  _type4 = ~_type4;
                  var op = ASSIGNMENTS[_type4];
                  op(data, instances, insIndex, eachData);
                }
              }

              return rootIndex;
            }

            function getMissingClass(hasCustomFinder, type) {
              if (!hasCustomFinder) {
                deserialize.reportMissingClass(type);
              }

              return Object;
            }

            function doLookupClass(classFinder, type, container, index, silent, hasCustomFinder) {
              var klass = classFinder(type);

              if (!klass) {
                if (silent) {
                  container[index] = function (c, i, t) {
                    return function proxy() {
                      var actualClass = classFinder(t) || getMissingClass(hasCustomFinder, t);
                      c[i] = actualClass;
                      return new actualClass();
                    };
                  }(container, index, type);

                  return;
                } else {
                  klass = getMissingClass(hasCustomFinder, type);
                }
              }

              container[index] = klass;
            }

            function lookupClasses(data, silent, customFinder) {
              var classFinder = customFinder || _getClassById;
              var classes = data[File.SharedClasses];

              for (var i = 0; i < classes.length; ++i) {
                var klassLayout = classes[i];

                if (typeof klassLayout !== 'string') {
                  {
                    if (typeof klassLayout[CLASS_TYPE] === 'function') {
                      throw new Error('Can not deserialize the same JSON data again.');
                    }
                  }

                  var _type5 = klassLayout[CLASS_TYPE];
                  doLookupClass(classFinder, _type5, klassLayout, CLASS_TYPE, silent, customFinder);
                } else {
                  doLookupClass(classFinder, klassLayout, classes, i, silent, customFinder);
                }
              }
            }

            function cacheMasks(data) {
              var masks = data[File.SharedMasks];

              if (masks) {
                var classes = data[File.SharedClasses];

                for (var i = 0; i < masks.length; ++i) {
                  var mask = masks[i];
                  mask[MASK_CLASS] = classes[mask[MASK_CLASS]];
                }
              }
            }

            function parseResult(data) {
              var instances = data[File.Instances];
              var sharedStrings = data[File.SharedStrings];
              var dependSharedUuids = data[File.SharedUuids];
              var dependObjs = data[File.DependObjs];
              var dependKeys = data[File.DependKeys];
              var dependUuids = data[File.DependUuidIndices];

              for (var i = 0; i < dependObjs.length; ++i) {
                var _obj2 = dependObjs[i];

                if (typeof _obj2 === 'number') {
                  dependObjs[i] = instances[_obj2];
                }

                var _key3 = dependKeys[i];

                if (typeof _key3 === 'number') {
                  if (_key3 >= 0) {
                    _key3 = sharedStrings[_key3];
                  } else {
                    _key3 = ~_key3;
                  }

                  dependKeys[i] = _key3;
                }

                var _uuid2 = dependUuids[i];

                if (typeof _uuid2 === 'number') {
                  dependUuids[i] = dependSharedUuids[_uuid2];
                }
              }
            }
            function deserialize(data, details, options) {
              if (typeof data === 'string') {
                data = JSON.parse(data);
              }

              var borrowDetails = !details;
              details = details || Details.pool.get();
              var res;

              {
                details.init(data);
                options = options || {};
                var version = data[File.Version];
                var preprocessed = false;

                if (typeof version === 'object') {
                  preprocessed = version.preprocessed;
                  version = version.version;
                }

                if (version < SUPPORT_MIN_FORMAT_VERSION) {
                  throw new Error(getError(5304, version));
                }

                options._version = version;
                options.result = details;
                data[File.Context] = options;

                if (!preprocessed) {
                  lookupClasses(data, false, options.classFinder);
                  cacheMasks(data);
                }

                legacyCC.game._isCloning = true;
                var instances = data[File.Instances];
                var rootIndex = parseInstances(data);
                legacyCC.game._isCloning = false;

                if (data[File.Refs]) {
                  dereference(data[File.Refs], instances, data[File.SharedStrings]);
                }

                parseResult(data);

                res = instances[rootIndex];
              }

              if (borrowDetails) {
                Details.pool.put(details);
              }

              return res;
            }
            deserialize.Details = Details;

            deserialize.reportMissingClass = function (id) {
              {
                warnID(5302, id);
              }
            };

            var FileInfo = function FileInfo(version) {
              this.preprocessed = true;
              this.version = version;
            };

            function unpackJSONs(data, classFinder) {
              if (data[File.Version] < SUPPORT_MIN_FORMAT_VERSION) {
                throw new Error(getError(5304, data[File.Version]));
              }

              lookupClasses(data, true, classFinder);
              cacheMasks(data);
              var version = new FileInfo(data[File.Version]);
              var sharedUuids = data[File.SharedUuids];
              var sharedStrings = data[File.SharedStrings];
              var sharedClasses = data[File.SharedClasses];
              var sharedMasks = data[File.SharedMasks];
              var sections = data[PACKED_SECTIONS];

              for (var i = 0; i < sections.length; ++i) {
                sections[i].unshift(version, sharedUuids, sharedStrings, sharedClasses, sharedMasks);
              }

              return sections;
            }
            function packCustomObjData(type, data, hasNativeDep) {
              return [SUPPORT_MIN_FORMAT_VERSION, EMPTY_PLACEHOLDER, EMPTY_PLACEHOLDER, [type], EMPTY_PLACEHOLDER, hasNativeDep ? [data, ~0] : [data], [0], EMPTY_PLACEHOLDER, [], [], []];
            }
            function hasNativeDep(data) {
              var instances = data[File.Instances];
              var rootInfo = instances[instances.length - 1];

              if (typeof rootInfo !== 'number') {
                return false;
              } else {
                return rootInfo < 0;
              }
            }
            function getDependUuidList(json) {
              var sharedUuids = json[File.SharedUuids];
              return json[File.DependUuidIndices].map(function (index) {
                return sharedUuids[index];
              });
            }

            legacyCC.deserialize = deserialize;

            var _dec$3, _class$3, _dec2, _class2$3, _dec3, _class3$2;
            var Script = exports('Script', (_dec$3 = ccclass('cc.Script'), _dec$3(_class$3 = function (_Asset) {
              _inheritsLoose(Script, _Asset);

              function Script() {
                return _Asset.apply(this, arguments) || this;
              }

              return Script;
            }(Asset)) || _class$3));
            legacyCC._Script = Script;
            var JavaScript = exports('JavaScript', (_dec2 = ccclass('cc.JavaScript'), _dec2(_class2$3 = function (_Script) {
              _inheritsLoose(JavaScript, _Script);

              function JavaScript() {
                return _Script.apply(this, arguments) || this;
              }

              return JavaScript;
            }(Script)) || _class2$3));
            legacyCC._JavaScript = JavaScript;
            var TypeScript = exports('TypeScript', (_dec3 = ccclass('cc.TypeScript'), _dec3(_class3$2 = function (_Script2) {
              _inheritsLoose(TypeScript, _Script2);

              function TypeScript() {
                return _Script2.apply(this, arguments) || this;
              }

              return TypeScript;
            }(Script)) || _class3$2));
            legacyCC._TypeScript = TypeScript;

            var _dec$4, _dec2$1, _dec3$1, _dec4, _class$4, _class2$4, _descriptor$2, _descriptor2$1, _descriptor3$1, _class3$3, _temp$3;
            var idGenerator$1 = new IDGenerator('Comp');
            var IsOnLoadCalled$1 = CCObject.Flags.IsOnLoadCalled;
            var NullNode = null;
            var Component = exports('Component', (_dec$4 = ccclass('cc.Component'), _dec2$1 = displayName(), _dec3$1 = type(Script), _dec4 = tooltip(), _dec$4(_class$4 = (_class2$4 = (_temp$3 = _class3$3 = function (_CCObject) {
              _inheritsLoose(Component, _CCObject);

              function Component() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _CCObject.call.apply(_CCObject, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "node", _descriptor$2, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_enabled", _descriptor2$1, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "__prefab", _descriptor3$1, _assertThisInitialized(_this));

                _this._sceneGetter = null;
                _this._id = idGenerator$1.getNewId();
                return _this;
              }

              var _proto = Component.prototype;

              _proto._getRenderScene = function _getRenderScene() {
                if (this._sceneGetter) {
                  return this._sceneGetter();
                }

                return this.node.scene._renderScene;
              };

              _proto.addComponent = function addComponent(typeOrClassName) {
                return this.node.addComponent(typeOrClassName);
              };

              _proto.getComponent = function getComponent(typeOrClassName) {
                return this.node.getComponent(typeOrClassName);
              };

              _proto.getComponents = function getComponents(typeOrClassName) {
                return this.node.getComponents(typeOrClassName);
              };

              _proto.getComponentInChildren = function getComponentInChildren(typeOrClassName) {
                return this.node.getComponentInChildren(typeOrClassName);
              };

              _proto.getComponentsInChildren = function getComponentsInChildren(typeOrClassName) {
                return this.node.getComponentsInChildren(typeOrClassName);
              };

              _proto.destroy = function destroy() {

                if (_CCObject.prototype.destroy.call(this)) {
                  if (this._enabled && this.node.activeInHierarchy) {
                    legacyCC.director._compScheduler.disableComp(this);
                  }

                  return true;
                }

                return false;
              };

              _proto._onPreDestroy = function _onPreDestroy() {
                this.unscheduleAllCallbacks();

                legacyCC.director._nodeActivator.destroyComp(this);

                this.node._removeComponent(this);
              };

              _proto._instantiate = function _instantiate(cloned) {
                if (!cloned) {
                  cloned = legacyCC.instantiate._clone(this, this);
                }

                if (cloned) {
                  cloned.node = NullNode;
                }

                return cloned;
              };

              _proto.schedule = function schedule(callback, interval, repeat, delay) {
                if (interval === void 0) {
                  interval = 0;
                }

                if (repeat === void 0) {
                  repeat = legacyCC.macro.REPEAT_FOREVER;
                }

                if (delay === void 0) {
                  delay = 0;
                }

                assertID(callback, 1619);
                interval = interval || 0;
                assertID(interval >= 0, 1620);
                repeat = Number.isNaN(repeat) ? legacyCC.macro.REPEAT_FOREVER : repeat;
                delay = delay || 0;
                var scheduler = legacyCC.director.getScheduler();
                var paused = scheduler.isTargetPaused(this);
                scheduler.schedule(callback, this, interval, repeat, delay, paused);
              };

              _proto.scheduleOnce = function scheduleOnce(callback, delay) {
                if (delay === void 0) {
                  delay = 0;
                }

                this.schedule(callback, 0, 0, delay);
              };

              _proto.unschedule = function unschedule(callback_fn) {
                if (!callback_fn) {
                  return;
                }

                legacyCC.director.getScheduler().unschedule(callback_fn, this);
              };

              _proto.unscheduleAllCallbacks = function unscheduleAllCallbacks() {
                legacyCC.director.getScheduler().unscheduleAllForTarget(this);
              };

              _createClass(Component, [{
                key: "name",
                get: function get() {
                  if (this._name) {
                    return this._name;
                  }

                  var className = getClassName(this);
                  var trimLeft = className.lastIndexOf('.');

                  if (trimLeft >= 0) {
                    className = className.slice(trimLeft + 1);
                  }

                  return this.node.name + "<" + className + ">";
                },
                set: function set(value) {
                  this._name = value;
                }
              }, {
                key: "uuid",
                get: function get() {
                  return this._id;
                }
              }, {
                key: "__scriptAsset",
                get: function get() {
                  return null;
                }
              }, {
                key: "enabled",
                get: function get() {
                  return this._enabled;
                },
                set: function set(value) {
                  if (this._enabled !== value) {
                    this._enabled = value;

                    if (this.node.activeInHierarchy) {
                      var compScheduler = legacyCC.director._compScheduler;

                      if (value) {
                        compScheduler.enableComp(this);
                      } else {
                        compScheduler.disableComp(this);
                      }
                    }
                  }
                }
              }, {
                key: "enabledInHierarchy",
                get: function get() {
                  return this._enabled && this.node && this.node.activeInHierarchy;
                }
              }, {
                key: "_isOnLoadCalled",
                get: function get() {
                  return this._objFlags & IsOnLoadCalled$1;
                }
              }]);

              return Component;
            }(CCObject), _class3$3.system = null, _temp$3), (_applyDecoratedDescriptor(_class2$4.prototype, "__scriptAsset", [_dec2$1, _dec3$1, _dec4, disallowAnimation], Object.getOwnPropertyDescriptor(_class2$4.prototype, "__scriptAsset"), _class2$4.prototype), _descriptor$2 = _applyDecoratedDescriptor(_class2$4.prototype, "node", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return NullNode;
              }
            }), _descriptor2$1 = _applyDecoratedDescriptor(_class2$4.prototype, "_enabled", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _descriptor3$1 = _applyDecoratedDescriptor(_class2$4.prototype, "__prefab", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            })), _class2$4)) || _class$4));
            var proto = Component.prototype;
            proto.update = null;
            proto.lateUpdate = null;
            proto.__preload = null;
            proto.onLoad = null;
            proto.start = null;
            proto.onEnable = null;
            proto.onDisable = null;
            proto.onDestroy = null;
            proto.onFocusInEditor = null;
            proto.onLostFocusInEditor = null;
            proto.resetInEditor = null;
            proto._getLocalBounds = null;
            proto.onRestore = null;
            Component._requireComponent = null;
            Component._executionOrder = 0;

            value(Component, '_registerEditorProps', function (cls, props) {
              var reqComp = props.requireComponent;

              if (reqComp) {
                cls._requireComponent = reqComp;
              }

              var order = props.executionOrder;

              if (order && typeof order === 'number') {
                cls._executionOrder = order;
              }
            });
            legacyCC.Component = Component;

            var _dec$5, _dec2$2, _class$5, _class2$5, _descriptor$3, _temp$4;
            var MissingScript = exports('MissingScript', (_dec$5 = ccclass('cc.MissingScript'), _dec2$2 = inspector(), _dec$5(_class$5 = _dec2$2(_class$5 = (_class2$5 = (_temp$4 = function (_Component) {
              _inheritsLoose(MissingScript, _Component);

              MissingScript.safeFindClass = function safeFindClass(id) {
                var cls = _getClassById(id);

                if (cls) {
                  return cls;
                }

                legacyCC.deserialize.reportMissingClass(id);
                return undefined;
              };

              function MissingScript() {
                var _this;

                _this = _Component.call(this) || this;

                _initializerDefineProperty(_this, "_$erialized", _descriptor$3, _assertThisInitialized(_this));

                return _this;
              }

              var _proto = MissingScript.prototype;

              _proto.onLoad = function onLoad() {
                warnID(4600, this.node.name);
              };

              return MissingScript;
            }(Component), _temp$4), (_descriptor$3 = _applyDecoratedDescriptor(_class2$5.prototype, "_$erialized", [serializable, editorOnly], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            })), _class2$5)) || _class$5) || _class$5));
            legacyCC._MissingScript = MissingScript;

            function deserialize$1 (json, options) {
              var classFinder;

              {
                classFinder = MissingScript.safeFindClass;
              }

              var tdInfo = Details.pool.get();
              var asset;

              try {
                asset = deserialize(json, tdInfo, {
                  classFinder: classFinder,
                  customEnv: options
                });
              } catch (e) {
                error(e);
                Details.pool.put(tdInfo);
                throw e;
              }

              asset._uuid = options.__uuid__ || '';

              var uuidList = tdInfo.uuidList;
              var objList = tdInfo.uuidObjList;
              var propList = tdInfo.uuidPropList;
              var typeList = tdInfo.uuidTypeList || [];
              var depends = [];

              for (var i = 0; i < uuidList.length; i++) {
                var dependUuid = uuidList[i];
                depends[i] = {
                  uuid: decodeUuid(dependUuid),
                  owner: objList[i],
                  prop: propList[i],
                  type: js._getClassById(typeList[i])
                };
              }

              asset.__depends__ = depends;

              if (asset._native) {
                asset.__nativeDepend__ = true;
              }

              Details.pool.put(tdInfo);
              return asset;
            }

            var DependUtil = function () {
              function DependUtil() {
                this._depends = new Cache();
              }

              var _proto = DependUtil.prototype;

              _proto.init = function init() {
                this._depends.clear();
              };

              _proto.getNativeDep = function getNativeDep(uuid) {
                var depend = this._depends.get(uuid);

                if (depend && depend.nativeDep) {
                  return _extends({}, depend.nativeDep);
                }

                return null;
              };

              _proto.getDeps = function getDeps(uuid) {
                if (this._depends.has(uuid)) {
                  return this._depends.get(uuid).deps;
                }

                return [];
              };

              _proto.getDepsRecursively = function getDepsRecursively(uuid) {
                var exclude = Object.create(null);
                var depends = [];

                this._descend(uuid, exclude, depends);

                return depends;
              };

              _proto.remove = function remove(uuid) {
                this._depends.remove(uuid);
              };

              _proto.parse = function parse(uuid, json) {
                var out = null;

                if (Array.isArray(json) || json.__type__) {
                  if (this._depends.has(uuid)) {
                    return this._depends.get(uuid);
                  }

                  if (Array.isArray(json) && ( !hasNativeDep(json))) {
                    out = {
                      deps: this._parseDepsFromJson(json)
                    };
                  } else {
                    try {
                      var asset = deserialize$1(json, {
                        __uuid__: uuid
                      });
                      out = this._parseDepsFromAsset(asset);

                      if (out.nativeDep) {
                        out.nativeDep.uuid = uuid;
                      }

                      parsed.add(uuid + "@import", asset);
                    } catch (e) {
                      files.remove(uuid + "@import");
                      out = {
                        deps: []
                      };
                    }
                  }
                } else {
                  if ( this._depends.has(uuid)) {
                    out = this._depends.get(uuid);

                    if (out.parsedFromExistAsset) {
                      return out;
                    }
                  }

                  out = this._parseDepsFromAsset(json);
                }

                this._depends.add(uuid, out);

                return out;
              };

              _proto._parseDepsFromAsset = function _parseDepsFromAsset(asset) {
                var out = {
                  deps: [],
                  parsedFromExistAsset: true
                };
                var deps = asset.__depends__;

                for (var i = 0, l = deps.length; i < l; i++) {
                  out.deps.push(deps[i].uuid);
                }

                if (asset.__nativeDepend__) {
                  out.nativeDep = asset._nativeDep;
                }

                return out;
              };

              _proto._parseDepsFromJson = function _parseDepsFromJson(json) {
                var depends = null;

                depends = getDependUuidList(json);
                depends.forEach(function (uuid, index) {
                  return depends[index] = decodeUuid(uuid);
                });
                return depends;
              };

              _proto._descend = function _descend(uuid, exclude, depends) {
                var deps = this.getDeps(uuid);

                for (var i = 0; i < deps.length; i++) {
                  var depend = deps[i];

                  if (!exclude[depend]) {
                    exclude[depend] = true;
                    depends.push(depend);

                    this._descend(depend, exclude, depends);
                  }
                }
              };

              return DependUtil;
            }();
            var dependUtil = new DependUtil();

            var _dec$6, _class$6, _temp$5;
            var _regions = [new BufferTextureCopy()];

            function getMipLevel(width, height) {
              var size = Math.max(width, height);
              var level = 0;

              while (size) {
                size >>= 1;
                level++;
              }

              return level;
            }

            function isPOT(n) {
              return n && (n & n - 1) === 0;
            }

            function canGenerateMipmap(device, w, h) {
              var needCheckPOT = device.gfxAPI === API.WEBGL;

              if (needCheckPOT) {
                return isPOT(w) && isPOT(h);
              }

              return true;
            }

            var SimpleTexture = (_dec$6 = ccclass('cc.SimpleTexture'), _dec$6(_class$6 = (_temp$5 = function (_TextureBase) {
              _inheritsLoose(SimpleTexture, _TextureBase);

              function SimpleTexture() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _TextureBase.call.apply(_TextureBase, [this].concat(args)) || this;
                _this._gfxTexture = null;
                _this._mipmapLevel = 1;
                _this._textureWidth = 0;
                _this._textureHeight = 0;
                return _this;
              }

              var _proto = SimpleTexture.prototype;

              _proto.getGFXTexture = function getGFXTexture() {
                return this._gfxTexture;
              };

              _proto.destroy = function destroy() {
                this._tryDestroyTexture();

                return _TextureBase.prototype.destroy.call(this);
              };

              _proto.updateImage = function updateImage() {
                this.updateMipmaps(0);
              };

              _proto.updateMipmaps = function updateMipmaps(firstLevel, count) {
              };

              _proto.uploadData = function uploadData(source, level, arrayIndex) {
                if (level === void 0) {
                  level = 0;
                }

                if (arrayIndex === void 0) {
                  arrayIndex = 0;
                }

                if (!this._gfxTexture || this._mipmapLevel <= level) {
                  return;
                }

                var gfxDevice = this._getGFXDevice();

                if (!gfxDevice) {
                  return;
                }

                var region = _regions[0];
                region.texExtent.width = this._textureWidth >> level;
                region.texExtent.height = this._textureHeight >> level;
                region.texSubres.mipLevel = level;
                region.texSubres.baseArrayLayer = arrayIndex;

                if (ArrayBuffer.isView(source)) {
                  gfxDevice.copyBuffersToTexture([source], this._gfxTexture, _regions);
                } else {
                  gfxDevice.copyTexImagesToTexture([source], this._gfxTexture, _regions);
                }
              };

              _proto._assignImage = function _assignImage(image, level, arrayIndex) {
                var _this2 = this;

                var upload = function upload() {
                  var data = image.data;

                  if (!data) {
                    return;
                  }

                  _this2.uploadData(data, level, arrayIndex);

                  _this2._checkTextureLoaded();

                  if (macro.CLEANUP_IMAGE_CACHE) {
                    var deps = dependUtil.getDeps(_this2._uuid);
                    var index = deps.indexOf(image._uuid);

                    if (index !== -1) {
                      fastRemoveAt(deps, index);
                      image.decRef();
                    }
                  }
                };

                if (image.loaded) {
                  upload();
                } else {
                  image.once('load', function () {
                    upload();
                  });

                  if (!this.isCompressed) {
                    var defaultImg = legacyCC.builtinResMgr.get('black-texture').image;
                    this.uploadData(defaultImg.data, level, arrayIndex);
                  }

                  legacyCC.assetManager.postLoadNative(image);
                }
              };

              _proto._checkTextureLoaded = function _checkTextureLoaded() {
                this._textureReady();
              };

              _proto._textureReady = function _textureReady() {
                this.loaded = true;
                this.emit('load');
              };

              _proto._setMipmapLevel = function _setMipmapLevel(value) {
                this._mipmapLevel = value < 1 ? 1 : value;
              };

              _proto._getGfxTextureCreateInfo = function _getGfxTextureCreateInfo(presumed) {
                return null;
              };

              _proto._tryReset = function _tryReset() {
                this._tryDestroyTexture();

                if (this._mipmapLevel === 0) {
                  return;
                }

                var device = this._getGFXDevice();

                if (!device) {
                  return;
                }

                this._createTexture(device);
              };

              _proto._createTexture = function _createTexture(device) {
                if (this._width === 0 || this._height === 0) {
                  return;
                }

                var flags = TextureFlagBit.NONE;

                if (this._mipFilter !== Filter$1.NONE && canGenerateMipmap(device, this._width, this._height)) {
                  this._mipmapLevel = getMipLevel(this._width, this._height);
                  flags = TextureFlagBit.GEN_MIPMAP;
                }

                var textureCreateInfo = this._getGfxTextureCreateInfo({
                  usage: TextureUsageBit.SAMPLED | TextureUsageBit.TRANSFER_DST,
                  format: this._getGFXFormat(),
                  levelCount: this._mipmapLevel,
                  flags: flags | TextureFlagBit.IMMUTABLE
                });

                if (!textureCreateInfo) {
                  return;
                }

                var texture = device.createTexture(textureCreateInfo);
                this._textureWidth = textureCreateInfo.width;
                this._textureHeight = textureCreateInfo.height;
                this._gfxTexture = texture;
              };

              _proto._tryDestroyTexture = function _tryDestroyTexture() {
                if (this._gfxTexture) {
                  this._gfxTexture.destroy();

                  this._gfxTexture = null;
                }
              };

              _createClass(SimpleTexture, [{
                key: "mipmapLevel",
                get: function get() {
                  return this._mipmapLevel;
                }
              }]);

              return SimpleTexture;
            }(TextureBase), _temp$5)) || _class$6);
            legacyCC.SimpleTexture = SimpleTexture;

            var _dec$7, _dec2$3, _class$7, _class2$6, _descriptor$4, _temp$6;
            var Texture2D = exports('Texture2D', (_dec$7 = ccclass('cc.Texture2D'), _dec2$3 = type([ImageAsset]), _dec$7(_class$7 = (_class2$6 = (_temp$6 = function (_SimpleTexture) {
              _inheritsLoose(Texture2D, _SimpleTexture);

              function Texture2D() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _SimpleTexture.call.apply(_SimpleTexture, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "_mipmaps", _descriptor$4, _assertThisInitialized(_this));

                return _this;
              }

              var _proto = Texture2D.prototype;

              _proto.initialize = function initialize() {
                this.mipmaps = this._mipmaps;
              };

              _proto.onLoaded = function onLoaded() {
                this.initialize();
              };

              _proto.reset = function reset(info) {
                this._width = info.width;
                this._height = info.height;

                this._setGFXFormat(info.format);

                this._setMipmapLevel(info.mipmapLevel || 1);

                this._tryReset();
              };

              _proto.create = function create(width, height, format, mipmapLevel) {
                if (format === void 0) {
                  format = PixelFormat.RGBA8888;
                }

                if (mipmapLevel === void 0) {
                  mipmapLevel = 1;
                }

                this.reset({
                  width: width,
                  height: height,
                  format: format,
                  mipmapLevel: mipmapLevel
                });
              };

              _proto.toString = function toString() {
                return this._mipmaps.length !== 0 ? this._mipmaps[0].url : '';
              };

              _proto.updateMipmaps = function updateMipmaps(firstLevel, count) {
                if (firstLevel === void 0) {
                  firstLevel = 0;
                }

                if (firstLevel >= this._mipmaps.length) {
                  return;
                }

                var nUpdate = Math.min(count === undefined ? this._mipmaps.length : count, this._mipmaps.length - firstLevel);

                for (var i = 0; i < nUpdate; ++i) {
                  var level = firstLevel + i;

                  this._assignImage(this._mipmaps[level], level);
                }
              };

              _proto.getHtmlElementObj = function getHtmlElementObj() {
                return this._mipmaps[0] && this._mipmaps[0].data instanceof HTMLElement ? this._mipmaps[0].data : null;
              };

              _proto.destroy = function destroy() {
                this._mipmaps = [];
                return _SimpleTexture.prototype.destroy.call(this);
              };

              _proto.description = function description() {
                var url = this._mipmaps[0] ? this._mipmaps[0].url : '';
                return "<cc.Texture2D | Name = " + url + " | Dimension = " + this.width + " x " + this.height + ">";
              };

              _proto.releaseTexture = function releaseTexture() {
                this.destroy();
              };

              _proto._serialize = function _serialize(ctxForExporting) {

                return null;
              };

              _proto._deserialize = function _deserialize(serializedData, handle) {
                var data = serializedData;

                _SimpleTexture.prototype._deserialize.call(this, data.base, handle);

                this._mipmaps = new Array(data.mipmaps.length);

                for (var i = 0; i < data.mipmaps.length; ++i) {
                  this._mipmaps[i] = new ImageAsset();

                  if (!data.mipmaps[i]) {
                    continue;
                  }

                  var mipmapUUID = data.mipmaps[i];
                  handle.result.push(this._mipmaps, "" + i, mipmapUUID, js._getClassId(ImageAsset));
                  this._mipmaps[i]._texture = this;
                }
              };

              _proto._getGfxTextureCreateInfo = function _getGfxTextureCreateInfo(presumed) {
                var texInfo = new TextureInfo(TextureType.TEX2D);
                texInfo.width = this._width;
                texInfo.height = this._height;
                return Object.assign(texInfo, presumed);
              };

              _proto._checkTextureLoaded = function _checkTextureLoaded() {
                var ready = true;

                for (var i = 0; i < this._mipmaps.length; ++i) {
                  var image = this._mipmaps[i];

                  if (!image.loaded) {
                    ready = false;
                    break;
                  }
                }

                if (ready) {
                  _SimpleTexture.prototype._textureReady.call(this);
                }
              };

              _proto.initDefault = function initDefault(uuid) {
                _SimpleTexture.prototype.initDefault.call(this, uuid);

                var imageAsset = new ImageAsset();
                imageAsset.initDefault();
                this.image = imageAsset;
              };

              _proto.validate = function validate() {
                return this.mipmaps && this.mipmaps.length !== 0;
              };

              _createClass(Texture2D, [{
                key: "mipmaps",
                get: function get() {
                  return this._mipmaps;
                },
                set: function set(value) {
                  var _this2 = this;

                  this._mipmaps = value;

                  this._setMipmapLevel(this._mipmaps.length);

                  if (this._mipmaps.length > 0) {
                    var imageAsset = this._mipmaps[0];
                    this.reset({
                      width: imageAsset.width,
                      height: imageAsset.height,
                      format: imageAsset.format,
                      mipmapLevel: this._mipmaps.length
                    });

                    this._mipmaps.forEach(function (mipmap, level) {
                      _this2._assignImage(mipmap, level);
                    });
                  } else {
                    this.reset({
                      width: 0,
                      height: 0,
                      mipmapLevel: this._mipmaps.length
                    });
                  }
                }
              }, {
                key: "image",
                get: function get() {
                  return this._mipmaps.length === 0 ? null : this._mipmaps[0];
                },
                set: function set(value) {
                  this.mipmaps = value ? [value] : [];
                }
              }]);

              return Texture2D;
            }(SimpleTexture), _temp$6), (_descriptor$4 = _applyDecoratedDescriptor(_class2$6.prototype, "_mipmaps", [_dec2$3], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            })), _class2$6)) || _class$7));
            legacyCC.Texture2D = Texture2D;

            var _dec$8, _class$8, _class2$7, _descriptor$5, _class3$4, _temp$7;
            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 TextureCube = exports('TextureCube', (_dec$8 = ccclass('cc.TextureCube'), _dec$8(_class$8 = (_class2$7 = (_temp$7 = _class3$4 = function (_SimpleTexture) {
              _inheritsLoose(TextureCube, _SimpleTexture);

              function TextureCube() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _SimpleTexture.call.apply(_SimpleTexture, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "_mipmaps", _descriptor$5, _assertThisInitialized(_this));

                return _this;
              }

              TextureCube.fromTexture2DArray = function fromTexture2DArray(textures, out) {
                var mipmaps = [];
                var nMipmaps = textures.length / 6;

                for (var i = 0; i < nMipmaps; i++) {
                  var x = i * 6;
                  mipmaps.push({
                    front: textures[x + FaceIndex.front].image,
                    back: textures[x + FaceIndex.back].image,
                    left: textures[x + FaceIndex.left].image,
                    right: textures[x + FaceIndex.right].image,
                    top: textures[x + FaceIndex.top].image,
                    bottom: textures[x + FaceIndex.bottom].image
                  });
                }

                out = out || new TextureCube();
                out.mipmaps = mipmaps;
                return out;
              };

              var _proto = TextureCube.prototype;

              _proto.onLoaded = function onLoaded() {
                this.mipmaps = this._mipmaps;
                this.loaded = true;
                this.emit('load');
              };

              _proto.reset = function reset(info) {
                this._width = info.width;
                this._height = info.height;

                this._setGFXFormat(info.format);

                this._setMipmapLevel(info.mipmapLevel || 1);

                this._tryReset();
              };

              _proto.updateMipmaps = function updateMipmaps(firstLevel, count) {
                var _this2 = this;

                if (firstLevel === void 0) {
                  firstLevel = 0;
                }

                if (firstLevel >= this._mipmaps.length) {
                  return;
                }

                var nUpdate = Math.min(count === undefined ? this._mipmaps.length : count, this._mipmaps.length - firstLevel);

                var _loop = function _loop(i) {
                  var level = firstLevel + i;

                  _forEachFace(_this2._mipmaps[level], function (face, faceIndex) {
                    _this2._assignImage(face, level, faceIndex);
                  });
                };

                for (var i = 0; i < nUpdate; ++i) {
                  _loop(i);
                }
              };

              _proto.destroy = function destroy() {
                this._mipmaps = [];
                return _SimpleTexture.prototype.destroy.call(this);
              };

              _proto.releaseTexture = function releaseTexture() {
                this.mipmaps = [];
              };

              _proto._serialize = function _serialize(ctxForExporting) {

                return null;
              };

              _proto._deserialize = function _deserialize(serializedData, handle) {
                var data = serializedData;

                _SimpleTexture.prototype._deserialize.call(this, data.base, handle);

                this._mipmaps = new Array(data.mipmaps.length);

                for (var i = 0; i < data.mipmaps.length; ++i) {
                  this._mipmaps[i] = {
                    front: new ImageAsset(),
                    back: new ImageAsset(),
                    left: new ImageAsset(),
                    right: new ImageAsset(),
                    top: new ImageAsset(),
                    bottom: new ImageAsset()
                  };
                  var mipmap = data.mipmaps[i];

                  var imageAssetClassId = js._getClassId(ImageAsset);

                  handle.result.push(this._mipmaps[i], "front", mipmap.front, imageAssetClassId);
                  handle.result.push(this._mipmaps[i], "back", mipmap.back, imageAssetClassId);
                  handle.result.push(this._mipmaps[i], "left", mipmap.left, imageAssetClassId);
                  handle.result.push(this._mipmaps[i], "right", mipmap.right, imageAssetClassId);
                  handle.result.push(this._mipmaps[i], "top", mipmap.top, imageAssetClassId);
                  handle.result.push(this._mipmaps[i], "bottom", mipmap.bottom, imageAssetClassId);
                }
              };

              _proto._getGfxTextureCreateInfo = function _getGfxTextureCreateInfo(presumed) {
                var texInfo = new TextureInfo(TextureType.CUBE);
                texInfo.width = this._width;
                texInfo.height = this._height;
                texInfo.layerCount = 6;
                Object.assign(texInfo, presumed);
                return texInfo;
              };

              _proto.initDefault = function initDefault(uuid) {
                _SimpleTexture.prototype.initDefault.call(this, uuid);

                var imageAsset = new ImageAsset();
                imageAsset.initDefault();
                this.mipmaps = [{
                  front: imageAsset,
                  back: imageAsset,
                  top: imageAsset,
                  bottom: imageAsset,
                  left: imageAsset,
                  right: imageAsset
                }];
              };

              _proto.validate = function validate() {
                return this._mipmaps.length !== 0 && !this._mipmaps.find(function (x) {
                  return !(x.top && x.bottom && x.front && x.back && x.left && x.right);
                });
              };

              _createClass(TextureCube, [{
                key: "mipmaps",
                get: function get() {
                  return this._mipmaps;
                },
                set: function set(value) {
                  var _this3 = this;

                  this._mipmaps = value;

                  this._setMipmapLevel(this._mipmaps.length);

                  if (this._mipmaps.length > 0) {
                    var imageAsset = this._mipmaps[0].front;
                    this.reset({
                      width: imageAsset.width,
                      height: imageAsset.height,
                      format: imageAsset.format,
                      mipmapLevel: this._mipmaps.length
                    });

                    this._mipmaps.forEach(function (mipmap, level) {
                      _forEachFace(mipmap, function (face, faceIndex) {
                        _this3._assignImage(face, level, faceIndex);
                      });
                    });
                  } else {
                    this.reset({
                      width: 0,
                      height: 0,
                      mipmapLevel: this._mipmaps.length
                    });
                  }
                }
              }, {
                key: "image",
                get: function get() {
                  return this._mipmaps.length === 0 ? null : this._mipmaps[0];
                },
                set: function set(value) {
                  this.mipmaps = value ? [value] : [];
                }
              }]);

              return TextureCube;
            }(SimpleTexture), _class3$4.FaceIndex = FaceIndex, _temp$7), (_descriptor$5 = _applyDecoratedDescriptor(_class2$7.prototype, "_mipmaps", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            })), _class2$7)) || _class$8));
            legacyCC.TextureCube = TextureCube;

            function _forEachFace(mipmap, callback) {
              callback(mipmap.front, FaceIndex.front);
              callback(mipmap.back, FaceIndex.back);
              callback(mipmap.left, FaceIndex.left);
              callback(mipmap.right, FaceIndex.right);
              callback(mipmap.top, FaceIndex.top);
              callback(mipmap.bottom, FaceIndex.bottom);
            }

            var effects = exports('effects', [{
              "name": "billboard",
              "techniques": [{
                "name": "add",
                "passes": [{
                  "rasterizerState": {
                    "cullMode": 0
                  },
                  "blendState": {
                    "targets": [{
                      "blend": true,
                      "blendSrc": 2,
                      "blendDst": 1,
                      "blendSrcAlpha": 2,
                      "blendDstAlpha": 1
                    }]
                  },
                  "program": "billboard|vert:vs_main|tinted-fs:add",
                  "depthStencilState": {
                    "depthTest": true,
                    "depthWrite": false
                  },
                  "properties": {
                    "mainTexture": {
                      "value": "grey",
                      "type": 28
                    },
                    "mainTiling_Offset": {
                      "value": [1, 1, 0, 0],
                      "type": 16
                    },
                    "tintColor": {
                      "value": [0.5, 0.5, 0.5, 0.5],
                      "type": 16
                    }
                  }
                }]
              }],
              "shaders": [{
                "name": "billboard|vert:vs_main|tinted-fs:add",
                "hash": 121727045,
                "builtins": {
                  "statistics": {
                    "CC_EFFECT_USED_VERTEX_UNIFORM_VECTORS": 50,
                    "CC_EFFECT_USED_FRAGMENT_UNIFORM_VECTORS": 38
                  },
                  "globals": {
                    "blocks": [{
                      "name": "CCGlobal",
                      "defines": []
                    }, {
                      "name": "CCCamera",
                      "defines": []
                    }],
                    "samplerTextures": []
                  },
                  "locals": {
                    "blocks": [{
                      "name": "CCLocal",
                      "defines": []
                    }],
                    "samplerTextures": []
                  }
                },
                "defines": [{
                  "name": "CC_USE_HDR",
                  "type": "boolean"
                }],
                "blocks": [{
                  "name": "Constants",
                  "defines": [],
                  "binding": 0,
                  "stageFlags": 1,
                  "members": [{
                    "name": "mainTiling_Offset",
                    "type": 16,
                    "count": 1
                  }, {
                    "name": "frameTile_velLenScale",
                    "type": 16,
                    "count": 1
                  }, {
                    "name": "scale",
                    "type": 16,
                    "count": 1
                  }]
                }, {
                  "name": "builtin",
                  "defines": [],
                  "binding": 1,
                  "stageFlags": 1,
                  "members": [{
                    "name": "cc_size_rotation",
                    "type": 16,
                    "count": 1
                  }]
                }, {
                  "name": "FragConstants",
                  "defines": [],
                  "binding": 2,
                  "stageFlags": 16,
                  "members": [{
                    "name": "tintColor",
                    "type": 16,
                    "count": 1
                  }]
                }],
                "samplerTextures": [{
                  "name": "mainTexture",
                  "type": 28,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 16,
                  "binding": 3
                }],
                "attributes": [{
                  "name": "a_position",
                  "type": 15,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 0
                }, {
                  "name": "a_texCoord",
                  "type": 14,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 21,
                  "location": 1
                }, {
                  "name": "a_color",
                  "type": 16,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 44,
                  "location": 2
                }]
              }]
            }, {
              "name": "clear-stencil",
              "techniques": [{
                "passes": [{
                  "blendState": {
                    "targets": [{
                      "blend": true
                    }]
                  },
                  "rasterizerState": {
                    "cullMode": 0
                  },
                  "program": "clear-stencil|sprite-vs:vert|sprite-fs:frag",
                  "depthStencilState": {
                    "depthTest": false,
                    "depthWrite": false
                  }
                }]
              }],
              "shaders": [{
                "name": "clear-stencil|sprite-vs:vert|sprite-fs:frag",
                "hash": 3507038093,
                "builtins": {
                  "statistics": {
                    "CC_EFFECT_USED_VERTEX_UNIFORM_VECTORS": 0,
                    "CC_EFFECT_USED_FRAGMENT_UNIFORM_VECTORS": 0
                  },
                  "globals": {
                    "blocks": [],
                    "samplerTextures": []
                  },
                  "locals": {
                    "blocks": [],
                    "samplerTextures": []
                  }
                },
                "defines": [],
                "blocks": [],
                "samplerTextures": [],
                "attributes": [{
                  "name": "a_position",
                  "type": 15,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 0
                }]
              }]
            }, {
              "name": "graphics",
              "techniques": [{
                "passes": [{
                  "blendState": {
                    "targets": [{
                      "blend": true,
                      "blendSrc": 1,
                      "blendDst": 4,
                      "blendSrcAlpha": 1,
                      "blendDstAlpha": 4
                    }]
                  },
                  "rasterizerState": {
                    "cullMode": 0
                  },
                  "program": "graphics|vs:vert|fs:frag",
                  "depthStencilState": {
                    "depthTest": false,
                    "depthWrite": false
                  }
                }]
              }],
              "shaders": [{
                "name": "graphics|vs:vert|fs:frag",
                "hash": 3113634185,
                "builtins": {
                  "statistics": {
                    "CC_EFFECT_USED_VERTEX_UNIFORM_VECTORS": 46,
                    "CC_EFFECT_USED_FRAGMENT_UNIFORM_VECTORS": 0
                  },
                  "globals": {
                    "blocks": [{
                      "name": "CCGlobal",
                      "defines": []
                    }, {
                      "name": "CCCamera",
                      "defines": []
                    }],
                    "samplerTextures": []
                  },
                  "locals": {
                    "blocks": [{
                      "name": "CCLocal",
                      "defines": []
                    }],
                    "samplerTextures": []
                  }
                },
                "defines": [],
                "blocks": [],
                "samplerTextures": [],
                "attributes": [{
                  "name": "a_position",
                  "type": 15,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 0
                }, {
                  "name": "a_color",
                  "type": 16,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 44,
                  "location": 1
                }, {
                  "name": "a_dist",
                  "type": 13,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 11,
                  "location": 2
                }]
              }]
            }, {
              "name": "particle-gpu",
              "techniques": [{
                "name": "add",
                "passes": [{
                  "rasterizerState": {
                    "cullMode": 0
                  },
                  "blendState": {
                    "targets": [{
                      "blend": true,
                      "blendSrc": 2,
                      "blendDst": 1,
                      "blendSrcAlpha": 2,
                      "blendDstAlpha": 1
                    }]
                  },
                  "program": "particle-gpu|particle-vs-gpu:gpvs_main|tinted-fs:add",
                  "depthStencilState": {
                    "depthTest": true,
                    "depthWrite": false
                  },
                  "properties": {
                    "mainTexture": {
                      "value": "grey",
                      "type": 28
                    },
                    "mainTiling_Offset": {
                      "value": [1, 1, 0, 0],
                      "type": 16
                    },
                    "tintColor": {
                      "value": [0.5, 0.5, 0.5, 0.5],
                      "type": 16
                    }
                  }
                }]
              }],
              "shaders": [{
                "name": "particle-gpu|particle-vs-gpu:gpvs_main|tinted-fs:add",
                "hash": 3356319967,
                "builtins": {
                  "statistics": {
                    "CC_EFFECT_USED_VERTEX_UNIFORM_VECTORS": 60,
                    "CC_EFFECT_USED_FRAGMENT_UNIFORM_VECTORS": 38
                  },
                  "globals": {
                    "blocks": [{
                      "name": "CCGlobal",
                      "defines": []
                    }, {
                      "name": "CCCamera",
                      "defines": []
                    }],
                    "samplerTextures": []
                  },
                  "locals": {
                    "blocks": [{
                      "name": "CCLocal",
                      "defines": []
                    }],
                    "samplerTextures": []
                  }
                },
                "defines": [{
                  "name": "CC_RENDER_MODE",
                  "type": "number",
                  "range": [0, 4]
                }, {
                  "name": "COLOR_OVER_TIME_MODULE_ENABLE",
                  "type": "boolean"
                }, {
                  "name": "ROTATION_OVER_TIME_MODULE_ENABLE",
                  "type": "boolean"
                }, {
                  "name": "SIZE_OVER_TIME_MODULE_ENABLE",
                  "type": "boolean"
                }, {
                  "name": "FORCE_OVER_TIME_MODULE_ENABLE",
                  "type": "boolean"
                }, {
                  "name": "VELOCITY_OVER_TIME_MODULE_ENABLE",
                  "type": "boolean"
                }, {
                  "name": "TEXTURE_ANIMATION_MODULE_ENABLE",
                  "type": "boolean"
                }, {
                  "name": "CC_USE_WORLD_SPACE",
                  "type": "boolean"
                }, {
                  "name": "CC_USE_HDR",
                  "type": "boolean"
                }],
                "blocks": [{
                  "name": "Constants",
                  "defines": [],
                  "binding": 0,
                  "stageFlags": 1,
                  "members": [{
                    "name": "mainTiling_Offset",
                    "type": 16,
                    "count": 1
                  }, {
                    "name": "frameTile_velLenScale",
                    "type": 16,
                    "count": 1
                  }, {
                    "name": "scale",
                    "type": 16,
                    "count": 1
                  }]
                }, {
                  "name": "SampleConstants",
                  "defines": [],
                  "binding": 1,
                  "stageFlags": 1,
                  "members": [{
                    "name": "u_sampleInfo",
                    "type": 16,
                    "count": 1
                  }]
                }, {
                  "name": "TickConstants",
                  "defines": [],
                  "binding": 2,
                  "stageFlags": 1,
                  "members": [{
                    "name": "u_worldRot",
                    "type": 16,
                    "count": 1
                  }, {
                    "name": "u_timeDelta",
                    "type": 16,
                    "count": 1
                  }]
                }, {
                  "name": "ColorConstant",
                  "defines": ["COLOR_OVER_TIME_MODULE_ENABLE"],
                  "binding": 3,
                  "stageFlags": 1,
                  "members": [{
                    "name": "u_color_mode",
                    "type": 5,
                    "count": 1
                  }]
                }, {
                  "name": "RotationConstant",
                  "defines": ["ROTATION_OVER_TIME_MODULE_ENABLE"],
                  "binding": 4,
                  "stageFlags": 1,
                  "members": [{
                    "name": "u_rotation_mode",
                    "type": 5,
                    "count": 1
                  }]
                }, {
                  "name": "SizeConstant",
                  "defines": ["SIZE_OVER_TIME_MODULE_ENABLE"],
                  "binding": 5,
                  "stageFlags": 1,
                  "members": [{
                    "name": "u_size_mode",
                    "type": 5,
                    "count": 1
                  }]
                }, {
                  "name": "ForceConstant",
                  "defines": ["FORCE_OVER_TIME_MODULE_ENABLE"],
                  "binding": 6,
                  "stageFlags": 1,
                  "members": [{
                    "name": "u_force_mode",
                    "type": 5,
                    "count": 1
                  }, {
                    "name": "u_force_space",
                    "type": 5,
                    "count": 1
                  }]
                }, {
                  "name": "VelocityConstant",
                  "defines": ["VELOCITY_OVER_TIME_MODULE_ENABLE"],
                  "binding": 7,
                  "stageFlags": 1,
                  "members": [{
                    "name": "u_velocity_mode",
                    "type": 5,
                    "count": 1
                  }, {
                    "name": "u_velocity_space",
                    "type": 5,
                    "count": 1
                  }]
                }, {
                  "name": "AnimationConstant",
                  "defines": ["TEXTURE_ANIMATION_MODULE_ENABLE"],
                  "binding": 8,
                  "stageFlags": 1,
                  "members": [{
                    "name": "u_anim_info",
                    "type": 16,
                    "count": 1
                  }]
                }, {
                  "name": "FragConstants",
                  "defines": [],
                  "binding": 9,
                  "stageFlags": 16,
                  "members": [{
                    "name": "tintColor",
                    "type": 16,
                    "count": 1
                  }]
                }],
                "samplerTextures": [{
                  "name": "color_over_time_tex0",
                  "type": 28,
                  "count": 1,
                  "defines": ["COLOR_OVER_TIME_MODULE_ENABLE"],
                  "stageFlags": 1,
                  "binding": 10
                }, {
                  "name": "rotation_over_time_tex0",
                  "type": 28,
                  "count": 1,
                  "defines": ["ROTATION_OVER_TIME_MODULE_ENABLE"],
                  "stageFlags": 1,
                  "binding": 11
                }, {
                  "name": "size_over_time_tex0",
                  "type": 28,
                  "count": 1,
                  "defines": ["SIZE_OVER_TIME_MODULE_ENABLE"],
                  "stageFlags": 1,
                  "binding": 12
                }, {
                  "name": "force_over_time_tex0",
                  "type": 28,
                  "count": 1,
                  "defines": ["FORCE_OVER_TIME_MODULE_ENABLE"],
                  "stageFlags": 1,
                  "binding": 13
                }, {
                  "name": "velocity_over_time_tex0",
                  "type": 28,
                  "count": 1,
                  "defines": ["VELOCITY_OVER_TIME_MODULE_ENABLE"],
                  "stageFlags": 1,
                  "binding": 14
                }, {
                  "name": "texture_animation_tex0",
                  "type": 28,
                  "count": 1,
                  "defines": ["TEXTURE_ANIMATION_MODULE_ENABLE"],
                  "stageFlags": 1,
                  "binding": 15
                }, {
                  "name": "mainTexture",
                  "type": 28,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 16,
                  "binding": 16
                }],
                "attributes": [{
                  "name": "a_position_starttime",
                  "type": 16,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 44,
                  "location": 0
                }, {
                  "name": "a_size_uv",
                  "type": 16,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 44,
                  "location": 1
                }, {
                  "name": "a_rotation_uv",
                  "type": 16,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 44,
                  "location": 2
                }, {
                  "name": "a_color",
                  "type": 16,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 44,
                  "location": 3
                }, {
                  "name": "a_dir_life",
                  "type": 16,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 44,
                  "location": 4
                }, {
                  "name": "a_rndSeed",
                  "type": 13,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 11,
                  "location": 5
                }, {
                  "name": "a_texCoord",
                  "type": 15,
                  "count": 1,
                  "defines": ["CC_RENDER_MODE"],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 6
                }, {
                  "name": "a_texCoord3",
                  "type": 15,
                  "count": 1,
                  "defines": ["CC_RENDER_MODE"],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 7
                }, {
                  "name": "a_normal",
                  "type": 15,
                  "count": 1,
                  "defines": ["CC_RENDER_MODE"],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 8
                }, {
                  "name": "a_color1",
                  "type": 16,
                  "count": 1,
                  "defines": ["CC_RENDER_MODE"],
                  "stageFlags": 1,
                  "format": 44,
                  "location": 9
                }]
              }]
            }, {
              "name": "particle-trail",
              "techniques": [{
                "name": "add",
                "passes": [{
                  "rasterizerState": {
                    "cullMode": 0
                  },
                  "blendState": {
                    "targets": [{
                      "blend": true,
                      "blendSrc": 2,
                      "blendDst": 1,
                      "blendSrcAlpha": 2,
                      "blendDstAlpha": 1
                    }]
                  },
                  "program": "particle-trail|particle-trail:vs_main|tinted-fs:add",
                  "depthStencilState": {
                    "depthTest": true,
                    "depthWrite": false
                  },
                  "properties": {
                    "mainTexture": {
                      "value": "grey",
                      "type": 28
                    },
                    "mainTiling_Offset": {
                      "value": [1, 1, 0, 0],
                      "type": 16
                    },
                    "frameTile_velLenScale": {
                      "value": [1, 1, 0, 0],
                      "type": 16
                    },
                    "tintColor": {
                      "value": [0.5, 0.5, 0.5, 0.5],
                      "type": 16
                    }
                  }
                }]
              }],
              "shaders": [{
                "name": "particle-trail|particle-trail:vs_main|tinted-fs:add",
                "hash": 2637621064,
                "builtins": {
                  "statistics": {
                    "CC_EFFECT_USED_VERTEX_UNIFORM_VECTORS": 49,
                    "CC_EFFECT_USED_FRAGMENT_UNIFORM_VECTORS": 38
                  },
                  "globals": {
                    "blocks": [{
                      "name": "CCGlobal",
                      "defines": []
                    }, {
                      "name": "CCCamera",
                      "defines": []
                    }],
                    "samplerTextures": []
                  },
                  "locals": {
                    "blocks": [{
                      "name": "CCLocal",
                      "defines": []
                    }],
                    "samplerTextures": []
                  }
                },
                "defines": [{
                  "name": "CC_RENDER_MODE",
                  "type": "number",
                  "range": [0, 4]
                }, {
                  "name": "CC_DRAW_WIRE_FRAME",
                  "type": "boolean"
                }, {
                  "name": "CC_USE_WORLD_SPACE",
                  "type": "boolean"
                }, {
                  "name": "CC_USE_HDR",
                  "type": "boolean"
                }],
                "blocks": [{
                  "name": "Constants",
                  "defines": [],
                  "binding": 0,
                  "stageFlags": 1,
                  "members": [{
                    "name": "mainTiling_Offset",
                    "type": 16,
                    "count": 1
                  }, {
                    "name": "frameTile_velLenScale",
                    "type": 16,
                    "count": 1
                  }, {
                    "name": "scale",
                    "type": 16,
                    "count": 1
                  }]
                }, {
                  "name": "FragConstants",
                  "defines": [],
                  "binding": 1,
                  "stageFlags": 16,
                  "members": [{
                    "name": "tintColor",
                    "type": 16,
                    "count": 1
                  }]
                }],
                "samplerTextures": [{
                  "name": "mainTexture",
                  "type": 28,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 16,
                  "binding": 2
                }],
                "attributes": [{
                  "name": "a_position",
                  "type": 15,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 0
                }, {
                  "name": "a_texCoord",
                  "type": 16,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 44,
                  "location": 1
                }, {
                  "name": "a_texCoord1",
                  "type": 15,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 2
                }, {
                  "name": "a_texCoord2",
                  "type": 15,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 3
                }, {
                  "name": "a_color",
                  "type": 16,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 44,
                  "location": 4
                }]
              }]
            }, {
              "name": "particle",
              "techniques": [{
                "name": "add",
                "passes": [{
                  "rasterizerState": {
                    "cullMode": 0
                  },
                  "blendState": {
                    "targets": [{
                      "blend": true,
                      "blendSrc": 2,
                      "blendDst": 1,
                      "blendSrcAlpha": 2,
                      "blendDstAlpha": 1
                    }]
                  },
                  "program": "particle|particle-vs-legacy:lpvs_main|tinted-fs:add",
                  "depthStencilState": {
                    "depthTest": true,
                    "depthWrite": false
                  },
                  "properties": {
                    "mainTexture": {
                      "value": "grey",
                      "type": 28
                    },
                    "mainTiling_Offset": {
                      "value": [1, 1, 0, 0],
                      "type": 16
                    },
                    "tintColor": {
                      "value": [0.5, 0.5, 0.5, 0.5],
                      "type": 16
                    }
                  }
                }]
              }],
              "shaders": [{
                "name": "particle|particle-vs-legacy:lpvs_main|tinted-fs:add",
                "hash": 1755172438,
                "builtins": {
                  "statistics": {
                    "CC_EFFECT_USED_VERTEX_UNIFORM_VECTORS": 49,
                    "CC_EFFECT_USED_FRAGMENT_UNIFORM_VECTORS": 38
                  },
                  "globals": {
                    "blocks": [{
                      "name": "CCGlobal",
                      "defines": []
                    }, {
                      "name": "CCCamera",
                      "defines": []
                    }],
                    "samplerTextures": []
                  },
                  "locals": {
                    "blocks": [{
                      "name": "CCLocal",
                      "defines": []
                    }],
                    "samplerTextures": []
                  }
                },
                "defines": [{
                  "name": "CC_RENDER_MODE",
                  "type": "number",
                  "range": [0, 4]
                }, {
                  "name": "CC_USE_WORLD_SPACE",
                  "type": "boolean"
                }, {
                  "name": "CC_USE_HDR",
                  "type": "boolean"
                }],
                "blocks": [{
                  "name": "Constants",
                  "defines": [],
                  "binding": 0,
                  "stageFlags": 1,
                  "members": [{
                    "name": "mainTiling_Offset",
                    "type": 16,
                    "count": 1
                  }, {
                    "name": "frameTile_velLenScale",
                    "type": 16,
                    "count": 1
                  }, {
                    "name": "scale",
                    "type": 16,
                    "count": 1
                  }]
                }, {
                  "name": "FragConstants",
                  "defines": [],
                  "binding": 1,
                  "stageFlags": 16,
                  "members": [{
                    "name": "tintColor",
                    "type": 16,
                    "count": 1
                  }]
                }],
                "samplerTextures": [{
                  "name": "mainTexture",
                  "type": 28,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 16,
                  "binding": 2
                }],
                "attributes": [{
                  "name": "a_position",
                  "type": 15,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 0
                }, {
                  "name": "a_texCoord",
                  "type": 15,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 1
                }, {
                  "name": "a_texCoord1",
                  "type": 15,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 2
                }, {
                  "name": "a_texCoord2",
                  "type": 15,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 3
                }, {
                  "name": "a_color",
                  "type": 16,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 44,
                  "location": 4
                }, {
                  "name": "a_color1",
                  "type": 15,
                  "count": 1,
                  "defines": ["CC_RENDER_MODE"],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 8
                }, {
                  "name": "a_texCoord3",
                  "type": 15,
                  "count": 1,
                  "defines": ["CC_RENDER_MODE"],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 6
                }, {
                  "name": "a_normal",
                  "type": 15,
                  "count": 1,
                  "defines": ["CC_RENDER_MODE"],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 7
                }]
              }]
            }, {
              "name": "spine",
              "techniques": [{
                "passes": [{
                  "blendState": {
                    "targets": [{
                      "blend": true,
                      "blendSrc": 2,
                      "blendDst": 4,
                      "blendDstAlpha": 4
                    }]
                  },
                  "rasterizerState": {
                    "cullMode": 0
                  },
                  "program": "spine|sprite-vs:vert|sprite-fs:frag",
                  "depthStencilState": {
                    "depthTest": false,
                    "depthWrite": false
                  },
                  "properties": {
                    "alphaThreshold": {
                      "value": [0.5],
                      "type": 13
                    }
                  }
                }]
              }],
              "shaders": [{
                "name": "spine|sprite-vs:vert|sprite-fs:frag",
                "hash": 1867464226,
                "builtins": {
                  "statistics": {
                    "CC_EFFECT_USED_VERTEX_UNIFORM_VECTORS": 46,
                    "CC_EFFECT_USED_FRAGMENT_UNIFORM_VECTORS": 1
                  },
                  "globals": {
                    "blocks": [{
                      "name": "CCGlobal",
                      "defines": []
                    }, {
                      "name": "CCCamera",
                      "defines": []
                    }],
                    "samplerTextures": []
                  },
                  "locals": {
                    "blocks": [{
                      "name": "CCLocal",
                      "defines": ["USE_LOCAL"]
                    }],
                    "samplerTextures": [{
                      "name": "cc_spriteTexture",
                      "defines": []
                    }]
                  }
                },
                "defines": [{
                  "name": "USE_LOCAL",
                  "type": "boolean"
                }, {
                  "name": "TWO_COLORED",
                  "type": "boolean"
                }, {
                  "name": "USE_ALPHA_TEST",
                  "type": "boolean"
                }],
                "blocks": [{
                  "name": "ALPHA_TEST_DATA",
                  "defines": ["USE_ALPHA_TEST"],
                  "binding": 0,
                  "stageFlags": 16,
                  "members": [{
                    "name": "alphaThreshold",
                    "type": 13,
                    "count": 1
                  }]
                }],
                "samplerTextures": [],
                "attributes": [{
                  "name": "a_position",
                  "type": 15,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 0
                }, {
                  "name": "a_texCoord",
                  "type": 14,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 21,
                  "location": 1
                }, {
                  "name": "a_color",
                  "type": 16,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 44,
                  "location": 2
                }, {
                  "name": "a_color2",
                  "type": 16,
                  "count": 1,
                  "defines": ["TWO_COLORED"],
                  "stageFlags": 1,
                  "format": 44,
                  "location": 3
                }]
              }]
            }, {
              "name": "sprite",
              "techniques": [{
                "passes": [{
                  "blendState": {
                    "targets": [{
                      "blend": true,
                      "blendSrc": 2,
                      "blendDst": 4,
                      "blendDstAlpha": 4
                    }]
                  },
                  "rasterizerState": {
                    "cullMode": 0
                  },
                  "program": "sprite|sprite-vs:vert|sprite-fs:frag",
                  "depthStencilState": {
                    "depthTest": false,
                    "depthWrite": false
                  },
                  "properties": {
                    "alphaThreshold": {
                      "value": [0.5],
                      "type": 13
                    }
                  }
                }]
              }],
              "shaders": [{
                "name": "sprite|sprite-vs:vert|sprite-fs:frag",
                "hash": 1559944983,
                "builtins": {
                  "statistics": {
                    "CC_EFFECT_USED_VERTEX_UNIFORM_VECTORS": 46,
                    "CC_EFFECT_USED_FRAGMENT_UNIFORM_VECTORS": 1
                  },
                  "globals": {
                    "blocks": [{
                      "name": "CCGlobal",
                      "defines": []
                    }, {
                      "name": "CCCamera",
                      "defines": []
                    }],
                    "samplerTextures": []
                  },
                  "locals": {
                    "blocks": [{
                      "name": "CCLocal",
                      "defines": ["USE_LOCAL"]
                    }],
                    "samplerTextures": [{
                      "name": "cc_spriteTexture",
                      "defines": ["USE_TEXTURE"]
                    }]
                  }
                },
                "defines": [{
                  "name": "USE_LOCAL",
                  "type": "boolean"
                }, {
                  "name": "SAMPLE_FROM_RT",
                  "type": "boolean"
                }, {
                  "name": "USE_PIXEL_ALIGNMENT",
                  "type": "boolean"
                }, {
                  "name": "CC_USE_EMBEDDED_ALPHA",
                  "type": "boolean"
                }, {
                  "name": "USE_ALPHA_TEST",
                  "type": "boolean"
                }, {
                  "name": "USE_TEXTURE",
                  "type": "boolean"
                }, {
                  "name": "IS_GRAY",
                  "type": "boolean"
                }],
                "blocks": [{
                  "name": "ALPHA_TEST_DATA",
                  "defines": ["USE_ALPHA_TEST"],
                  "binding": 0,
                  "stageFlags": 16,
                  "members": [{
                    "name": "alphaThreshold",
                    "type": 13,
                    "count": 1
                  }]
                }],
                "samplerTextures": [],
                "attributes": [{
                  "name": "a_position",
                  "type": 15,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 0
                }, {
                  "name": "a_texCoord",
                  "type": 14,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 21,
                  "location": 1
                }, {
                  "name": "a_color",
                  "type": 16,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 44,
                  "location": 2
                }]
              }]
            }, {
              "name": "standard",
              "techniques": [{
                "name": "opaque",
                "passes": [{
                  "program": "standard|standard-vs|standard-fs",
                  "properties": {
                    "tilingOffset": {
                      "value": [1, 1, 0, 0],
                      "type": 16
                    },
                    "mainColor": {
                      "value": [1, 1, 1, 1],
                      "type": 16,
                      "handleInfo": ["albedo", 0, 16]
                    },
                    "albedoScale": {
                      "value": [1, 1, 1],
                      "type": 15,
                      "handleInfo": ["albedoScaleAndCutoff", 0, 15]
                    },
                    "alphaThreshold": {
                      "value": [0.5],
                      "type": 13,
                      "handleInfo": ["albedoScaleAndCutoff", 3, 13]
                    },
                    "occlusion": {
                      "value": [1],
                      "type": 13,
                      "handleInfo": ["pbrParams", 0, 13]
                    },
                    "roughness": {
                      "value": [0.8],
                      "type": 13,
                      "handleInfo": ["pbrParams", 1, 13]
                    },
                    "metallic": {
                      "value": [0.6],
                      "type": 13,
                      "handleInfo": ["pbrParams", 2, 13]
                    },
                    "normalStrenth": {
                      "value": [1],
                      "type": 13,
                      "handleInfo": ["pbrParams", 3, 13]
                    },
                    "emissive": {
                      "value": [0, 0, 0, 1],
                      "type": 16
                    },
                    "emissiveScale": {
                      "value": [1, 1, 1],
                      "type": 15,
                      "handleInfo": ["emissiveScaleParam", 0, 15]
                    },
                    "mainTexture": {
                      "value": "grey",
                      "type": 28,
                      "handleInfo": ["albedoMap", 0, 28]
                    },
                    "normalMap": {
                      "value": "normal",
                      "type": 28
                    },
                    "pbrMap": {
                      "value": "grey",
                      "type": 28
                    },
                    "metallicRoughnessMap": {
                      "value": "grey",
                      "type": 28
                    },
                    "occlusionMap": {
                      "value": "white",
                      "type": 28
                    },
                    "emissiveMap": {
                      "value": "grey",
                      "type": 28
                    },
                    "albedo": {
                      "type": 16,
                      "value": [1, 1, 1, 1]
                    },
                    "albedoScaleAndCutoff": {
                      "type": 16,
                      "value": [1, 1, 1, 0.5]
                    },
                    "pbrParams": {
                      "type": 16,
                      "value": [1, 0.8, 0.6, 1]
                    },
                    "emissiveScaleParam": {
                      "type": 16,
                      "value": [1, 1, 1, 0]
                    },
                    "albedoMap": {
                      "type": 28,
                      "value": "grey"
                    }
                  }
                }, {
                  "phase": "deferred",
                  "propertyIndex": 0,
                  "blendState": {
                    "targets": [{
                      "blend": false
                    }, {
                      "blend": false
                    }, {
                      "blend": false
                    }, {
                      "blend": false
                    }]
                  },
                  "program": "standard|standard-vs|standard-fs",
                  "properties": {
                    "tilingOffset": {
                      "value": [1, 1, 0, 0],
                      "type": 16
                    },
                    "mainColor": {
                      "value": [1, 1, 1, 1],
                      "type": 16,
                      "handleInfo": ["albedo", 0, 16]
                    },
                    "albedoScale": {
                      "value": [1, 1, 1],
                      "type": 15,
                      "handleInfo": ["albedoScaleAndCutoff", 0, 15]
                    },
                    "alphaThreshold": {
                      "value": [0.5],
                      "type": 13,
                      "handleInfo": ["albedoScaleAndCutoff", 3, 13]
                    },
                    "occlusion": {
                      "value": [1],
                      "type": 13,
                      "handleInfo": ["pbrParams", 0, 13]
                    },
                    "roughness": {
                      "value": [0.8],
                      "type": 13,
                      "handleInfo": ["pbrParams", 1, 13]
                    },
                    "metallic": {
                      "value": [0.6],
                      "type": 13,
                      "handleInfo": ["pbrParams", 2, 13]
                    },
                    "normalStrenth": {
                      "value": [1],
                      "type": 13,
                      "handleInfo": ["pbrParams", 3, 13]
                    },
                    "emissive": {
                      "value": [0, 0, 0, 1],
                      "type": 16
                    },
                    "emissiveScale": {
                      "value": [1, 1, 1],
                      "type": 15,
                      "handleInfo": ["emissiveScaleParam", 0, 15]
                    },
                    "mainTexture": {
                      "value": "grey",
                      "type": 28,
                      "handleInfo": ["albedoMap", 0, 28]
                    },
                    "normalMap": {
                      "value": "normal",
                      "type": 28
                    },
                    "pbrMap": {
                      "value": "grey",
                      "type": 28
                    },
                    "metallicRoughnessMap": {
                      "value": "grey",
                      "type": 28
                    },
                    "occlusionMap": {
                      "value": "white",
                      "type": 28
                    },
                    "emissiveMap": {
                      "value": "grey",
                      "type": 28
                    },
                    "albedo": {
                      "type": 16,
                      "value": [1, 1, 1, 1]
                    },
                    "albedoScaleAndCutoff": {
                      "type": 16,
                      "value": [1, 1, 1, 0.5]
                    },
                    "pbrParams": {
                      "type": 16,
                      "value": [1, 0.8, 0.6, 1]
                    },
                    "emissiveScaleParam": {
                      "type": 16,
                      "value": [1, 1, 1, 0]
                    },
                    "albedoMap": {
                      "type": 28,
                      "value": "grey"
                    }
                  }
                }, {
                  "phase": "forward-add",
                  "propertyIndex": 0,
                  "embeddedMacros": {
                    "CC_FORWARD_ADD": true
                  },
                  "blendState": {
                    "targets": [{
                      "blend": true,
                      "blendSrc": 1,
                      "blendDst": 1,
                      "blendSrcAlpha": 0,
                      "blendDstAlpha": 1
                    }]
                  },
                  "program": "standard|standard-vs|standard-fs",
                  "depthStencilState": {
                    "depthFunc": 2,
                    "depthTest": true,
                    "depthWrite": false
                  },
                  "properties": {
                    "tilingOffset": {
                      "value": [1, 1, 0, 0],
                      "type": 16
                    },
                    "mainColor": {
                      "value": [1, 1, 1, 1],
                      "type": 16,
                      "handleInfo": ["albedo", 0, 16]
                    },
                    "albedoScale": {
                      "value": [1, 1, 1],
                      "type": 15,
                      "handleInfo": ["albedoScaleAndCutoff", 0, 15]
                    },
                    "alphaThreshold": {
                      "value": [0.5],
                      "type": 13,
                      "handleInfo": ["albedoScaleAndCutoff", 3, 13]
                    },
                    "occlusion": {
                      "value": [1],
                      "type": 13,
                      "handleInfo": ["pbrParams", 0, 13]
                    },
                    "roughness": {
                      "value": [0.8],
                      "type": 13,
                      "handleInfo": ["pbrParams", 1, 13]
                    },
                    "metallic": {
                      "value": [0.6],
                      "type": 13,
                      "handleInfo": ["pbrParams", 2, 13]
                    },
                    "normalStrenth": {
                      "value": [1],
                      "type": 13,
                      "handleInfo": ["pbrParams", 3, 13]
                    },
                    "emissive": {
                      "value": [0, 0, 0, 1],
                      "type": 16
                    },
                    "emissiveScale": {
                      "value": [1, 1, 1],
                      "type": 15,
                      "handleInfo": ["emissiveScaleParam", 0, 15]
                    },
                    "mainTexture": {
                      "value": "grey",
                      "type": 28,
                      "handleInfo": ["albedoMap", 0, 28]
                    },
                    "normalMap": {
                      "value": "normal",
                      "type": 28
                    },
                    "pbrMap": {
                      "value": "grey",
                      "type": 28
                    },
                    "metallicRoughnessMap": {
                      "value": "grey",
                      "type": 28
                    },
                    "occlusionMap": {
                      "value": "white",
                      "type": 28
                    },
                    "emissiveMap": {
                      "value": "grey",
                      "type": 28
                    },
                    "albedo": {
                      "type": 16,
                      "value": [1, 1, 1, 1]
                    },
                    "albedoScaleAndCutoff": {
                      "type": 16,
                      "value": [1, 1, 1, 0.5]
                    },
                    "pbrParams": {
                      "type": 16,
                      "value": [1, 0.8, 0.6, 1]
                    },
                    "emissiveScaleParam": {
                      "type": 16,
                      "value": [1, 1, 1, 0]
                    },
                    "albedoMap": {
                      "type": 28,
                      "value": "grey"
                    }
                  }
                }, {
                  "phase": "shadow-caster",
                  "propertyIndex": 0,
                  "rasterizerState": {
                    "cullMode": 1
                  },
                  "program": "standard|shadow-caster-vs:vert|shadow-caster-fs:frag",
                  "properties": {
                    "tilingOffset": {
                      "value": [1, 1, 0, 0],
                      "type": 16
                    },
                    "mainColor": {
                      "value": [1, 1, 1, 1],
                      "type": 16,
                      "handleInfo": ["albedo", 0, 16]
                    },
                    "albedoScale": {
                      "value": [1, 1, 1],
                      "type": 15,
                      "handleInfo": ["albedoScaleAndCutoff", 0, 15]
                    },
                    "alphaThreshold": {
                      "value": [0.5],
                      "type": 13,
                      "handleInfo": ["albedoScaleAndCutoff", 3, 13]
                    },
                    "occlusion": {
                      "value": [1],
                      "type": 13,
                      "handleInfo": ["pbrParams", 0, 13]
                    },
                    "roughness": {
                      "value": [0.8],
                      "type": 13,
                      "handleInfo": ["pbrParams", 1, 13]
                    },
                    "metallic": {
                      "value": [0.6],
                      "type": 13,
                      "handleInfo": ["pbrParams", 2, 13]
                    },
                    "normalStrenth": {
                      "value": [1],
                      "type": 13,
                      "handleInfo": ["pbrParams", 3, 13]
                    },
                    "emissive": {
                      "value": [0, 0, 0, 1],
                      "type": 16
                    },
                    "emissiveScale": {
                      "value": [1, 1, 1],
                      "type": 15,
                      "handleInfo": ["emissiveScaleParam", 0, 15]
                    },
                    "mainTexture": {
                      "value": "grey",
                      "type": 28,
                      "handleInfo": ["albedoMap", 0, 28]
                    },
                    "albedo": {
                      "type": 16,
                      "value": [1, 1, 1, 1]
                    },
                    "albedoScaleAndCutoff": {
                      "type": 16,
                      "value": [1, 1, 1, 0.5]
                    },
                    "pbrParams": {
                      "type": 16,
                      "value": [1, 0.8, 0.6, 1]
                    },
                    "emissiveScaleParam": {
                      "type": 16,
                      "value": [1, 1, 1, 0]
                    },
                    "albedoMap": {
                      "type": 28,
                      "value": "grey"
                    }
                  }
                }]
              }],
              "shaders": [{
                "name": "standard|standard-vs|standard-fs",
                "hash": 442396670,
                "builtins": {
                  "statistics": {
                    "CC_EFFECT_USED_VERTEX_UNIFORM_VECTORS": 216,
                    "CC_EFFECT_USED_FRAGMENT_UNIFORM_VECTORS": 59
                  },
                  "globals": {
                    "blocks": [{
                      "name": "CCGlobal",
                      "defines": []
                    }, {
                      "name": "CCCamera",
                      "defines": []
                    }, {
                      "name": "CCShadow",
                      "defines": []
                    }],
                    "samplerTextures": [{
                      "name": "cc_shadowMap",
                      "defines": ["CC_RECEIVE_SHADOW"]
                    }, {
                      "name": "cc_spotLightingMap",
                      "defines": ["CC_RECEIVE_SHADOW"]
                    }, {
                      "name": "cc_environment",
                      "defines": ["CC_USE_IBL"]
                    }]
                  },
                  "locals": {
                    "blocks": [{
                      "name": "CCMorph",
                      "defines": ["CC_USE_MORPH"]
                    }, {
                      "name": "CCSkinningTexture",
                      "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION"]
                    }, {
                      "name": "CCSkinningAnimation",
                      "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION"]
                    }, {
                      "name": "CCSkinning",
                      "defines": ["CC_USE_SKINNING", "!CC_USE_BAKED_ANIMATION"]
                    }, {
                      "name": "CCLocalBatched",
                      "defines": ["!USE_INSTANCING", "USE_BATCHING"]
                    }, {
                      "name": "CCLocal",
                      "defines": ["!USE_INSTANCING", "!USE_BATCHING"]
                    }, {
                      "name": "CCForwardLight",
                      "defines": ["CC_FORWARD_ADD"]
                    }],
                    "samplerTextures": [{
                      "name": "cc_PositionDisplacements",
                      "defines": ["CC_USE_MORPH", "CC_MORPH_TARGET_HAS_POSITION"]
                    }, {
                      "name": "cc_NormalDisplacements",
                      "defines": ["CC_USE_MORPH", "CC_MORPH_TARGET_HAS_NORMAL"]
                    }, {
                      "name": "cc_TangentDisplacements",
                      "defines": ["CC_USE_MORPH", "CC_MORPH_TARGET_HAS_TANGENT"]
                    }, {
                      "name": "cc_jointTexture",
                      "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION"]
                    }, {
                      "name": "cc_lightingMap",
                      "defines": ["USE_LIGHTMAP", "!USE_BATCHING", "!CC_FORWARD_ADD"]
                    }]
                  }
                },
                "defines": [{
                  "name": "CC_USE_MORPH",
                  "type": "boolean"
                }, {
                  "name": "CC_MORPH_TARGET_COUNT",
                  "type": "number",
                  "range": [2, 8]
                }, {
                  "name": "CC_MORPH_PRECOMPUTED",
                  "type": "boolean"
                }, {
                  "name": "CC_MORPH_TARGET_HAS_POSITION",
                  "type": "boolean"
                }, {
                  "name": "CC_MORPH_TARGET_HAS_NORMAL",
                  "type": "boolean"
                }, {
                  "name": "CC_MORPH_TARGET_HAS_TANGENT",
                  "type": "boolean"
                }, {
                  "name": "CC_USE_SKINNING",
                  "type": "boolean"
                }, {
                  "name": "CC_USE_BAKED_ANIMATION",
                  "type": "boolean"
                }, {
                  "name": "USE_INSTANCING",
                  "type": "boolean"
                }, {
                  "name": "USE_BATCHING",
                  "type": "boolean"
                }, {
                  "name": "USE_LIGHTMAP",
                  "type": "boolean"
                }, {
                  "name": "CC_USE_FOG",
                  "type": "number",
                  "range": [0, 4]
                }, {
                  "name": "CC_FORWARD_ADD",
                  "type": "boolean"
                }, {
                  "name": "CC_RECEIVE_SHADOW",
                  "type": "boolean"
                }, {
                  "name": "USE_VERTEX_COLOR",
                  "type": "boolean"
                }, {
                  "name": "USE_NORMAL_MAP",
                  "type": "boolean"
                }, {
                  "name": "HAS_SECOND_UV",
                  "type": "boolean"
                }, {
                  "name": "SAMPLE_FROM_RT",
                  "type": "boolean"
                }, {
                  "name": "CC_USE_IBL",
                  "type": "number",
                  "range": [0, 2]
                }, {
                  "name": "CC_USE_HDR",
                  "type": "boolean"
                }, {
                  "name": "USE_ALBEDO_MAP",
                  "type": "boolean"
                }, {
                  "name": "ALBEDO_UV",
                  "type": "string",
                  "options": ["v_uv", "v_uv1"]
                }, {
                  "name": "NORMAL_UV",
                  "type": "string",
                  "options": ["v_uv", "v_uv1"]
                }, {
                  "name": "PBR_UV",
                  "type": "string",
                  "options": ["v_uv", "v_uv1"]
                }, {
                  "name": "USE_PBR_MAP",
                  "type": "boolean"
                }, {
                  "name": "USE_METALLIC_ROUGHNESS_MAP",
                  "type": "boolean"
                }, {
                  "name": "USE_OCCLUSION_MAP",
                  "type": "boolean"
                }, {
                  "name": "USE_EMISSIVE_MAP",
                  "type": "boolean"
                }, {
                  "name": "EMISSIVE_UV",
                  "type": "string",
                  "options": ["v_uv", "v_uv1"]
                }, {
                  "name": "USE_ALPHA_TEST",
                  "type": "boolean"
                }, {
                  "name": "ALPHA_TEST_CHANNEL",
                  "type": "string",
                  "options": ["a", "r"]
                }, {
                  "name": "CC_PIPELINE_TYPE",
                  "type": "number",
                  "range": [0, 1]
                }],
                "blocks": [{
                  "name": "Constants",
                  "defines": [],
                  "binding": 0,
                  "stageFlags": 17,
                  "members": [{
                    "name": "tilingOffset",
                    "type": 16,
                    "count": 1
                  }, {
                    "name": "albedo",
                    "type": 16,
                    "count": 1
                  }, {
                    "name": "albedoScaleAndCutoff",
                    "type": 16,
                    "count": 1
                  }, {
                    "name": "pbrParams",
                    "type": 16,
                    "count": 1
                  }, {
                    "name": "emissive",
                    "type": 16,
                    "count": 1
                  }, {
                    "name": "emissiveScaleParam",
                    "type": 16,
                    "count": 1
                  }]
                }],
                "samplerTextures": [{
                  "name": "albedoMap",
                  "type": 28,
                  "count": 1,
                  "defines": ["USE_ALBEDO_MAP"],
                  "stageFlags": 16,
                  "binding": 1
                }, {
                  "name": "normalMap",
                  "type": 28,
                  "count": 1,
                  "defines": ["USE_NORMAL_MAP"],
                  "stageFlags": 16,
                  "binding": 2
                }, {
                  "name": "pbrMap",
                  "type": 28,
                  "count": 1,
                  "defines": ["USE_PBR_MAP"],
                  "stageFlags": 16,
                  "binding": 3
                }, {
                  "name": "metallicRoughnessMap",
                  "type": 28,
                  "count": 1,
                  "defines": ["USE_METALLIC_ROUGHNESS_MAP"],
                  "stageFlags": 16,
                  "binding": 4
                }, {
                  "name": "occlusionMap",
                  "type": 28,
                  "count": 1,
                  "defines": ["USE_OCCLUSION_MAP"],
                  "stageFlags": 16,
                  "binding": 5
                }, {
                  "name": "emissiveMap",
                  "type": 28,
                  "count": 1,
                  "defines": ["USE_EMISSIVE_MAP"],
                  "stageFlags": 16,
                  "binding": 6
                }],
                "attributes": [{
                  "name": "a_position",
                  "type": 15,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 0
                }, {
                  "name": "a_normal",
                  "type": 15,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 1
                }, {
                  "name": "a_texCoord",
                  "type": 14,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 21,
                  "location": 2
                }, {
                  "name": "a_tangent",
                  "type": 16,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 44,
                  "location": 3
                }, {
                  "name": "a_vertexId",
                  "type": 13,
                  "count": 1,
                  "defines": ["CC_USE_MORPH"],
                  "stageFlags": 1,
                  "format": 11,
                  "location": 6
                }, {
                  "name": "a_joints",
                  "type": "u32vec4",
                  "count": 1,
                  "defines": ["CC_USE_SKINNING"],
                  "stageFlags": 1,
                  "location": 4
                }, {
                  "name": "a_weights",
                  "type": 16,
                  "count": 1,
                  "defines": ["CC_USE_SKINNING"],
                  "stageFlags": 1,
                  "format": 44,
                  "location": 5
                }, {
                  "name": "a_jointAnimInfo",
                  "type": 16,
                  "count": 1,
                  "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION", "USE_INSTANCING"],
                  "stageFlags": 1,
                  "format": 44,
                  "isInstanced": true,
                  "location": 7
                }, {
                  "name": "a_matWorld0",
                  "type": 16,
                  "count": 1,
                  "defines": ["USE_INSTANCING"],
                  "stageFlags": 1,
                  "format": 44,
                  "isInstanced": true,
                  "location": 8
                }, {
                  "name": "a_matWorld1",
                  "type": 16,
                  "count": 1,
                  "defines": ["USE_INSTANCING"],
                  "stageFlags": 1,
                  "format": 44,
                  "isInstanced": true,
                  "location": 9
                }, {
                  "name": "a_matWorld2",
                  "type": 16,
                  "count": 1,
                  "defines": ["USE_INSTANCING"],
                  "stageFlags": 1,
                  "format": 44,
                  "isInstanced": true,
                  "location": 10
                }, {
                  "name": "a_lightingMapUVParam",
                  "type": 16,
                  "count": 1,
                  "defines": ["USE_INSTANCING", "USE_LIGHTMAP"],
                  "stageFlags": 1,
                  "format": 44,
                  "isInstanced": true,
                  "location": 11
                }, {
                  "name": "a_dyn_batch_id",
                  "type": 13,
                  "count": 1,
                  "defines": ["!USE_INSTANCING", "USE_BATCHING"],
                  "stageFlags": 1,
                  "format": 11,
                  "location": 12
                }, {
                  "name": "a_color",
                  "type": 16,
                  "count": 1,
                  "defines": ["USE_VERTEX_COLOR"],
                  "stageFlags": 1,
                  "format": 44,
                  "location": 13
                }, {
                  "name": "a_texCoord1",
                  "type": 14,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 21,
                  "location": 14
                }]
              }, {
                "name": "standard|shadow-caster-vs:vert|shadow-caster-fs:frag",
                "hash": 826679743,
                "builtins": {
                  "statistics": {
                    "CC_EFFECT_USED_VERTEX_UNIFORM_VECTORS": 179,
                    "CC_EFFECT_USED_FRAGMENT_UNIFORM_VECTORS": 22
                  },
                  "globals": {
                    "blocks": [{
                      "name": "CCShadow",
                      "defines": []
                    }],
                    "samplerTextures": []
                  },
                  "locals": {
                    "blocks": [{
                      "name": "CCMorph",
                      "defines": ["CC_USE_MORPH"]
                    }, {
                      "name": "CCSkinningTexture",
                      "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION"]
                    }, {
                      "name": "CCSkinningAnimation",
                      "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION"]
                    }, {
                      "name": "CCSkinning",
                      "defines": ["CC_USE_SKINNING", "!CC_USE_BAKED_ANIMATION"]
                    }, {
                      "name": "CCLocalBatched",
                      "defines": ["!USE_INSTANCING", "USE_BATCHING"]
                    }, {
                      "name": "CCLocal",
                      "defines": ["!USE_INSTANCING", "!USE_BATCHING"]
                    }],
                    "samplerTextures": [{
                      "name": "cc_PositionDisplacements",
                      "defines": ["CC_USE_MORPH", "CC_MORPH_TARGET_HAS_POSITION"]
                    }, {
                      "name": "cc_NormalDisplacements",
                      "defines": ["CC_USE_MORPH", "CC_MORPH_TARGET_HAS_NORMAL"]
                    }, {
                      "name": "cc_TangentDisplacements",
                      "defines": ["CC_USE_MORPH", "CC_MORPH_TARGET_HAS_TANGENT"]
                    }, {
                      "name": "cc_jointTexture",
                      "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION"]
                    }]
                  }
                },
                "defines": [{
                  "name": "CC_USE_MORPH",
                  "type": "boolean"
                }, {
                  "name": "CC_MORPH_TARGET_COUNT",
                  "type": "number",
                  "range": [2, 8]
                }, {
                  "name": "CC_MORPH_PRECOMPUTED",
                  "type": "boolean"
                }, {
                  "name": "CC_MORPH_TARGET_HAS_POSITION",
                  "type": "boolean"
                }, {
                  "name": "CC_MORPH_TARGET_HAS_NORMAL",
                  "type": "boolean"
                }, {
                  "name": "CC_MORPH_TARGET_HAS_TANGENT",
                  "type": "boolean"
                }, {
                  "name": "CC_USE_SKINNING",
                  "type": "boolean"
                }, {
                  "name": "CC_USE_BAKED_ANIMATION",
                  "type": "boolean"
                }, {
                  "name": "USE_INSTANCING",
                  "type": "boolean"
                }, {
                  "name": "USE_BATCHING",
                  "type": "boolean"
                }, {
                  "name": "USE_LIGHTMAP",
                  "type": "boolean"
                }, {
                  "name": "HAS_SECOND_UV",
                  "type": "boolean"
                }, {
                  "name": "USE_ALBEDO_MAP",
                  "type": "boolean"
                }, {
                  "name": "ALBEDO_UV",
                  "type": "string",
                  "options": ["v_uv", "v_uv1"]
                }, {
                  "name": "USE_ALPHA_TEST",
                  "type": "boolean"
                }, {
                  "name": "ALPHA_TEST_CHANNEL",
                  "type": "string",
                  "options": ["a", "r"]
                }],
                "blocks": [{
                  "name": "Constants",
                  "defines": [],
                  "binding": 0,
                  "stageFlags": 17,
                  "members": [{
                    "name": "tilingOffset",
                    "type": 16,
                    "count": 1
                  }, {
                    "name": "albedo",
                    "type": 16,
                    "count": 1
                  }, {
                    "name": "albedoScaleAndCutoff",
                    "type": 16,
                    "count": 1
                  }, {
                    "name": "pbrParams",
                    "type": 16,
                    "count": 1
                  }, {
                    "name": "emissive",
                    "type": 16,
                    "count": 1
                  }, {
                    "name": "emissiveScaleParam",
                    "type": 16,
                    "count": 1
                  }]
                }],
                "samplerTextures": [{
                  "name": "albedoMap",
                  "type": 28,
                  "count": 1,
                  "defines": ["USE_ALBEDO_MAP"],
                  "stageFlags": 16,
                  "binding": 1
                }],
                "attributes": [{
                  "name": "a_position",
                  "type": 15,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 0
                }, {
                  "name": "a_normal",
                  "type": 15,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 1
                }, {
                  "name": "a_texCoord",
                  "type": 14,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 21,
                  "location": 2
                }, {
                  "name": "a_tangent",
                  "type": 16,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 44,
                  "location": 3
                }, {
                  "name": "a_vertexId",
                  "type": 13,
                  "count": 1,
                  "defines": ["CC_USE_MORPH"],
                  "stageFlags": 1,
                  "format": 11,
                  "location": 6
                }, {
                  "name": "a_joints",
                  "type": "u32vec4",
                  "count": 1,
                  "defines": ["CC_USE_SKINNING"],
                  "stageFlags": 1,
                  "location": 4
                }, {
                  "name": "a_weights",
                  "type": 16,
                  "count": 1,
                  "defines": ["CC_USE_SKINNING"],
                  "stageFlags": 1,
                  "format": 44,
                  "location": 5
                }, {
                  "name": "a_jointAnimInfo",
                  "type": 16,
                  "count": 1,
                  "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION", "USE_INSTANCING"],
                  "stageFlags": 1,
                  "format": 44,
                  "isInstanced": true,
                  "location": 7
                }, {
                  "name": "a_matWorld0",
                  "type": 16,
                  "count": 1,
                  "defines": ["USE_INSTANCING"],
                  "stageFlags": 1,
                  "format": 44,
                  "isInstanced": true,
                  "location": 8
                }, {
                  "name": "a_matWorld1",
                  "type": 16,
                  "count": 1,
                  "defines": ["USE_INSTANCING"],
                  "stageFlags": 1,
                  "format": 44,
                  "isInstanced": true,
                  "location": 9
                }, {
                  "name": "a_matWorld2",
                  "type": 16,
                  "count": 1,
                  "defines": ["USE_INSTANCING"],
                  "stageFlags": 1,
                  "format": 44,
                  "isInstanced": true,
                  "location": 10
                }, {
                  "name": "a_lightingMapUVParam",
                  "type": 16,
                  "count": 1,
                  "defines": ["USE_INSTANCING", "USE_LIGHTMAP"],
                  "stageFlags": 1,
                  "format": 44,
                  "isInstanced": true,
                  "location": 11
                }, {
                  "name": "a_dyn_batch_id",
                  "type": 13,
                  "count": 1,
                  "defines": ["!USE_INSTANCING", "USE_BATCHING"],
                  "stageFlags": 1,
                  "format": 11,
                  "location": 12
                }, {
                  "name": "a_texCoord1",
                  "type": 14,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 21,
                  "location": 13
                }]
              }]
            }, {
              "name": "terrain",
              "techniques": [{
                "name": "opaque",
                "passes": [{
                  "program": "terrain|terrain-vs|terrain-fs",
                  "properties": {
                    "UVScale": {
                      "value": [1, 1, 1, 1],
                      "type": 16
                    },
                    "lightMapUVParam": {
                      "value": [0, 0, 0, 0],
                      "type": 16
                    },
                    "metallic": {
                      "value": [0, 0, 0, 0],
                      "type": 16
                    },
                    "roughness": {
                      "value": [1, 1, 1, 1],
                      "type": 16
                    },
                    "weightMap": {
                      "value": "black",
                      "type": 28
                    },
                    "detailMap0": {
                      "value": "grey",
                      "type": 28
                    },
                    "detailMap1": {
                      "value": "grey",
                      "type": 28
                    },
                    "detailMap2": {
                      "value": "grey",
                      "type": 28
                    },
                    "detailMap3": {
                      "value": "grey",
                      "type": 28
                    },
                    "normalMap0": {
                      "value": "normal",
                      "type": 28
                    },
                    "normalMap1": {
                      "value": "normal",
                      "type": 28
                    },
                    "normalMap2": {
                      "value": "normal",
                      "type": 28
                    },
                    "normalMap3": {
                      "value": "normal",
                      "type": 28
                    },
                    "lightMap": {
                      "value": "grey",
                      "type": 28
                    }
                  }
                }, {
                  "phase": "deferred",
                  "propertyIndex": 0,
                  "blendState": {
                    "targets": [{
                      "blend": false
                    }, {
                      "blend": false
                    }, {
                      "blend": false
                    }, {
                      "blend": false
                    }]
                  },
                  "program": "terrain|terrain-vs|terrain-fs",
                  "properties": {
                    "UVScale": {
                      "value": [1, 1, 1, 1],
                      "type": 16
                    },
                    "lightMapUVParam": {
                      "value": [0, 0, 0, 0],
                      "type": 16
                    },
                    "metallic": {
                      "value": [0, 0, 0, 0],
                      "type": 16
                    },
                    "roughness": {
                      "value": [1, 1, 1, 1],
                      "type": 16
                    },
                    "weightMap": {
                      "value": "black",
                      "type": 28
                    },
                    "detailMap0": {
                      "value": "grey",
                      "type": 28
                    },
                    "detailMap1": {
                      "value": "grey",
                      "type": 28
                    },
                    "detailMap2": {
                      "value": "grey",
                      "type": 28
                    },
                    "detailMap3": {
                      "value": "grey",
                      "type": 28
                    },
                    "normalMap0": {
                      "value": "normal",
                      "type": 28
                    },
                    "normalMap1": {
                      "value": "normal",
                      "type": 28
                    },
                    "normalMap2": {
                      "value": "normal",
                      "type": 28
                    },
                    "normalMap3": {
                      "value": "normal",
                      "type": 28
                    },
                    "lightMap": {
                      "value": "grey",
                      "type": 28
                    }
                  }
                }, {
                  "phase": "forward-add",
                  "propertyIndex": 0,
                  "embeddedMacros": {
                    "CC_FORWARD_ADD": true
                  },
                  "blendState": {
                    "targets": [{
                      "blend": true,
                      "blendSrc": 1,
                      "blendDst": 1,
                      "blendSrcAlpha": 0,
                      "blendDstAlpha": 1
                    }]
                  },
                  "program": "terrain|terrain-vs|terrain-fs",
                  "depthStencilState": {
                    "depthFunc": 2,
                    "depthTest": true,
                    "depthWrite": false
                  },
                  "properties": {
                    "UVScale": {
                      "value": [1, 1, 1, 1],
                      "type": 16
                    },
                    "lightMapUVParam": {
                      "value": [0, 0, 0, 0],
                      "type": 16
                    },
                    "metallic": {
                      "value": [0, 0, 0, 0],
                      "type": 16
                    },
                    "roughness": {
                      "value": [1, 1, 1, 1],
                      "type": 16
                    },
                    "weightMap": {
                      "value": "black",
                      "type": 28
                    },
                    "detailMap0": {
                      "value": "grey",
                      "type": 28
                    },
                    "detailMap1": {
                      "value": "grey",
                      "type": 28
                    },
                    "detailMap2": {
                      "value": "grey",
                      "type": 28
                    },
                    "detailMap3": {
                      "value": "grey",
                      "type": 28
                    },
                    "normalMap0": {
                      "value": "normal",
                      "type": 28
                    },
                    "normalMap1": {
                      "value": "normal",
                      "type": 28
                    },
                    "normalMap2": {
                      "value": "normal",
                      "type": 28
                    },
                    "normalMap3": {
                      "value": "normal",
                      "type": 28
                    },
                    "lightMap": {
                      "value": "grey",
                      "type": 28
                    }
                  }
                }, {
                  "phase": "shadow-add",
                  "propertyIndex": 0,
                  "rasterizerState": {
                    "cullMode": 2
                  },
                  "program": "terrain|shadow-caster-vs:vert|shadow-caster-fs:frag"
                }]
              }],
              "shaders": [{
                "name": "terrain|terrain-vs|terrain-fs",
                "hash": 3030724902,
                "builtins": {
                  "statistics": {
                    "CC_EFFECT_USED_VERTEX_UNIFORM_VECTORS": 64,
                    "CC_EFFECT_USED_FRAGMENT_UNIFORM_VECTORS": 55
                  },
                  "globals": {
                    "blocks": [{
                      "name": "CCGlobal",
                      "defines": []
                    }, {
                      "name": "CCCamera",
                      "defines": []
                    }, {
                      "name": "CCShadow",
                      "defines": []
                    }],
                    "samplerTextures": [{
                      "name": "cc_shadowMap",
                      "defines": ["CC_RECEIVE_SHADOW"]
                    }, {
                      "name": "cc_spotLightingMap",
                      "defines": ["CC_RECEIVE_SHADOW"]
                    }, {
                      "name": "cc_environment",
                      "defines": ["CC_USE_IBL"]
                    }]
                  },
                  "locals": {
                    "blocks": [{
                      "name": "CCLocal",
                      "defines": []
                    }, {
                      "name": "CCForwardLight",
                      "defines": ["CC_FORWARD_ADD"]
                    }],
                    "samplerTextures": [{
                      "name": "cc_lightingMap",
                      "defines": ["USE_LIGHTMAP", "!USE_BATCHING", "!CC_FORWARD_ADD"]
                    }]
                  }
                },
                "defines": [{
                  "name": "CC_USE_FOG",
                  "type": "number",
                  "range": [0, 4]
                }, {
                  "name": "CC_FORWARD_ADD",
                  "type": "boolean"
                }, {
                  "name": "CC_RECEIVE_SHADOW",
                  "type": "boolean"
                }, {
                  "name": "USE_NORMALMAP",
                  "type": "boolean"
                }, {
                  "name": "USE_LIGHTMAP",
                  "type": "boolean"
                }, {
                  "name": "CC_USE_IBL",
                  "type": "number",
                  "range": [0, 2]
                }, {
                  "name": "USE_BATCHING",
                  "type": "boolean"
                }, {
                  "name": "CC_USE_HDR",
                  "type": "boolean"
                }, {
                  "name": "LAYERS",
                  "type": "number",
                  "range": [0, 4]
                }, {
                  "name": "USE_PBR",
                  "type": "boolean"
                }, {
                  "name": "CC_PIPELINE_TYPE",
                  "type": "number",
                  "range": [0, 1]
                }],
                "blocks": [{
                  "name": "TexCoords",
                  "defines": [],
                  "binding": 0,
                  "stageFlags": 1,
                  "members": [{
                    "name": "UVScale",
                    "type": 16,
                    "count": 1
                  }, {
                    "name": "lightMapUVParam",
                    "type": 16,
                    "count": 1
                  }]
                }, {
                  "name": "PbrParams",
                  "defines": [],
                  "binding": 1,
                  "stageFlags": 16,
                  "members": [{
                    "name": "metallic",
                    "type": 16,
                    "count": 1
                  }, {
                    "name": "roughness",
                    "type": 16,
                    "count": 1
                  }]
                }],
                "samplerTextures": [{
                  "name": "weightMap",
                  "type": 28,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 16,
                  "binding": 2
                }, {
                  "name": "detailMap0",
                  "type": 28,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 16,
                  "binding": 3
                }, {
                  "name": "detailMap1",
                  "type": 28,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 16,
                  "binding": 4
                }, {
                  "name": "detailMap2",
                  "type": 28,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 16,
                  "binding": 5
                }, {
                  "name": "detailMap3",
                  "type": 28,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 16,
                  "binding": 6
                }, {
                  "name": "normalMap0",
                  "type": 28,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 16,
                  "binding": 7
                }, {
                  "name": "normalMap1",
                  "type": 28,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 16,
                  "binding": 8
                }, {
                  "name": "normalMap2",
                  "type": 28,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 16,
                  "binding": 9
                }, {
                  "name": "normalMap3",
                  "type": 28,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 16,
                  "binding": 10
                }, {
                  "name": "lightMap",
                  "type": 28,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 16,
                  "binding": 11
                }],
                "attributes": [{
                  "name": "a_position",
                  "type": 15,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 0
                }, {
                  "name": "a_normal",
                  "type": 15,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 1
                }, {
                  "name": "a_texCoord",
                  "type": 14,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 21,
                  "location": 2
                }]
              }, {
                "name": "terrain|shadow-caster-vs:vert|shadow-caster-fs:frag",
                "hash": 1471860764,
                "builtins": {
                  "statistics": {
                    "CC_EFFECT_USED_VERTEX_UNIFORM_VECTORS": 62,
                    "CC_EFFECT_USED_FRAGMENT_UNIFORM_VECTORS": 0
                  },
                  "globals": {
                    "blocks": [{
                      "name": "CCGlobal",
                      "defines": []
                    }, {
                      "name": "CCCamera",
                      "defines": []
                    }, {
                      "name": "CCShadow",
                      "defines": []
                    }],
                    "samplerTextures": []
                  },
                  "locals": {
                    "blocks": [{
                      "name": "CCLocal",
                      "defines": []
                    }],
                    "samplerTextures": []
                  }
                },
                "defines": [],
                "blocks": [],
                "samplerTextures": [],
                "attributes": [{
                  "name": "a_position",
                  "type": 15,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 0
                }, {
                  "name": "a_normal",
                  "type": 15,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 1
                }, {
                  "name": "a_texCoord",
                  "type": 14,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 21,
                  "location": 2
                }]
              }]
            }, {
              "name": "unlit",
              "techniques": [{
                "name": "opaque",
                "passes": [{
                  "program": "unlit|unlit-vs:vert|unlit-fs:frag",
                  "properties": {
                    "mainTexture": {
                      "value": "grey",
                      "type": 28
                    },
                    "tilingOffset": {
                      "value": [1, 1, 0, 0],
                      "type": 16
                    },
                    "mainColor": {
                      "value": [1, 1, 1, 1],
                      "type": 16
                    },
                    "colorScale": {
                      "value": [1, 1, 1],
                      "type": 15,
                      "handleInfo": ["colorScaleAndCutoff", 0, 15]
                    },
                    "alphaThreshold": {
                      "value": [0.5],
                      "type": 13,
                      "handleInfo": ["colorScaleAndCutoff", 3, 13]
                    },
                    "color": {
                      "type": 16,
                      "handleInfo": ["mainColor", 0, 16]
                    },
                    "colorScaleAndCutoff": {
                      "type": 16,
                      "value": [1, 1, 1, 0.5]
                    }
                  }
                }]
              }],
              "shaders": [{
                "name": "unlit|unlit-vs:vert|unlit-fs:frag",
                "hash": 1017648509,
                "builtins": {
                  "statistics": {
                    "CC_EFFECT_USED_VERTEX_UNIFORM_VECTORS": 195,
                    "CC_EFFECT_USED_FRAGMENT_UNIFORM_VECTORS": 39
                  },
                  "globals": {
                    "blocks": [{
                      "name": "CCGlobal",
                      "defines": []
                    }, {
                      "name": "CCCamera",
                      "defines": []
                    }],
                    "samplerTextures": []
                  },
                  "locals": {
                    "blocks": [{
                      "name": "CCMorph",
                      "defines": ["CC_USE_MORPH"]
                    }, {
                      "name": "CCSkinningTexture",
                      "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION"]
                    }, {
                      "name": "CCSkinningAnimation",
                      "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION"]
                    }, {
                      "name": "CCSkinning",
                      "defines": ["CC_USE_SKINNING", "!CC_USE_BAKED_ANIMATION"]
                    }, {
                      "name": "CCLocalBatched",
                      "defines": ["!USE_INSTANCING", "USE_BATCHING"]
                    }, {
                      "name": "CCLocal",
                      "defines": ["!USE_INSTANCING", "!USE_BATCHING"]
                    }],
                    "samplerTextures": [{
                      "name": "cc_PositionDisplacements",
                      "defines": ["CC_USE_MORPH", "CC_MORPH_TARGET_HAS_POSITION"]
                    }, {
                      "name": "cc_NormalDisplacements",
                      "defines": ["CC_USE_MORPH", "CC_MORPH_TARGET_HAS_NORMAL"]
                    }, {
                      "name": "cc_TangentDisplacements",
                      "defines": ["CC_USE_MORPH", "CC_MORPH_TARGET_HAS_TANGENT"]
                    }, {
                      "name": "cc_jointTexture",
                      "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION"]
                    }]
                  }
                },
                "defines": [{
                  "name": "CC_USE_MORPH",
                  "type": "boolean"
                }, {
                  "name": "CC_MORPH_TARGET_COUNT",
                  "type": "number",
                  "range": [2, 8]
                }, {
                  "name": "CC_MORPH_PRECOMPUTED",
                  "type": "boolean"
                }, {
                  "name": "CC_MORPH_TARGET_HAS_POSITION",
                  "type": "boolean"
                }, {
                  "name": "CC_MORPH_TARGET_HAS_NORMAL",
                  "type": "boolean"
                }, {
                  "name": "CC_MORPH_TARGET_HAS_TANGENT",
                  "type": "boolean"
                }, {
                  "name": "CC_USE_SKINNING",
                  "type": "boolean"
                }, {
                  "name": "CC_USE_BAKED_ANIMATION",
                  "type": "boolean"
                }, {
                  "name": "USE_INSTANCING",
                  "type": "boolean"
                }, {
                  "name": "USE_BATCHING",
                  "type": "boolean"
                }, {
                  "name": "USE_LIGHTMAP",
                  "type": "boolean"
                }, {
                  "name": "CC_USE_FOG",
                  "type": "number",
                  "range": [0, 4]
                }, {
                  "name": "CC_FORWARD_ADD",
                  "type": "boolean"
                }, {
                  "name": "USE_VERTEX_COLOR",
                  "type": "boolean"
                }, {
                  "name": "USE_TEXTURE",
                  "type": "boolean"
                }, {
                  "name": "SAMPLE_FROM_RT",
                  "type": "boolean"
                }, {
                  "name": "CC_USE_HDR",
                  "type": "boolean"
                }, {
                  "name": "USE_ALPHA_TEST",
                  "type": "boolean"
                }, {
                  "name": "ALPHA_TEST_CHANNEL",
                  "type": "string",
                  "options": ["a", "r", "g", "b"]
                }],
                "blocks": [{
                  "name": "TexCoords",
                  "defines": ["USE_TEXTURE"],
                  "binding": 0,
                  "stageFlags": 1,
                  "members": [{
                    "name": "tilingOffset",
                    "type": 16,
                    "count": 1
                  }]
                }, {
                  "name": "Constant",
                  "defines": [],
                  "binding": 1,
                  "stageFlags": 16,
                  "members": [{
                    "name": "mainColor",
                    "type": 16,
                    "count": 1
                  }, {
                    "name": "colorScaleAndCutoff",
                    "type": 16,
                    "count": 1
                  }]
                }],
                "samplerTextures": [{
                  "name": "mainTexture",
                  "type": 28,
                  "count": 1,
                  "defines": ["USE_TEXTURE"],
                  "stageFlags": 16,
                  "binding": 2
                }],
                "attributes": [{
                  "name": "a_position",
                  "type": 15,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 0
                }, {
                  "name": "a_normal",
                  "type": 15,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 1
                }, {
                  "name": "a_texCoord",
                  "type": 14,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 21,
                  "location": 2
                }, {
                  "name": "a_tangent",
                  "type": 16,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 44,
                  "location": 3
                }, {
                  "name": "a_vertexId",
                  "type": 13,
                  "count": 1,
                  "defines": ["CC_USE_MORPH"],
                  "stageFlags": 1,
                  "format": 11,
                  "location": 6
                }, {
                  "name": "a_joints",
                  "type": "u32vec4",
                  "count": 1,
                  "defines": ["CC_USE_SKINNING"],
                  "stageFlags": 1,
                  "location": 4
                }, {
                  "name": "a_weights",
                  "type": 16,
                  "count": 1,
                  "defines": ["CC_USE_SKINNING"],
                  "stageFlags": 1,
                  "format": 44,
                  "location": 5
                }, {
                  "name": "a_jointAnimInfo",
                  "type": 16,
                  "count": 1,
                  "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION", "USE_INSTANCING"],
                  "stageFlags": 1,
                  "format": 44,
                  "isInstanced": true,
                  "location": 7
                }, {
                  "name": "a_matWorld0",
                  "type": 16,
                  "count": 1,
                  "defines": ["USE_INSTANCING"],
                  "stageFlags": 1,
                  "format": 44,
                  "isInstanced": true,
                  "location": 8
                }, {
                  "name": "a_matWorld1",
                  "type": 16,
                  "count": 1,
                  "defines": ["USE_INSTANCING"],
                  "stageFlags": 1,
                  "format": 44,
                  "isInstanced": true,
                  "location": 9
                }, {
                  "name": "a_matWorld2",
                  "type": 16,
                  "count": 1,
                  "defines": ["USE_INSTANCING"],
                  "stageFlags": 1,
                  "format": 44,
                  "isInstanced": true,
                  "location": 10
                }, {
                  "name": "a_lightingMapUVParam",
                  "type": 16,
                  "count": 1,
                  "defines": ["USE_INSTANCING", "USE_LIGHTMAP"],
                  "stageFlags": 1,
                  "format": 44,
                  "isInstanced": true,
                  "location": 11
                }, {
                  "name": "a_dyn_batch_id",
                  "type": 13,
                  "count": 1,
                  "defines": ["!USE_INSTANCING", "USE_BATCHING"],
                  "stageFlags": 1,
                  "format": 11,
                  "location": 12
                }, {
                  "name": "a_color",
                  "type": 16,
                  "count": 1,
                  "defines": ["USE_VERTEX_COLOR"],
                  "stageFlags": 1,
                  "format": 44,
                  "location": 13
                }]
              }]
            }, {
              "name": "deferred-lighting",
              "techniques": [{
                "passes": [{
                  "phase": "deferred-lighting",
                  "program": "deferred-lighting|lighting-vs|lighting-fs",
                  "depthStencilState": {
                    "depthFunc": 4,
                    "depthTest": true,
                    "depthWrite": false
                  }
                }]
              }],
              "shaders": [{
                "name": "deferred-lighting|lighting-vs|lighting-fs",
                "hash": 1507574087,
                "builtins": {
                  "statistics": {
                    "CC_EFFECT_USED_VERTEX_UNIFORM_VECTORS": 37,
                    "CC_EFFECT_USED_FRAGMENT_UNIFORM_VECTORS": 53
                  },
                  "globals": {
                    "blocks": [{
                      "name": "CCGlobal",
                      "defines": []
                    }, {
                      "name": "CCCamera",
                      "defines": []
                    }, {
                      "name": "CCShadow",
                      "defines": []
                    }],
                    "samplerTextures": [{
                      "name": "cc_shadowMap",
                      "defines": ["CC_RECEIVE_SHADOW"]
                    }, {
                      "name": "cc_spotLightingMap",
                      "defines": ["CC_RECEIVE_SHADOW"]
                    }, {
                      "name": "cc_environment",
                      "defines": ["CC_USE_IBL"]
                    }, {
                      "name": "cc_gbuffer_albedoMap",
                      "defines": []
                    }, {
                      "name": "cc_gbuffer_positionMap",
                      "defines": []
                    }, {
                      "name": "cc_gbuffer_normalMap",
                      "defines": []
                    }, {
                      "name": "cc_gbuffer_emissiveMap",
                      "defines": []
                    }]
                  },
                  "locals": {
                    "blocks": [{
                      "name": "CCForwardLight",
                      "defines": []
                    }],
                    "samplerTextures": []
                  }
                },
                "defines": [{
                  "name": "CC_RECEIVE_SHADOW",
                  "type": "boolean"
                }, {
                  "name": "CC_USE_IBL",
                  "type": "number",
                  "range": [0, 2]
                }, {
                  "name": "USE_LIGHTMAP",
                  "type": "boolean"
                }, {
                  "name": "USE_BATCHING",
                  "type": "boolean"
                }, {
                  "name": "CC_FORWARD_ADD",
                  "type": "boolean"
                }, {
                  "name": "CC_USE_HDR",
                  "type": "boolean"
                }, {
                  "name": "CC_PIPELINE_TYPE",
                  "type": "number",
                  "range": [0, 1]
                }, {
                  "name": "CC_USE_FOG",
                  "type": "number",
                  "range": [0, 4]
                }],
                "blocks": [],
                "samplerTextures": [],
                "attributes": [{
                  "name": "a_position",
                  "type": 15,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 0
                }, {
                  "name": "a_normal",
                  "type": 15,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 1
                }, {
                  "name": "a_texCoord",
                  "type": 14,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 21,
                  "location": 2
                }, {
                  "name": "a_tangent",
                  "type": 16,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 44,
                  "location": 3
                }]
              }]
            }, {
              "name": "planar-shadow",
              "techniques": [{
                "passes": [{
                  "phase": "planarShadow",
                  "blendState": {
                    "targets": [{
                      "blend": true,
                      "blendSrc": 2,
                      "blendDst": 4,
                      "blendDstAlpha": 4
                    }]
                  },
                  "program": "planar-shadow|planar-shadow-vs:vert|planar-shadow-fs:frag",
                  "depthStencilState": {
                    "depthTest": true,
                    "depthWrite": false,
                    "stencilTestFront": true,
                    "stencilFuncFront": 5,
                    "stencilPassOpFront": 2,
                    "stencilRefBack": 128,
                    "stencilRefFront": 128,
                    "stencilReadMaskBack": 128,
                    "stencilReadMaskFront": 128,
                    "stencilWriteMaskBack": 128,
                    "stencilWriteMaskFront": 128
                  }
                }]
              }],
              "shaders": [{
                "name": "planar-shadow|planar-shadow-vs:vert|planar-shadow-fs:frag",
                "hash": 649108546,
                "builtins": {
                  "statistics": {
                    "CC_EFFECT_USED_VERTEX_UNIFORM_VECTORS": 210,
                    "CC_EFFECT_USED_FRAGMENT_UNIFORM_VECTORS": 53
                  },
                  "globals": {
                    "blocks": [{
                      "name": "CCGlobal",
                      "defines": []
                    }, {
                      "name": "CCCamera",
                      "defines": []
                    }, {
                      "name": "CCShadow",
                      "defines": []
                    }],
                    "samplerTextures": []
                  },
                  "locals": {
                    "blocks": [{
                      "name": "CCMorph",
                      "defines": ["CC_USE_MORPH"]
                    }, {
                      "name": "CCSkinningTexture",
                      "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION"]
                    }, {
                      "name": "CCSkinningAnimation",
                      "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION"]
                    }, {
                      "name": "CCSkinning",
                      "defines": ["CC_USE_SKINNING", "!CC_USE_BAKED_ANIMATION"]
                    }, {
                      "name": "CCLocalBatched",
                      "defines": ["!USE_INSTANCING", "USE_BATCHING"]
                    }, {
                      "name": "CCLocal",
                      "defines": ["!USE_INSTANCING", "!USE_BATCHING"]
                    }],
                    "samplerTextures": [{
                      "name": "cc_PositionDisplacements",
                      "defines": ["CC_USE_MORPH", "CC_MORPH_TARGET_HAS_POSITION"]
                    }, {
                      "name": "cc_NormalDisplacements",
                      "defines": ["CC_USE_MORPH", "CC_MORPH_TARGET_HAS_NORMAL"]
                    }, {
                      "name": "cc_TangentDisplacements",
                      "defines": ["CC_USE_MORPH", "CC_MORPH_TARGET_HAS_TANGENT"]
                    }, {
                      "name": "cc_jointTexture",
                      "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION"]
                    }]
                  }
                },
                "defines": [{
                  "name": "CC_USE_MORPH",
                  "type": "boolean"
                }, {
                  "name": "CC_MORPH_TARGET_COUNT",
                  "type": "number",
                  "range": [2, 8]
                }, {
                  "name": "CC_MORPH_PRECOMPUTED",
                  "type": "boolean"
                }, {
                  "name": "CC_MORPH_TARGET_HAS_POSITION",
                  "type": "boolean"
                }, {
                  "name": "CC_MORPH_TARGET_HAS_NORMAL",
                  "type": "boolean"
                }, {
                  "name": "CC_MORPH_TARGET_HAS_TANGENT",
                  "type": "boolean"
                }, {
                  "name": "CC_USE_SKINNING",
                  "type": "boolean"
                }, {
                  "name": "CC_USE_BAKED_ANIMATION",
                  "type": "boolean"
                }, {
                  "name": "USE_INSTANCING",
                  "type": "boolean"
                }, {
                  "name": "USE_BATCHING",
                  "type": "boolean"
                }, {
                  "name": "USE_LIGHTMAP",
                  "type": "boolean"
                }, {
                  "name": "CC_USE_HDR",
                  "type": "boolean"
                }],
                "blocks": [],
                "samplerTextures": [],
                "attributes": [{
                  "name": "a_position",
                  "type": 15,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 0
                }, {
                  "name": "a_normal",
                  "type": 15,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 1
                }, {
                  "name": "a_texCoord",
                  "type": 14,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 21,
                  "location": 2
                }, {
                  "name": "a_tangent",
                  "type": 16,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 44,
                  "location": 3
                }, {
                  "name": "a_vertexId",
                  "type": 13,
                  "count": 1,
                  "defines": ["CC_USE_MORPH"],
                  "stageFlags": 1,
                  "format": 11,
                  "location": 6
                }, {
                  "name": "a_joints",
                  "type": "u32vec4",
                  "count": 1,
                  "defines": ["CC_USE_SKINNING"],
                  "stageFlags": 1,
                  "location": 4
                }, {
                  "name": "a_weights",
                  "type": 16,
                  "count": 1,
                  "defines": ["CC_USE_SKINNING"],
                  "stageFlags": 1,
                  "format": 44,
                  "location": 5
                }, {
                  "name": "a_jointAnimInfo",
                  "type": 16,
                  "count": 1,
                  "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION", "USE_INSTANCING"],
                  "stageFlags": 1,
                  "format": 44,
                  "isInstanced": true,
                  "location": 7
                }, {
                  "name": "a_matWorld0",
                  "type": 16,
                  "count": 1,
                  "defines": ["USE_INSTANCING"],
                  "stageFlags": 1,
                  "format": 44,
                  "isInstanced": true,
                  "location": 8
                }, {
                  "name": "a_matWorld1",
                  "type": 16,
                  "count": 1,
                  "defines": ["USE_INSTANCING"],
                  "stageFlags": 1,
                  "format": 44,
                  "isInstanced": true,
                  "location": 9
                }, {
                  "name": "a_matWorld2",
                  "type": 16,
                  "count": 1,
                  "defines": ["USE_INSTANCING"],
                  "stageFlags": 1,
                  "format": 44,
                  "isInstanced": true,
                  "location": 10
                }, {
                  "name": "a_lightingMapUVParam",
                  "type": 16,
                  "count": 1,
                  "defines": ["USE_INSTANCING", "USE_LIGHTMAP"],
                  "stageFlags": 1,
                  "format": 44,
                  "isInstanced": true,
                  "location": 11
                }, {
                  "name": "a_dyn_batch_id",
                  "type": 13,
                  "count": 1,
                  "defines": ["!USE_INSTANCING", "USE_BATCHING"],
                  "stageFlags": 1,
                  "format": 11,
                  "location": 12
                }]
              }]
            }, {
              "name": "post-process",
              "techniques": [{
                "passes": [{
                  "phase": "post-process",
                  "blendState": {
                    "targets": [{
                      "blend": true,
                      "blendSrc": 2,
                      "blendDst": 4,
                      "blendSrcAlpha": 2,
                      "blendDstAlpha": 4
                    }]
                  },
                  "program": "post-process|post-process-vs|post-process-fs",
                  "depthStencilState": {
                    "depthTest": false,
                    "depthWrite": false
                  }
                }]
              }],
              "shaders": [{
                "name": "post-process|post-process-vs|post-process-fs",
                "hash": 1780456825,
                "builtins": {
                  "statistics": {
                    "CC_EFFECT_USED_VERTEX_UNIFORM_VECTORS": 145,
                    "CC_EFFECT_USED_FRAGMENT_UNIFORM_VECTORS": 37
                  },
                  "globals": {
                    "blocks": [{
                      "name": "CCGlobal",
                      "defines": []
                    }, {
                      "name": "CCCamera",
                      "defines": []
                    }],
                    "samplerTextures": [{
                      "name": "cc_lighting_resultMap",
                      "defines": []
                    }]
                  },
                  "locals": {
                    "blocks": [{
                      "name": "CCMorph",
                      "defines": ["CC_USE_MORPH"]
                    }, {
                      "name": "CCSkinningTexture",
                      "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION"]
                    }, {
                      "name": "CCSkinningAnimation",
                      "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION"]
                    }, {
                      "name": "CCSkinning",
                      "defines": ["CC_USE_SKINNING", "!CC_USE_BAKED_ANIMATION"]
                    }],
                    "samplerTextures": [{
                      "name": "cc_PositionDisplacements",
                      "defines": ["CC_USE_MORPH", "CC_MORPH_TARGET_HAS_POSITION"]
                    }, {
                      "name": "cc_NormalDisplacements",
                      "defines": ["CC_USE_MORPH", "CC_MORPH_TARGET_HAS_NORMAL"]
                    }, {
                      "name": "cc_TangentDisplacements",
                      "defines": ["CC_USE_MORPH", "CC_MORPH_TARGET_HAS_TANGENT"]
                    }, {
                      "name": "cc_jointTexture",
                      "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION"]
                    }]
                  }
                },
                "defines": [{
                  "name": "CC_USE_MORPH",
                  "type": "boolean"
                }, {
                  "name": "CC_MORPH_TARGET_COUNT",
                  "type": "number",
                  "range": [2, 8]
                }, {
                  "name": "CC_MORPH_PRECOMPUTED",
                  "type": "boolean"
                }, {
                  "name": "CC_MORPH_TARGET_HAS_POSITION",
                  "type": "boolean"
                }, {
                  "name": "CC_MORPH_TARGET_HAS_NORMAL",
                  "type": "boolean"
                }, {
                  "name": "CC_MORPH_TARGET_HAS_TANGENT",
                  "type": "boolean"
                }, {
                  "name": "CC_USE_SKINNING",
                  "type": "boolean"
                }, {
                  "name": "CC_USE_BAKED_ANIMATION",
                  "type": "boolean"
                }, {
                  "name": "USE_INSTANCING",
                  "type": "boolean"
                }],
                "blocks": [],
                "samplerTextures": [],
                "attributes": [{
                  "name": "a_position",
                  "type": 15,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 0
                }, {
                  "name": "a_normal",
                  "type": 15,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 1
                }, {
                  "name": "a_texCoord",
                  "type": 14,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 21,
                  "location": 2
                }, {
                  "name": "a_tangent",
                  "type": 16,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 44,
                  "location": 3
                }, {
                  "name": "a_vertexId",
                  "type": 13,
                  "count": 1,
                  "defines": ["CC_USE_MORPH"],
                  "stageFlags": 1,
                  "format": 11,
                  "location": 6
                }, {
                  "name": "a_joints",
                  "type": "u32vec4",
                  "count": 1,
                  "defines": ["CC_USE_SKINNING"],
                  "stageFlags": 1,
                  "location": 4
                }, {
                  "name": "a_weights",
                  "type": 16,
                  "count": 1,
                  "defines": ["CC_USE_SKINNING"],
                  "stageFlags": 1,
                  "format": 44,
                  "location": 5
                }, {
                  "name": "a_jointAnimInfo",
                  "type": 16,
                  "count": 1,
                  "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION", "USE_INSTANCING"],
                  "stageFlags": 1,
                  "format": 44,
                  "isInstanced": true,
                  "location": 7
                }]
              }]
            }, {
              "name": "skybox",
              "techniques": [{
                "passes": [{
                  "rasterizerState": {
                    "cullMode": 0
                  },
                  "program": "skybox|sky-vs:vert|sky-fs:frag",
                  "priority": 245,
                  "depthStencilState": {
                    "depthTest": true,
                    "depthWrite": false
                  }
                }]
              }],
              "shaders": [{
                "name": "skybox|sky-vs:vert|sky-fs:frag",
                "hash": 311136147,
                "builtins": {
                  "statistics": {
                    "CC_EFFECT_USED_VERTEX_UNIFORM_VECTORS": 37,
                    "CC_EFFECT_USED_FRAGMENT_UNIFORM_VECTORS": 37
                  },
                  "globals": {
                    "blocks": [{
                      "name": "CCGlobal",
                      "defines": []
                    }, {
                      "name": "CCCamera",
                      "defines": []
                    }],
                    "samplerTextures": [{
                      "name": "cc_environment",
                      "defines": []
                    }]
                  },
                  "locals": {
                    "blocks": [],
                    "samplerTextures": []
                  }
                },
                "defines": [{
                  "name": "CC_USE_IBL",
                  "type": "number",
                  "range": [0, 2]
                }, {
                  "name": "CC_USE_HDR",
                  "type": "boolean"
                }, {
                  "name": "USE_RGBE_CUBEMAP",
                  "type": "boolean"
                }],
                "blocks": [],
                "samplerTextures": [],
                "attributes": [{
                  "name": "a_position",
                  "type": 15,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 0
                }, {
                  "name": "a_normal",
                  "type": 15,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 1
                }, {
                  "name": "a_texCoord",
                  "type": 14,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 21,
                  "location": 2
                }, {
                  "name": "a_tangent",
                  "type": 16,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 44,
                  "location": 3
                }]
              }]
            }, {
              "name": "profiler",
              "techniques": [{
                "passes": [{
                  "blendState": {
                    "targets": [{
                      "blend": true,
                      "blendSrc": 2,
                      "blendDst": 4,
                      "blendDstAlpha": 4
                    }]
                  },
                  "rasterizerState": {
                    "cullMode": 0
                  },
                  "program": "profiler|profiler-vs:vert|profiler-fs:frag",
                  "depthStencilState": {
                    "depthTest": false,
                    "depthWrite": false
                  }
                }]
              }],
              "shaders": [{
                "name": "profiler|profiler-vs:vert|profiler-fs:frag",
                "hash": 3552712539,
                "builtins": {
                  "statistics": {
                    "CC_EFFECT_USED_VERTEX_UNIFORM_VECTORS": 58,
                    "CC_EFFECT_USED_FRAGMENT_UNIFORM_VECTORS": 37
                  },
                  "globals": {
                    "blocks": [{
                      "name": "CCGlobal",
                      "defines": []
                    }, {
                      "name": "CCCamera",
                      "defines": []
                    }],
                    "samplerTextures": []
                  },
                  "locals": {
                    "blocks": [],
                    "samplerTextures": []
                  }
                },
                "defines": [{
                  "name": "CC_USE_HDR",
                  "type": "boolean"
                }],
                "blocks": [{
                  "name": "Constants",
                  "defines": [],
                  "binding": 0,
                  "stageFlags": 1,
                  "members": [{
                    "name": "offset",
                    "type": 16,
                    "count": 1
                  }]
                }, {
                  "name": "PerFrameInfo",
                  "defines": [],
                  "binding": 1,
                  "stageFlags": 1,
                  "members": [{
                    "name": "digits",
                    "type": 16,
                    "count": 20
                  }]
                }],
                "samplerTextures": [{
                  "name": "mainTexture",
                  "type": 28,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 16,
                  "binding": 2
                }],
                "attributes": [{
                  "name": "a_position",
                  "type": 15,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 32,
                  "location": 0
                }, {
                  "name": "a_color",
                  "type": 16,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 44,
                  "location": 1
                }]
              }]
            }, {
              "name": "splash-screen",
              "techniques": [{
                "name": "default",
                "passes": [{
                  "blendState": {
                    "targets": [{
                      "blend": true,
                      "blendSrc": 2,
                      "blendDst": 4,
                      "blendDstAlpha": 4
                    }]
                  },
                  "rasterizerState": {
                    "cullMode": 0
                  },
                  "program": "splash-screen|splash-screen-vs:vert|splash-screen-fs:frag",
                  "depthStencilState": {
                    "depthTest": false,
                    "depthWrite": false
                  },
                  "properties": {
                    "mainTexture": {
                      "value": "grey",
                      "type": 28
                    },
                    "resolution": {
                      "value": [640, 960],
                      "type": 14,
                      "handleInfo": ["u_buffer0", 0, 14]
                    },
                    "precent": {
                      "value": [0.5],
                      "type": 13,
                      "handleInfo": ["u_buffer0", 2, 13]
                    },
                    "scale": {
                      "value": [200, 500],
                      "type": 14,
                      "handleInfo": ["u_buffer1", 0, 14]
                    },
                    "translate": {
                      "value": [320, 480],
                      "type": 14,
                      "handleInfo": ["u_buffer1", 2, 14]
                    },
                    "u_buffer0": {
                      "type": 16,
                      "value": [640, 960, 0.5, 0]
                    },
                    "u_buffer1": {
                      "type": 16,
                      "value": [200, 500, 320, 480]
                    }
                  }
                }]
              }],
              "shaders": [{
                "name": "splash-screen|splash-screen-vs:vert|splash-screen-fs:frag",
                "hash": 1349506124,
                "builtins": {
                  "statistics": {
                    "CC_EFFECT_USED_VERTEX_UNIFORM_VECTORS": 6,
                    "CC_EFFECT_USED_FRAGMENT_UNIFORM_VECTORS": 0
                  },
                  "globals": {
                    "blocks": [],
                    "samplerTextures": []
                  },
                  "locals": {
                    "blocks": [],
                    "samplerTextures": []
                  }
                },
                "defines": [],
                "blocks": [{
                  "name": "Constant",
                  "defines": [],
                  "binding": 0,
                  "stageFlags": 1,
                  "members": [{
                    "name": "u_buffer0",
                    "type": 16,
                    "count": 1
                  }, {
                    "name": "u_buffer1",
                    "type": 16,
                    "count": 1
                  }, {
                    "name": "u_projection",
                    "type": 25,
                    "count": 1
                  }]
                }],
                "samplerTextures": [{
                  "name": "mainTexture",
                  "type": 28,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 16,
                  "binding": 1
                }],
                "attributes": [{
                  "name": "a_position",
                  "type": 14,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 21,
                  "location": 0
                }, {
                  "name": "a_texCoord",
                  "type": 14,
                  "count": 1,
                  "defines": [],
                  "stageFlags": 1,
                  "format": 21,
                  "location": 1
                }]
              }]
            }]);

            var _type2reader, _type2writer;
            var dtMask = 0xf0000000;
            var typeMask = 0x0fc00000;
            var setMask = 0x00300000;
            var bindingMask = 0x000fc000;
            var offsetMask = 0x00003fff;
            var PropertyType;

            (function (PropertyType) {
              PropertyType[PropertyType["BUFFER"] = 0] = "BUFFER";
              PropertyType[PropertyType["TEXTURE"] = 1] = "TEXTURE";
            })(PropertyType || (PropertyType = {}));

            var genHandle = function genHandle(pt, set, binding, type, offset) {
              if (offset === void 0) {
                offset = 0;
              }

              return pt << 28 & dtMask | type << 22 & typeMask | set << 20 & setMask | binding << 14 & bindingMask | offset & offsetMask;
            };
            var getPropertyTypeFromHandle = function getPropertyTypeFromHandle(handle) {
              return (handle & dtMask) >>> 28;
            };
            var getTypeFromHandle = function getTypeFromHandle(handle) {
              return (handle & typeMask) >>> 22;
            };
            var getSetIndexFromHandle = function getSetIndexFromHandle(handle) {
              return (handle & setMask) >>> 20;
            };
            var getBindingFromHandle = function getBindingFromHandle(handle) {
              return (handle & bindingMask) >>> 14;
            };
            var getOffsetFromHandle = function getOffsetFromHandle(handle) {
              return handle & offsetMask;
            };
            var customizeType = function customizeType(handle, type) {
              return handle & ~typeMask | type << 22 & typeMask;
            };
            var type2reader = (_type2reader = {}, _type2reader[Type.UNKNOWN] = function (a, v, idx) {

              return console.warn('illegal uniform handle');
            }, _type2reader[Type.INT] = function (a, v, idx) {
              if (idx === void 0) {
                idx = 0;
              }

              return a[idx];
            }, _type2reader[Type.INT2] = function (a, v, idx) {
              if (idx === void 0) {
                idx = 0;
              }

              return Vec2.fromArray(v, a, idx);
            }, _type2reader[Type.INT3] = function (a, v, idx) {
              if (idx === void 0) {
                idx = 0;
              }

              return Vec3.fromArray(v, a, idx);
            }, _type2reader[Type.INT4] = function (a, v, idx) {
              if (idx === void 0) {
                idx = 0;
              }

              return Vec4.fromArray(v, a, idx);
            }, _type2reader[Type.FLOAT] = function (a, v, idx) {
              if (idx === void 0) {
                idx = 0;
              }

              return a[idx];
            }, _type2reader[Type.FLOAT2] = function (a, v, idx) {
              if (idx === void 0) {
                idx = 0;
              }

              return Vec2.fromArray(v, a, idx);
            }, _type2reader[Type.FLOAT3] = function (a, v, idx) {
              if (idx === void 0) {
                idx = 0;
              }

              return Vec3.fromArray(v, a, idx);
            }, _type2reader[Type.FLOAT4] = function (a, v, idx) {
              if (idx === void 0) {
                idx = 0;
              }

              return Vec4.fromArray(v, a, idx);
            }, _type2reader[Type.MAT3] = function (a, v, idx) {
              if (idx === void 0) {
                idx = 0;
              }

              return Mat3.fromArray(v, a, idx);
            }, _type2reader[Type.MAT4] = function (a, v, idx) {
              if (idx === void 0) {
                idx = 0;
              }

              return Mat4.fromArray(v, a, idx);
            }, _type2reader);
            var type2writer = (_type2writer = {}, _type2writer[Type.UNKNOWN] = function (a, v, idx) {

              return console.warn('illegal uniform handle');
            }, _type2writer[Type.INT] = function (a, v, idx) {
              if (idx === void 0) {
                idx = 0;
              }

              return a[idx] = v;
            }, _type2writer[Type.INT2] = function (a, v, idx) {
              if (idx === void 0) {
                idx = 0;
              }

              return Vec2.toArray(a, v, idx);
            }, _type2writer[Type.INT3] = function (a, v, idx) {
              if (idx === void 0) {
                idx = 0;
              }

              return Vec3.toArray(a, v, idx);
            }, _type2writer[Type.INT4] = function (a, v, idx) {
              if (idx === void 0) {
                idx = 0;
              }

              return Vec4.toArray(a, v, idx);
            }, _type2writer[Type.FLOAT] = function (a, v, idx) {
              if (idx === void 0) {
                idx = 0;
              }

              return a[idx] = v;
            }, _type2writer[Type.FLOAT2] = function (a, v, idx) {
              if (idx === void 0) {
                idx = 0;
              }

              return Vec2.toArray(a, v, idx);
            }, _type2writer[Type.FLOAT3] = function (a, v, idx) {
              if (idx === void 0) {
                idx = 0;
              }

              return Vec3.toArray(a, v, idx);
            }, _type2writer[Type.FLOAT4] = function (a, v, idx) {
              if (idx === void 0) {
                idx = 0;
              }

              return Vec4.toArray(a, v, idx);
            }, _type2writer[Type.MAT3] = function (a, v, idx) {
              if (idx === void 0) {
                idx = 0;
              }

              return Mat3.toArray(a, v, idx);
            }, _type2writer[Type.MAT4] = function (a, v, idx) {
              if (idx === void 0) {
                idx = 0;
              }

              return Mat4.toArray(a, v, idx);
            }, _type2writer);
            var defaultValues = [Object.freeze([0]), Object.freeze([0, 0]), Object.freeze([0, 0, 0, 0]), Object.freeze([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1])];
            function getDefaultFromType(type) {
              switch (type) {
                case Type.BOOL:
                case Type.INT:
                case Type.UINT:
                case Type.FLOAT:
                  return defaultValues[0];

                case Type.BOOL2:
                case Type.INT2:
                case Type.UINT2:
                case Type.FLOAT2:
                  return defaultValues[1];

                case Type.BOOL4:
                case Type.INT4:
                case Type.UINT4:
                case Type.FLOAT4:
                  return defaultValues[2];

                case Type.MAT4:
                  return defaultValues[3];

                case Type.SAMPLER2D:
                  return 'default-texture';

                case Type.SAMPLER_CUBE:
                  return 'default-cube-texture';
              }

              return defaultValues[0];
            }
            function overrideMacros(target, source) {
              var entries = Object.entries(source);
              var isDifferent = false;

              for (var i = 0; i < entries.length; i++) {
                if (target[entries[i][0]] !== entries[i][1]) {
                  target[entries[i][0]] = entries[i][1];
                  isDifferent = true;
                }
              }

              return isDifferent;
            }

            var _dsLayoutInfo = new DescriptorSetLayoutInfo();

            function getBitCount(cnt) {
              return Math.ceil(Math.log2(Math.max(cnt, 2)));
            }

            function mapDefine(info, def) {
              switch (info.type) {
                case 'boolean':
                  return typeof def === 'number' ? def.toString() : def ? '1' : '0';

                case 'string':
                  return def !== undefined ? def : info.options[0];

                case 'number':
                  return def !== undefined ? def.toString() : info.range[0].toString();

                default:
                  console.warn("unknown define type '" + info.type + "'");
                  return '-1';
              }
            }

            function prepareDefines(defs, tDefs) {
              var macros = [];

              for (var i = 0; i < tDefs.length; i++) {
                var tmpl = tDefs[i];
                var name = tmpl.name;
                var v = defs[name];

                var _value = mapDefine(tmpl, v);

                var isDefault = !v || v === '0';
                macros.push({
                  name: name,
                  value: _value,
                  isDefault: isDefault
                });
              }

              return macros;
            }

            function getShaderInstanceName(name, macros) {
              return name + macros.reduce(function (acc, cur) {
                return cur.isDefault ? acc : acc + "|" + cur.name + cur.value;
              }, '');
            }

            function insertBuiltinBindings(tmpl, tmplInfo, source, type, outBindings) {
              var target = tmpl.builtins[type];
              var tempBlocks = [];

              var _loop = function _loop(i) {
                var b = target.blocks[i];
                var info = source.layouts[b.name];
                var binding = info && source.bindings.find(function (bd) {
                  return bd.binding === info.binding;
                });

                if (!info || !binding || !(binding.descriptorType & DESCRIPTOR_BUFFER_TYPE)) {
                  console.warn("builtin UBO '" + b.name + "' not available!");
                  return "continue";
                }

                tempBlocks.push(info);
                if (outBindings && !outBindings.includes(binding)) outBindings.push(binding);
              };

              for (var i = 0; i < target.blocks.length; i++) {
                var _ret = _loop(i);

                if (_ret === "continue") continue;
              }

              Array.prototype.unshift.apply(tmplInfo.gfxBlocks, tempBlocks);
              var tempSamplerTextures = [];

              var _loop2 = function _loop2(_i) {
                var s = target.samplerTextures[_i];
                var info = source.layouts[s.name];
                var binding = info && source.bindings.find(function (bd) {
                  return bd.binding === info.binding;
                });

                if (!info || !binding || !(binding.descriptorType & DESCRIPTOR_SAMPLER_TYPE)) {
                  console.warn("builtin samplerTexture '" + s.name + "' not available!");
                  return "continue";
                }

                tempSamplerTextures.push(info);
                if (outBindings && !outBindings.includes(binding)) outBindings.push(binding);
              };

              for (var _i = 0; _i < target.samplerTextures.length; _i++) {
                var _ret2 = _loop2(_i);

                if (_ret2 === "continue") continue;
              }

              Array.prototype.unshift.apply(tmplInfo.gfxSamplerTextures, tempSamplerTextures);
              if (outBindings) outBindings.sort(function (a, b) {
                return a.binding - b.binding;
              });
            }

            function getSize(block) {
              return block.members.reduce(function (s, m) {
                return s + GetTypeSize(m.type) * m.count;
              }, 0);
            }

            function genHandles(tmpl) {
              var handleMap = {};

              for (var i = 0; i < tmpl.blocks.length; i++) {
                var block = tmpl.blocks[i];
                var members = block.members;
                var offset = 0;

                for (var j = 0; j < members.length; j++) {
                  var uniform = members[j];
                  handleMap[uniform.name] = genHandle(PropertyType.BUFFER, SetIndex.MATERIAL, block.binding, uniform.type, offset);
                  offset += (GetTypeSize(uniform.type) >> 2) * uniform.count;
                }
              }

              for (var _i2 = 0; _i2 < tmpl.samplerTextures.length; _i2++) {
                var samplerTexture = tmpl.samplerTextures[_i2];
                handleMap[samplerTexture.name] = genHandle(PropertyType.TEXTURE, SetIndex.MATERIAL, samplerTexture.binding, samplerTexture.type);
              }

              return handleMap;
            }

            function dependencyCheck(dependencies, defines) {
              for (var i = 0; i < dependencies.length; i++) {
                var d = dependencies[i];

                if (d[0] === '!') {
                  if (defines[d.slice(1)]) {
                    return false;
                  }
                } else if (!defines[d]) {
                  return false;
                }
              }

              return true;
            }

            function getActiveAttributes(tmpl, tmplInfo, defines) {
              var out = [];
              var attributes = tmpl.attributes;
              var gfxAttributes = tmplInfo.gfxAttributes;

              for (var i = 0; i < attributes.length; i++) {
                if (!dependencyCheck(attributes[i].defines, defines)) {
                  continue;
                }

                out.push(gfxAttributes[i]);
              }

              return out;
            }

            var ProgramLib = function () {
              function ProgramLib() {
                this._templates = {};
                this._cache = {};
                this._templateInfos = {};
              }

              var _proto = ProgramLib.prototype;

              _proto.register = function register(effect) {
                for (var i = 0; i < effect.shaders.length; i++) {
                  var tmpl = this.define(effect.shaders[i]);
                  tmpl.effectName = effect.name;
                }
              };

              _proto.define = function define(shader) {
                var curTmpl = this._templates[shader.name];

                if (curTmpl && curTmpl.hash === shader.hash) {
                  return curTmpl;
                }

                var tmpl = _extends({}, shader);

                var offset = 0;

                var _loop3 = function _loop3(i) {
                  var def = tmpl.defines[i];
                  var cnt = 1;

                  if (def.type === 'number') {
                    var range = def.range;
                    cnt = getBitCount(range[1] - range[0] + 1);

                    def._map = function (value) {
                      return value - range[0];
                    };
                  } else if (def.type === 'string') {
                    cnt = getBitCount(def.options.length);

                    def._map = function (value) {
                      return Math.max(0, def.options.findIndex(function (s) {
                        return s === value;
                      }));
                    };
                  } else if (def.type === 'boolean') {
                    def._map = function (value) {
                      return value ? 1 : 0;
                    };
                  }

                  def._offset = offset;
                  offset += cnt;
                };

                for (var i = 0; i < tmpl.defines.length; i++) {
                  _loop3(i);
                }

                if (offset > 31) {
                  tmpl.uber = true;
                }

                tmpl.constantMacros = '';

                for (var key in tmpl.builtins.statistics) {
                  tmpl.constantMacros += "#define " + key + " " + tmpl.builtins.statistics[key] + "\n";
                }

                this._templates[shader.name] = tmpl;

                if (!this._templateInfos[tmpl.hash]) {
                  var tmplInfo = {};
                  tmplInfo.samplerStartBinding = tmpl.blocks.length;
                  tmplInfo.gfxBlocks = [];
                  tmplInfo.gfxSamplerTextures = [];
                  tmplInfo.bindings = [];
                  tmplInfo.blockSizes = [];

                  for (var _i3 = 0; _i3 < tmpl.blocks.length; _i3++) {
                    var block = tmpl.blocks[_i3];
                    tmplInfo.blockSizes.push(getSize(block));
                    tmplInfo.bindings.push(new DescriptorSetLayoutBinding(block.binding, block.descriptorType || DescriptorType.UNIFORM_BUFFER, 1, block.stageFlags));
                    tmplInfo.gfxBlocks.push(new UniformBlock(SetIndex.MATERIAL, block.binding, block.name, block.members.map(function (m) {
                      return new Uniform(m.name, m.type, m.count);
                    }), 1));
                  }

                  for (var _i4 = 0; _i4 < tmpl.samplerTextures.length; _i4++) {
                    var samplerTexture = tmpl.samplerTextures[_i4];
                    tmplInfo.bindings.push(new DescriptorSetLayoutBinding(samplerTexture.binding, samplerTexture.descriptorType || DescriptorType.SAMPLER_TEXTURE, samplerTexture.count, samplerTexture.stageFlags));
                    tmplInfo.gfxSamplerTextures.push(new UniformSamplerTexture(SetIndex.MATERIAL, samplerTexture.binding, samplerTexture.name, samplerTexture.type, samplerTexture.count));
                  }

                  tmplInfo.gfxAttributes = [];

                  for (var _i5 = 0; _i5 < tmpl.attributes.length; _i5++) {
                    var attr = tmpl.attributes[_i5];
                    tmplInfo.gfxAttributes.push(new Attribute(attr.name, attr.format, attr.isNormalized, 0, attr.isInstanced, attr.location));
                  }

                  insertBuiltinBindings(tmpl, tmplInfo, localDescriptorSetLayout, 'locals');
                  tmplInfo.gfxStages = [];
                  tmplInfo.gfxStages.push(new ShaderStage(ShaderStageFlagBit.VERTEX, ''));
                  tmplInfo.gfxStages.push(new ShaderStage(ShaderStageFlagBit.FRAGMENT, ''));
                  tmplInfo.handleMap = genHandles(tmpl);
                  tmplInfo.hPipelineLayout = NULL_HANDLE;
                  tmplInfo.setLayouts = [];
                  this._templateInfos[tmpl.hash] = tmplInfo;
                }

                return tmpl;
              };

              _proto.getTemplate = function getTemplate(name) {
                return this._templates[name];
              };

              _proto.getTemplateInfo = function getTemplateInfo(name) {
                var hash = this._templates[name].hash;
                return this._templateInfos[hash];
              };

              _proto.getDescriptorSetLayout = function getDescriptorSetLayout(device, name, isLocal) {
                if (isLocal === void 0) {
                  isLocal = false;
                }

                var tmpl = this._templates[name];
                var tmplInfo = this._templateInfos[tmpl.hash];

                if (!tmplInfo.setLayouts.length) {
                  _dsLayoutInfo.bindings = tmplInfo.bindings;
                  tmplInfo.setLayouts[SetIndex.MATERIAL] = device.createDescriptorSetLayout(_dsLayoutInfo);
                  _dsLayoutInfo.bindings = localDescriptorSetLayout.bindings;
                  tmplInfo.setLayouts[SetIndex.LOCAL] = device.createDescriptorSetLayout(_dsLayoutInfo);
                }

                return tmplInfo.setLayouts[isLocal ? SetIndex.LOCAL : SetIndex.MATERIAL];
              };

              _proto.hasProgram = function hasProgram(name) {
                return this._templates[name] !== undefined;
              };

              _proto.getKey = function getKey(name, defines) {
                var tmpl = this._templates[name];
                var tmplDefs = tmpl.defines;

                if (tmpl.uber) {
                  var _key = '';

                  for (var i = 0; i < tmplDefs.length; i++) {
                    var tmplDef = tmplDefs[i];
                    var _value2 = defines[tmplDef.name];

                    if (!_value2 || !tmplDef._map) {
                      continue;
                    }

                    var mapped = tmplDef._map(_value2);

                    var offset = tmplDef._offset;
                    _key += "" + offset + mapped + "|";
                  }

                  return "" + _key + tmpl.hash;
                }

                var key = 0;

                for (var _i6 = 0; _i6 < tmplDefs.length; _i6++) {
                  var _tmplDef = tmplDefs[_i6];
                  var _value3 = defines[_tmplDef.name];

                  if (!_value3 || !_tmplDef._map) {
                    continue;
                  }

                  var _mapped = _tmplDef._map(_value3);

                  var _offset = _tmplDef._offset;
                  key |= _mapped << _offset;
                }

                return key.toString(16) + "|" + tmpl.hash;
              };

              _proto.destroyShaderByDefines = function destroyShaderByDefines(defines) {
                var _this = this;

                var names = Object.keys(defines);

                if (!names.length) {
                  return;
                }

                var regexes = names.map(function (cur) {
                  var val = defines[cur];

                  if (typeof val === 'boolean') {
                    val = val ? '1' : '0';
                  }

                  return new RegExp("" + cur + val);
                });
                var keys = Object.keys(this._cache).filter(function (k) {
                  return regexes.every(function (re) {
                    return re.test(ShaderPool.get(_this._cache[k]).name);
                  });
                });

                for (var i = 0; i < keys.length; i++) {
                  var k = keys[i];
                  var prog = ShaderPool.get(this._cache[k]);
                  console.log("destroyed shader " + prog.name);
                  prog.destroy();
                  delete this._cache[k];
                }
              };

              _proto.getGFXShader = function getGFXShader(device, name, defines, pipeline, key) {
                Object.assign(defines, pipeline.macros);
                if (!key) key = this.getKey(name, defines);
                var res = this._cache[key];

                if (res) {
                  return res;
                }

                var tmpl = this._templates[name];
                var tmplInfo = this._templateInfos[tmpl.hash];

                if (!tmplInfo.hPipelineLayout) {
                  this.getDescriptorSetLayout(device, name);
                  insertBuiltinBindings(tmpl, tmplInfo, globalDescriptorSetLayout, 'globals');
                  tmplInfo.setLayouts[SetIndex.GLOBAL] = pipeline.descriptorSetLayout;
                  tmplInfo.hPipelineLayout = PipelineLayoutPool.alloc(device, new PipelineLayoutInfo(tmplInfo.setLayouts));
                }

                var macroArray = prepareDefines(defines, tmpl.defines);
                var prefix = pipeline.constantMacros + tmpl.constantMacros + macroArray.reduce(function (acc, cur) {
                  return acc + "#define " + cur.name + " " + cur.value + "\n";
                }, '');
                var src = tmpl.glsl3;
                var deviceShaderVersion = getDeviceShaderVersion(device);

                if (deviceShaderVersion) {
                  src = tmpl[deviceShaderVersion];
                } else {
                  console.error('Invalid GFX API!');
                }

                tmplInfo.gfxStages[0].source = prefix + src.vert;
                tmplInfo.gfxStages[1].source = prefix + src.frag;
                var attributes = getActiveAttributes(tmpl, tmplInfo, defines);
                var instanceName = getShaderInstanceName(name, macroArray);
                var shaderInfo = new ShaderInfo(instanceName, tmplInfo.gfxStages, attributes, tmplInfo.gfxBlocks);
                shaderInfo.samplerTextures = tmplInfo.gfxSamplerTextures;
                return this._cache[key] = ShaderPool.alloc(device, shaderInfo);
              };

              return ProgramLib;
            }();

            function getDeviceShaderVersion(device) {
              switch (device.gfxAPI) {
                case API.GLES2:
                case API.WEBGL:
                  return 'glsl1';

                case API.GLES3:
                case API.WEBGL2:
                  return 'glsl3';

                default:
                  return 'glsl4';
              }
            }
            var programLib = new ProgramLib();
            legacyCC.programLib = programLib;

            var glsl1 = [[{
              "vert": "\nprecision mediump float;\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matViewInv;\nuniform highp mat4 cc_matViewProj;\nuniform highp mat4 cc_matWorld;\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\nmat3 m = mat3(xAxis,yAxis,zAxis);\nfloat trace = m[0][0] + m[1][1] + m[2][2];\nvec4 quat;\nif (trace > 0.) {\nfloat s = 0.5 / sqrt(trace + 1.0);\nquat.w = 0.25 / s;\nquat.x = (m[2][1] - m[1][2]) * s;\nquat.y = (m[0][2] - m[2][0]) * s;\nquat.z = (m[1][0] - m[0][1]) * s;\n} else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\nfloat s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\nquat.w = (m[2][1] - m[1][2]) / s;\nquat.x = 0.25 * s;\nquat.y = (m[0][1] + m[1][0]) / s;\nquat.z = (m[0][2] + m[2][0]) / s;\n} else if (m[1][1] > m[2][2]) {\nfloat s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\nquat.w = (m[0][2] - m[2][0]) / s;\nquat.x = (m[0][1] + m[1][0]) / s;\nquat.y = 0.25 * s;\nquat.z = (m[1][2] + m[2][1]) / s;\n} else {\nfloat s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\nquat.w = (m[1][0] - m[0][1]) / s;\nquat.x = (m[0][2] + m[2][0]) / s;\nquat.y = (m[1][2] + m[2][1]) / s;\nquat.z = 0.25 * s;\n}\nfloat len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\nif (len > 0.) {\nlen = 1. / sqrt(len);\nquat.x = quat.x * len;\nquat.y = quat.y * len;\nquat.z = quat.z * len;\nquat.w = quat.w * len;\n}\nreturn quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\nfloat x = angle.x / 2.;\nfloat y = angle.y / 2.;\nfloat z = angle.z / 2.;\nfloat sx = sin(x);\nfloat cx = cos(x);\nfloat sy = sin(y);\nfloat cy = cos(y);\nfloat sz = sin(z);\nfloat cz = cos(z);\nvec4 quat = vec4(0);\nquat.x = sx * cy * cz + cx * sy * sz;\nquat.y = cx * sy * cz + sx * cy * sz;\nquat.z = cx * cy * sz - sx * sy * cz;\nquat.w = cx * cy * cz - sx * sy * sz;\nreturn quat;\n}\nvec4 quatMultiply (vec4 a, vec4 b){\nvec4 quat;\nquat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\nquat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\nquat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\nquat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\nreturn quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\nfloat ix = q.w * v.x + q.y * v.z - q.z * v.y;\nfloat iy = q.w * v.y + q.z * v.x - q.x * v.z;\nfloat iz = q.w * v.z + q.x * v.y - q.y * v.x;\nfloat iw = -q.x * v.x - q.y * v.y - q.z * v.z;\nv.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\nv.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\nv.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\nvec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\nvec4 rotQuat = quatMultiply(viewQuat, q);\nrotateVecFromQuat(pos, rotQuat);\nreturn pos;\n}\nvoid rotateCorner (inout vec2 corner, float angle){\nfloat xOS = cos(angle) * corner.x - sin(angle) * corner.y;\nfloat yOS = sin(angle) * corner.x + cos(angle) * corner.y;\ncorner.x = xOS;\ncorner.y = yOS;\n}\nvarying mediump vec2 uv;\nvarying mediump vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n, mat4 viewInv\n) {\nvec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\nvec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\nvec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\nvec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\npos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n}\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\nuniform vec4 cc_size_rotation;\nvec4 vs_main() {\nvec4 pos = vec4(a_position, 1);\npos = cc_matWorld * pos;\nvec2 vertOffset = a_texCoord.xy - 0.5;\ncomputeVertPos(pos, vertOffset, quaternionFromEuler(vec3(0., 0., cc_size_rotation.z)), vec3(cc_size_rotation.xy, 0.), cc_matViewInv);\npos = cc_matViewProj * pos;\nuv = a_texCoord.xy;\ncolor = a_color;\nreturn pos;\n}\nvoid main() { gl_Position = vs_main(); }",
              "frag": "\nprecision mediump float;\nuniform mediump vec4 cc_exposure;\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n#if CC_USE_HDR\ncolor.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n#endif\nreturn color;\n}\nvarying vec2 uv;\nvarying vec4 color;\nuniform sampler2D mainTexture;\nuniform vec4 tintColor;\nvec4 add () {\nvec4 col = 2.0 * color * tintColor * texture2D(mainTexture, uv);\nreturn CCFragOutput(col);\n}\nvoid main() { gl_FragColor = add(); }"
            }], [{
              "vert": "\nprecision highp float;\nattribute vec3 a_position;\nvec4 vert () {\nvec4 pos = vec4(a_position, 1);\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }",
              "frag": "\nprecision highp float;\nvec4 frag () {\nvec4 o = vec4(1.0);\nreturn o;\n}\nvoid main() { gl_FragColor = frag(); }"
            }], [{
              "vert": "\nprecision highp float;\nuniform highp mat4 cc_matViewProj;\nuniform highp mat4 cc_matWorld;\nattribute vec3 a_position;\nattribute vec4 a_color;\nvarying vec4 v_color;\nattribute float a_dist;\nvarying float v_dist;\nvec4 vert () {\nvec4 pos = vec4(a_position, 1);\npos = cc_matViewProj * cc_matWorld * pos;\nv_color = a_color;\nv_dist = a_dist;\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }",
              "frag": "\n#ifdef GL_OES_standard_derivatives\n#extension GL_OES_standard_derivatives: enable\n#endif\nprecision highp float;\nvarying vec4 v_color;\nvarying float v_dist;\nvec4 frag () {\nvec4 o = v_color;\n#ifdef GL_OES_standard_derivatives\nfloat aa = fwidth(v_dist);\n#else\nfloat aa = 0.05;\n#endif\nfloat alpha = 1. - smoothstep(-aa, 0., abs(v_dist) - 1.0);\no.rgb *= o.a;\no *= alpha;\nreturn o;\n}\nvoid main() { gl_FragColor = frag(); }"
            }], [{
              "vert": "\nprecision mediump float;\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\nmat3 m = mat3(xAxis,yAxis,zAxis);\nfloat trace = m[0][0] + m[1][1] + m[2][2];\nvec4 quat;\nif (trace > 0.) {\nfloat s = 0.5 / sqrt(trace + 1.0);\nquat.w = 0.25 / s;\nquat.x = (m[2][1] - m[1][2]) * s;\nquat.y = (m[0][2] - m[2][0]) * s;\nquat.z = (m[1][0] - m[0][1]) * s;\n} else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\nfloat s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\nquat.w = (m[2][1] - m[1][2]) / s;\nquat.x = 0.25 * s;\nquat.y = (m[0][1] + m[1][0]) / s;\nquat.z = (m[0][2] + m[2][0]) / s;\n} else if (m[1][1] > m[2][2]) {\nfloat s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\nquat.w = (m[0][2] - m[2][0]) / s;\nquat.x = (m[0][1] + m[1][0]) / s;\nquat.y = 0.25 * s;\nquat.z = (m[1][2] + m[2][1]) / s;\n} else {\nfloat s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\nquat.w = (m[1][0] - m[0][1]) / s;\nquat.x = (m[0][2] + m[2][0]) / s;\nquat.y = (m[1][2] + m[2][1]) / s;\nquat.z = 0.25 * s;\n}\nfloat len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\nif (len > 0.) {\nlen = 1. / sqrt(len);\nquat.x = quat.x * len;\nquat.y = quat.y * len;\nquat.z = quat.z * len;\nquat.w = quat.w * len;\n}\nreturn quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\nfloat x = angle.x / 2.;\nfloat y = angle.y / 2.;\nfloat z = angle.z / 2.;\nfloat sx = sin(x);\nfloat cx = cos(x);\nfloat sy = sin(y);\nfloat cy = cos(y);\nfloat sz = sin(z);\nfloat cz = cos(z);\nvec4 quat = vec4(0);\nquat.x = sx * cy * cz + cx * sy * sz;\nquat.y = cx * sy * cz + sx * cy * sz;\nquat.z = cx * cy * sz - sx * sy * cz;\nquat.w = cx * cy * cz - sx * sy * sz;\nreturn quat;\n}\nmat4 matrixFromRT (vec4 q, vec3 p){\nfloat x2 = q.x + q.x;\nfloat y2 = q.y + q.y;\nfloat z2 = q.z + q.z;\nfloat xx = q.x * x2;\nfloat xy = q.x * y2;\nfloat xz = q.x * z2;\nfloat yy = q.y * y2;\nfloat yz = q.y * z2;\nfloat zz = q.z * z2;\nfloat wx = q.w * x2;\nfloat wy = q.w * y2;\nfloat wz = q.w * z2;\nreturn mat4(\n1. - (yy + zz), xy + wz, xz - wy, 0,\nxy - wz, 1. - (xx + zz), yz + wx, 0,\nxz + wy, yz - wx, 1. - (xx + yy), 0,\np.x, p.y, p.z, 1\n);\n}\nmat4 matFromRTS (vec4 q, vec3 t, vec3 s){\nfloat x = q.x, y = q.y, z = q.z, w = q.w;\nfloat x2 = x + x;\nfloat y2 = y + y;\nfloat z2 = z + z;\nfloat xx = x * x2;\nfloat xy = x * y2;\nfloat xz = x * z2;\nfloat yy = y * y2;\nfloat yz = y * z2;\nfloat zz = z * z2;\nfloat wx = w * x2;\nfloat wy = w * y2;\nfloat wz = w * z2;\nfloat sx = s.x;\nfloat sy = s.y;\nfloat sz = s.z;\nreturn mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n(xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n(xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\nt.x, t.y, t.z, 1);\n}\nvec4 quatMultiply (vec4 a, vec4 b){\nvec4 quat;\nquat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\nquat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\nquat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\nquat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\nreturn quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\nfloat ix = q.w * v.x + q.y * v.z - q.z * v.y;\nfloat iy = q.w * v.y + q.z * v.x - q.x * v.z;\nfloat iz = q.w * v.z + q.x * v.y - q.y * v.x;\nfloat iw = -q.x * v.x - q.y * v.y - q.z * v.z;\nv.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\nv.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\nv.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\nvec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\nvec4 rotQuat = quatMultiply(viewQuat, q);\nrotateVecFromQuat(pos, rotQuat);\nreturn pos;\n}\nvoid rotateCorner (inout vec2 corner, float angle){\nfloat xOS = cos(angle) * corner.x - sin(angle) * corner.y;\nfloat yOS = sin(angle) * corner.x + cos(angle) * corner.y;\ncorner.x = xOS;\ncorner.y = yOS;\n}\nuniform vec4 mainTiling_Offset;\nuniform vec4 frameTile_velLenScale;\nuniform vec4 scale;\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matViewInv;\nuniform highp mat4 cc_matViewProj;\nuniform highp vec4 cc_cameraPos;\nuniform highp mat4 cc_matWorld;\nvarying mediump vec2 uv;\nvarying mediump vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if CC_RENDER_MODE == 0 || CC_RENDER_MODE == 3\n, mat4 viewInv\n#endif\n#if CC_RENDER_MODE == 1\n, vec3 eye\n, vec4 velocity\n, float velocityScale\n, float lengthScale\n, float xIndex\n#endif\n) {\n#if CC_RENDER_MODE == 0\nvec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\nvec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\nvec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\nvec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\npos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_RENDER_MODE == 1\nvec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\nvec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\npos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_RENDER_MODE == 2\nvec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\nvec3 camX = vec3(1, 0, 0);\nvec3 camY = vec3(0, 0, -1);\npos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_RENDER_MODE == 3\nvec2 viewSpaceVert = vec2(vertOffset.x * s.x, vertOffset.y * s.y);\nrotateCorner(viewSpaceVert, q.z);\nvec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\nvec3 camY = vec3(0, 1, 0);\nvec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\npos.xyz += offset;\n#else\npos.x += vertOffset.x;\npos.y += vertOffset.y;\n#endif\n}\nvec2 computeUV (float frameIndex, vec2 vertIndex, vec2 frameTile){\nvec2 aniUV = vec2(0, floor(frameIndex * frameTile.y));\naniUV.x = floor(frameIndex * frameTile.x * frameTile.y - aniUV.y * frameTile.x);\n#if CC_RENDER_MODE != 4\nvertIndex.y = 1. - vertIndex.y;\n#endif\nreturn (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nuniform vec4 u_sampleInfo;\nuniform vec4 u_worldRot;\nuniform vec4 u_timeDelta;\nattribute vec4 a_position_starttime;\nattribute vec4 a_size_uv;\nattribute vec4 a_rotation_uv;\nattribute vec4 a_color;\nattribute vec4 a_dir_life;\nattribute float a_rndSeed;\n#if CC_RENDER_MODE == 4\nattribute vec3 a_texCoord;\nattribute vec3 a_texCoord3;\nattribute vec3 a_normal;\nattribute vec4 a_color1;\n#endif\nvec3 unpackCurveData (sampler2D tex, vec2 coord) {\nvec4 a = texture2D(tex, coord);\nvec4 b = texture2D(tex, coord + u_sampleInfo.y);\nfloat c = fract(coord.x * u_sampleInfo.x);\nreturn mix(a.xyz, b.xyz, c);\n}\nvec3 unpackCurveData (sampler2D tex, vec2 coord, out float w) {\nvec4 a = texture2D(tex, coord);\nvec4 b = texture2D(tex, coord + u_sampleInfo.y);\nfloat c = fract(coord.x * u_sampleInfo.x);\nw = mix(a.w, b.w, c);\nreturn mix(a.xyz, b.xyz, c);\n}\nfloat pseudoRandom (float seed) {\nseed = mod(seed, 233280.);\nfloat q = (seed * 9301. + 49297.) / 233280.;\nreturn fract(q);\n}\n#if COLOR_OVER_TIME_MODULE_ENABLE\nuniform sampler2D color_over_time_tex0;\nuniform int u_color_mode;\n#endif\n#if ROTATION_OVER_TIME_MODULE_ENABLE\nuniform sampler2D rotation_over_time_tex0;\nuniform int u_rotation_mode;\n#endif\n#if SIZE_OVER_TIME_MODULE_ENABLE\nuniform sampler2D size_over_time_tex0;\nuniform int u_size_mode;\n#endif\n#if FORCE_OVER_TIME_MODULE_ENABLE\nuniform sampler2D force_over_time_tex0;\nuniform int u_force_mode;\nuniform int u_force_space;\n#endif\n#if VELOCITY_OVER_TIME_MODULE_ENABLE\nuniform sampler2D velocity_over_time_tex0;\nuniform int u_velocity_mode;\nuniform int u_velocity_space;\n#endif\n#if TEXTURE_ANIMATION_MODULE_ENABLE\nuniform sampler2D texture_animation_tex0;\nuniform vec4 u_anim_info;\n#endif\nfloat repeat (float t, float length) {\nreturn t - floor(t / length) * length;\n}\nvec4 rotateQuat (vec4 p, vec4 q) {\nvec3 iv = cross(q.xyz, p.xyz) + q.w * p.xyz;\nvec3 res = p.xyz + 2.0 * cross(q.xyz, iv);\nreturn vec4(res.xyz, p.w);\n}\nvec4 gpvs_main () {\nfloat activeTime = u_timeDelta.x - a_position_starttime.w;\nfloat normalizedTime = clamp(activeTime / a_dir_life.w, 0.0, 1.0);\nvec2 timeCoord0 = vec2(normalizedTime, 0.);\nvec2 timeCoord1 = vec2(normalizedTime, 1.);\n#if CC_RENDER_MODE == 4\nvec2 vertIdx = vec2(a_texCoord.x, a_texCoord.y);\n#else\nvec2 vertIdx = vec2(a_size_uv.w, a_rotation_uv.w);\n#endif\nvec4 velocity = vec4(a_dir_life.xyz, 0.);\nvec4 pos = vec4(a_position_starttime.xyz, 1.);\nvec3 size = a_size_uv.xyz;\n#if SIZE_OVER_TIME_MODULE_ENABLE\nif (u_size_mode == 1) {\nsize *= unpackCurveData(size_over_time_tex0, timeCoord0);\n} else {\nvec3 size_0 = unpackCurveData(size_over_time_tex0, timeCoord0);\nvec3 size_1 = unpackCurveData(size_over_time_tex0, timeCoord1);\nfloat factor_s = pseudoRandom(a_rndSeed + 39825.);\nsize *= mix(size_0, size_1, factor_s);\n}\n#endif\nvec3 compScale = scale.xyz * size;\n#if FORCE_OVER_TIME_MODULE_ENABLE\nvec3 forceAnim = vec3(0.);\nif (u_force_mode == 1) {\nforceAnim = unpackCurveData(force_over_time_tex0, timeCoord0);\n} else {\nvec3 force_0 = unpackCurveData(force_over_time_tex0, timeCoord0);\nvec3 force_1 = unpackCurveData(force_over_time_tex0, timeCoord1);\nfloat factor_f =  pseudoRandom(a_rndSeed + 212165.);\nforceAnim = mix(force_0, force_1, factor_f);\n}\nvec4 forceTrack = vec4(forceAnim, 0.);\nif (u_force_space == 0) {\nforceTrack = rotateQuat(forceTrack, u_worldRot);\n}\nvelocity.xyz += forceTrack.xyz;\n#endif\n#if VELOCITY_OVER_TIME_MODULE_ENABLE\nfloat speedModifier0 = 1.;\nfloat speedModifier1 = 1.;\nvec3 velocityAnim = vec3(0.);\nif (u_velocity_mode == 1) {\nvelocityAnim = unpackCurveData(velocity_over_time_tex0, timeCoord0, speedModifier0);\n} else {\nvec3 vectory_0 = unpackCurveData(velocity_over_time_tex0, timeCoord0, speedModifier0);\nvec3 vectory_1 = unpackCurveData(velocity_over_time_tex0, timeCoord1, speedModifier1);\nfloat factor_v = pseudoRandom(a_rndSeed + 197866.);\nvelocityAnim = mix(vectory_0, vectory_1, factor_v);\nspeedModifier0 = mix(speedModifier0, speedModifier1, factor_v);\n}\nvec4 velocityTrack = vec4(velocityAnim, 0.);\nif (u_velocity_space == 0) {\nvelocityTrack = rotateQuat(velocityTrack, u_worldRot);\n}\nvelocity.xyz += velocityTrack.xyz;\nvelocity.xyz *= speedModifier0;\n#endif\npos.xyz += velocity.xyz * normalizedTime * a_dir_life.w;\n#if !CC_USE_WORLD_SPACE\npos = cc_matWorld * pos;\n#if CC_RENDER_MODE == 1\nvelocity = rotateQuat(velocity, u_worldRot);\n#endif\n#endif\nvec3 rotation = a_rotation_uv.xyz;\n#if ROTATION_OVER_TIME_MODULE_ENABLE\nif (u_rotation_mode == 1) {\nrotation += unpackCurveData(rotation_over_time_tex0, timeCoord0) * normalizedTime * a_dir_life.w;\n} else {\nvec3 rotation_0 = unpackCurveData(rotation_over_time_tex0, timeCoord0);\nvec3 rotation_1 = unpackCurveData(rotation_over_time_tex0, timeCoord1);\nfloat factor_r = pseudoRandom(a_rndSeed + 125292.);\nrotation += mix(rotation_0, rotation_1, factor_r) * normalizedTime * a_dir_life.w;\n}\n#endif\n#if COLOR_OVER_TIME_MODULE_ENABLE\nif (u_color_mode == 1) {\ncolor = a_color * texture2D(color_over_time_tex0, timeCoord0);\n} else {\nvec4 color_0 = texture2D(color_over_time_tex0, timeCoord0);\nvec4 color_1 = texture2D(color_over_time_tex0, timeCoord1);\nfloat factor_c = pseudoRandom(a_rndSeed + 91041.);\ncolor = a_color * mix(color_0, color_1, factor_c);\n}\n#else\ncolor = a_color;\n#endif\n#if CC_RENDER_MODE != 4\nvec2 cornerOffset = vec2((vertIdx - 0.5));\n#if CC_RENDER_MODE == 0\nvec3 rotEuler = rotation.xyz;\n#elif CC_RENDER_MODE == 1\nvec3 rotEuler = vec3(0.);\n#else\nvec3 rotEuler = vec3(0., 0., rotation.z);\n#endif\ncomputeVertPos(pos, cornerOffset, quaternionFromEuler(rotEuler), compScale\n#if CC_RENDER_MODE == 0 || CC_RENDER_MODE == 3\n, cc_matViewInv\n#endif\n#if CC_RENDER_MODE == 1\n, cc_cameraPos.xyz\n, velocity\n, frameTile_velLenScale.z\n, frameTile_velLenScale.w\n, a_size_uv.w\n#endif\n);\n#else\nmat4 xformNoScale = matrixFromRT(quaternionFromEuler(rotation), pos.xyz);\nmat4 xform = matFromRTS(quaternionFromEuler(rotation), pos.xyz, compScale);\npos = xform * vec4(a_texCoord3, 1);\nvec4 normal = xformNoScale * vec4(a_normal, 0);\ncolor *= a_color1;\n#endif\npos = cc_matViewProj * pos;\nfloat frameIndex = 0.;\n#if TEXTURE_ANIMATION_MODULE_ENABLE\nfloat startFrame = 0.;\nvec3 frameInfo = vec3(0.);\nif (int(u_anim_info.x) == 1) {\nframeInfo = unpackCurveData(texture_animation_tex0, timeCoord0);\n} else {\nvec3 frameInfo0 = unpackCurveData(texture_animation_tex0, timeCoord0);\nvec3 frameInfo1 = unpackCurveData(texture_animation_tex0, timeCoord1);\nfloat factor_t = pseudoRandom(a_rndSeed + 90794.);\nframeInfo = mix(frameInfo0, frameInfo1, factor_t);\n}\nstartFrame = frameInfo.x / u_anim_info.y;\nframeIndex = repeat(u_anim_info.z * (frameInfo.y + startFrame), 1.);\n#endif\nuv = computeUV(frameIndex, vertIdx, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw;\nreturn pos;\n}\nvoid main() { gl_Position = gpvs_main(); }",
              "frag": "\nprecision mediump float;\nuniform mediump vec4 cc_exposure;\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n#if CC_USE_HDR\ncolor.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n#endif\nreturn color;\n}\nvarying vec2 uv;\nvarying vec4 color;\nuniform sampler2D mainTexture;\nuniform vec4 tintColor;\nvec4 add () {\nvec4 col = 2.0 * color * tintColor * texture2D(mainTexture, uv);\nreturn CCFragOutput(col);\n}\nvoid main() { gl_FragColor = add(); }"
            }], [{
              "vert": "\nprecision mediump float;\nuniform vec4 mainTiling_Offset;\nuniform highp mat4 cc_matViewProj;\nuniform highp vec4 cc_cameraPos;\nuniform highp mat4 cc_matWorld;\nvarying mediump vec2 uv;\nvarying mediump vec4 color;\nattribute vec3 a_position;\nattribute vec4 a_texCoord;\nattribute vec3 a_texCoord1;\nattribute vec3 a_texCoord2;\nattribute vec4 a_color;\n#if CC_DRAW_WIRE_FRAME\nvarying vec3 vBarycentric;\n#endif\nvec4 vs_main() {\nhighp vec4 pos = vec4(a_position, 1);\nvec4 velocity = vec4(a_texCoord1.xyz, 0);\n#if !CC_USE_WORLD_SPACE\npos = cc_matWorld * pos;\nvelocity = cc_matWorld * velocity;\n#endif\nfloat vertOffset = (a_texCoord.x - 0.5) * a_texCoord.y;\nvec3 camUp = normalize(cross(pos.xyz - cc_cameraPos.xyz, velocity.xyz));\npos.xyz += camUp * vertOffset;\npos = cc_matViewProj * pos;\nuv = a_texCoord.zw * mainTiling_Offset.xy + mainTiling_Offset.zw;;\ncolor = a_color;\n#if CC_DRAW_WIRE_FRAME\nvBarycentric = a_texCoord2;\n#endif\nreturn pos;\n}\nvoid main() { gl_Position = vs_main(); }",
              "frag": "\nprecision mediump float;\nuniform mediump vec4 cc_exposure;\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n#if CC_USE_HDR\ncolor.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n#endif\nreturn color;\n}\nvarying vec2 uv;\nvarying vec4 color;\n#if CC_DRAW_WIRE_FRAME\nvarying vec3 vBarycentric;\n#endif\nuniform sampler2D mainTexture;\nuniform vec4 tintColor;\nvec4 add () {\nvec4 col = 2.0 * color * tintColor * texture2D(mainTexture, uv);\n#if CC_DRAW_WIRE_FRAME\nif (any(lessThan(vBarycentric, vec3(0.02)))) {\ncol = vec4(0., 1., 1., 1.);\n}\n#endif\nreturn CCFragOutput(col);\n}\nvoid main() { gl_FragColor = add(); }"
            }], [{
              "vert": "\nprecision highp float;\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\nmat3 m = mat3(xAxis,yAxis,zAxis);\nfloat trace = m[0][0] + m[1][1] + m[2][2];\nvec4 quat;\nif (trace > 0.) {\nfloat s = 0.5 / sqrt(trace + 1.0);\nquat.w = 0.25 / s;\nquat.x = (m[2][1] - m[1][2]) * s;\nquat.y = (m[0][2] - m[2][0]) * s;\nquat.z = (m[1][0] - m[0][1]) * s;\n} else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\nfloat s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\nquat.w = (m[2][1] - m[1][2]) / s;\nquat.x = 0.25 * s;\nquat.y = (m[0][1] + m[1][0]) / s;\nquat.z = (m[0][2] + m[2][0]) / s;\n} else if (m[1][1] > m[2][2]) {\nfloat s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\nquat.w = (m[0][2] - m[2][0]) / s;\nquat.x = (m[0][1] + m[1][0]) / s;\nquat.y = 0.25 * s;\nquat.z = (m[1][2] + m[2][1]) / s;\n} else {\nfloat s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\nquat.w = (m[1][0] - m[0][1]) / s;\nquat.x = (m[0][2] + m[2][0]) / s;\nquat.y = (m[1][2] + m[2][1]) / s;\nquat.z = 0.25 * s;\n}\nfloat len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\nif (len > 0.) {\nlen = 1. / sqrt(len);\nquat.x = quat.x * len;\nquat.y = quat.y * len;\nquat.z = quat.z * len;\nquat.w = quat.w * len;\n}\nreturn quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\nfloat x = angle.x / 2.;\nfloat y = angle.y / 2.;\nfloat z = angle.z / 2.;\nfloat sx = sin(x);\nfloat cx = cos(x);\nfloat sy = sin(y);\nfloat cy = cos(y);\nfloat sz = sin(z);\nfloat cz = cos(z);\nvec4 quat = vec4(0);\nquat.x = sx * cy * cz + cx * sy * sz;\nquat.y = cx * sy * cz + sx * cy * sz;\nquat.z = cx * cy * sz - sx * sy * cz;\nquat.w = cx * cy * cz - sx * sy * sz;\nreturn quat;\n}\nmat4 matrixFromRT (vec4 q, vec3 p){\nfloat x2 = q.x + q.x;\nfloat y2 = q.y + q.y;\nfloat z2 = q.z + q.z;\nfloat xx = q.x * x2;\nfloat xy = q.x * y2;\nfloat xz = q.x * z2;\nfloat yy = q.y * y2;\nfloat yz = q.y * z2;\nfloat zz = q.z * z2;\nfloat wx = q.w * x2;\nfloat wy = q.w * y2;\nfloat wz = q.w * z2;\nreturn mat4(\n1. - (yy + zz), xy + wz, xz - wy, 0,\nxy - wz, 1. - (xx + zz), yz + wx, 0,\nxz + wy, yz - wx, 1. - (xx + yy), 0,\np.x, p.y, p.z, 1\n);\n}\nmat4 matFromRTS (vec4 q, vec3 t, vec3 s){\nfloat x = q.x, y = q.y, z = q.z, w = q.w;\nfloat x2 = x + x;\nfloat y2 = y + y;\nfloat z2 = z + z;\nfloat xx = x * x2;\nfloat xy = x * y2;\nfloat xz = x * z2;\nfloat yy = y * y2;\nfloat yz = y * z2;\nfloat zz = z * z2;\nfloat wx = w * x2;\nfloat wy = w * y2;\nfloat wz = w * z2;\nfloat sx = s.x;\nfloat sy = s.y;\nfloat sz = s.z;\nreturn mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n(xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n(xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\nt.x, t.y, t.z, 1);\n}\nvec4 quatMultiply (vec4 a, vec4 b){\nvec4 quat;\nquat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\nquat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\nquat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\nquat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\nreturn quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\nfloat ix = q.w * v.x + q.y * v.z - q.z * v.y;\nfloat iy = q.w * v.y + q.z * v.x - q.x * v.z;\nfloat iz = q.w * v.z + q.x * v.y - q.y * v.x;\nfloat iw = -q.x * v.x - q.y * v.y - q.z * v.z;\nv.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\nv.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\nv.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\nvec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\nvec4 rotQuat = quatMultiply(viewQuat, q);\nrotateVecFromQuat(pos, rotQuat);\nreturn pos;\n}\nvoid rotateCorner (inout vec2 corner, float angle){\nfloat xOS = cos(angle) * corner.x - sin(angle) * corner.y;\nfloat yOS = sin(angle) * corner.x + cos(angle) * corner.y;\ncorner.x = xOS;\ncorner.y = yOS;\n}\nuniform vec4 mainTiling_Offset;\nuniform vec4 frameTile_velLenScale;\nuniform vec4 scale;\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matViewInv;\nuniform highp mat4 cc_matViewProj;\nuniform highp vec4 cc_cameraPos;\nuniform highp mat4 cc_matWorld;\nvarying mediump vec2 uv;\nvarying mediump vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if CC_RENDER_MODE == 0 || CC_RENDER_MODE == 3\n, mat4 viewInv\n#endif\n#if CC_RENDER_MODE == 1\n, vec3 eye\n, vec4 velocity\n, float velocityScale\n, float lengthScale\n, float xIndex\n#endif\n) {\n#if CC_RENDER_MODE == 0\nvec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\nvec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\nvec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\nvec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\npos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_RENDER_MODE == 1\nvec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\nvec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\npos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_RENDER_MODE == 2\nvec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\nvec3 camX = vec3(1, 0, 0);\nvec3 camY = vec3(0, 0, -1);\npos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_RENDER_MODE == 3\nvec2 viewSpaceVert = vec2(vertOffset.x * s.x, vertOffset.y * s.y);\nrotateCorner(viewSpaceVert, q.z);\nvec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\nvec3 camY = vec3(0, 1, 0);\nvec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\npos.xyz += offset;\n#else\npos.x += vertOffset.x;\npos.y += vertOffset.y;\n#endif\n}\nvec2 computeUV (float frameIndex, vec2 vertIndex, vec2 frameTile){\nvec2 aniUV = vec2(0, floor(frameIndex * frameTile.y));\naniUV.x = floor(frameIndex * frameTile.x * frameTile.y - aniUV.y * frameTile.x);\n#if CC_RENDER_MODE != 4\nvertIndex.y = 1. - vertIndex.y;\n#endif\nreturn (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nattribute vec3 a_position;\nattribute vec3 a_texCoord;\nattribute vec3 a_texCoord1;\nattribute vec3 a_texCoord2;\nattribute vec4 a_color;\n#if CC_RENDER_MODE == 1\nattribute vec3 a_color1;\n#endif\n#if CC_RENDER_MODE == 4\nattribute vec3 a_texCoord3;\nattribute vec3 a_normal;\nattribute vec4 a_color1;\n#endif\nvec4 lpvs_main () {\nvec3 compScale = scale.xyz * a_texCoord1;\nvec4 pos = vec4(a_position, 1);\n#if CC_RENDER_MODE == 1\nvec4 velocity = vec4(a_color1.xyz, 0);\n#endif\n#if !CC_USE_WORLD_SPACE\npos = cc_matWorld * pos;\n#if CC_RENDER_MODE == 1\nvelocity = cc_matWorld * velocity;\n#endif\n#endif\n#if CC_RENDER_MODE != 4\nvec2 cornerOffset = vec2((a_texCoord.xy - 0.5));\n#if CC_RENDER_MODE == 0\nvec3 rotEuler = a_texCoord2;\n#elif CC_RENDER_MODE == 1\nvec3 rotEuler = vec3(0.);\n#else\nvec3 rotEuler = vec3(0., 0., a_texCoord2.z);\n#endif\ncomputeVertPos(pos, cornerOffset, quaternionFromEuler(rotEuler), compScale\n#if CC_RENDER_MODE == 0 || CC_RENDER_MODE == 3\n, cc_matViewInv\n#endif\n#if CC_RENDER_MODE == 1\n, cc_cameraPos.xyz\n, velocity\n, frameTile_velLenScale.z\n, frameTile_velLenScale.w\n, a_texCoord.x\n#endif\n);\ncolor = a_color;\n#else\nmat4 xformNoScale = matrixFromRT(quaternionFromEuler(a_texCoord2), pos.xyz);\nmat4 xform = matFromRTS(quaternionFromEuler(a_texCoord2), pos.xyz, compScale);\npos = xform * vec4(a_texCoord3, 1);\nvec4 normal = xformNoScale * vec4(a_normal, 0);\ncolor = a_color * a_color1;\n#endif\nuv = computeUV(a_texCoord.z, a_texCoord.xy, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw;\npos = cc_matViewProj * pos;\nreturn pos;\n}\nvoid main() { gl_Position = lpvs_main(); }",
              "frag": "\nprecision mediump float;\nuniform mediump vec4 cc_exposure;\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n#if CC_USE_HDR\ncolor.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n#endif\nreturn color;\n}\nvarying vec2 uv;\nvarying vec4 color;\nuniform sampler2D mainTexture;\nuniform vec4 tintColor;\nvec4 add () {\nvec4 col = 2.0 * color * tintColor * texture2D(mainTexture, uv);\nreturn CCFragOutput(col);\n}\nvoid main() { gl_FragColor = add(); }"
            }], [{
              "vert": "\nprecision highp float;\nuniform highp mat4 cc_matViewProj;\n#if USE_LOCAL\nuniform highp mat4 cc_matWorld;\n#endif\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\nvarying vec4 v_light;\nvarying vec2 uv0;\n#if TWO_COLORED\nattribute vec4 a_color2;\nvarying vec4 v_dark;\n#endif\nvec4 vert () {\nvec4 pos = vec4(a_position, 1);\n#if USE_LOCAL\npos = cc_matWorld * pos;\n#endif\npos = cc_matViewProj * pos;\nuv0 = a_texCoord;\nv_light = a_color;\n#if TWO_COLORED\nv_dark = a_color2;\n#endif\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }",
              "frag": "\nprecision highp float;\n#if USE_ALPHA_TEST\nuniform float alphaThreshold;\n#endif\nvoid ALPHA_TEST (in vec4 color) {\n#if USE_ALPHA_TEST\nif (color.a < alphaThreshold) discard;\n#endif\n}\nvoid ALPHA_TEST (in float alpha) {\n#if USE_ALPHA_TEST\nif (alpha < alphaThreshold) discard;\n#endif\n}\nvarying vec4 v_light;\n#if TWO_COLORED\nvarying vec4 v_dark;\n#endif\nvarying vec2 uv0;\nuniform sampler2D cc_spriteTexture;\nvec4 frag () {\nvec4 o = vec4(1, 1, 1, 1);\n#if TWO_COLORED\nvec4 texColor = vec4(1, 1, 1, 1);\ntexColor *= texture2D(cc_spriteTexture, uv0);\no.a = texColor.a * v_light.a;\no.rgb = ((texColor.a - 1.0) * v_dark.a + 1.0 - texColor.rgb) * v_dark.rgb + texColor.rgb * v_light.rgb;\n#else\no *= texture2D(cc_spriteTexture, uv0);\no *= v_light;\n#endif\nALPHA_TEST(o);\nreturn o;\n}\nvoid main() { gl_FragColor = frag(); }"
            }], [{
              "vert": "\nprecision highp float;\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matProj;\nuniform highp mat4 cc_matViewProj;\nuniform highp vec4 cc_cameraPos;\n#if USE_LOCAL\nuniform highp mat4 cc_matWorld;\n#endif\n#if SAMPLE_FROM_RT\n#endif\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\nvarying vec4 color;\nvarying vec2 uv0;\nvec4 vert () {\nvec4 pos = vec4(a_position, 1);\n#if USE_LOCAL\npos = cc_matWorld * pos;\n#endif\n#if USE_PIXEL_ALIGNMENT\npos = cc_matView * pos;\npos.xyz = floor(pos.xyz);\npos = cc_matProj * pos;\n#else\npos = cc_matViewProj * pos;\n#endif\nuv0 = a_texCoord;\n#if SAMPLE_FROM_RT\nuv0 = cc_cameraPos.w > 1.0 ? vec2(uv0.x, 1.0 - uv0.y) : uv0;\n#endif\ncolor = a_color;\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }",
              "frag": "\nprecision highp float;\nvec4 CCSampleWithAlphaSeparated(sampler2D tex, vec2 uv) {\n#if CC_USE_EMBEDDED_ALPHA\nreturn vec4(texture2D(tex, uv).rgb, texture2D(tex, uv + vec2(0.0, 0.5)).r);\n#else\nreturn texture2D(tex, uv);\n#endif\n}\n#if USE_ALPHA_TEST\nuniform float alphaThreshold;\n#endif\nvoid ALPHA_TEST (in vec4 color) {\n#if USE_ALPHA_TEST\nif (color.a < alphaThreshold) discard;\n#endif\n}\nvoid ALPHA_TEST (in float alpha) {\n#if USE_ALPHA_TEST\nif (alpha < alphaThreshold) discard;\n#endif\n}\nvarying vec4 color;\n#if USE_TEXTURE\nvarying vec2 uv0;\nuniform sampler2D cc_spriteTexture;\n#endif\nvec4 frag () {\nvec4 o = vec4(1, 1, 1, 1);\n#if USE_TEXTURE\no *= CCSampleWithAlphaSeparated(cc_spriteTexture, uv0);\n#if IS_GRAY\nfloat gray  = 0.2126 * o.r + 0.7152 * o.g + 0.0722 * o.b;\no.r = o.g = o.b = gray;\n#endif\n#endif\no *= color;\nALPHA_TEST(o);\nreturn o;\n}\nvoid main() { gl_FragColor = frag(); }"
            }], [{
              "vert": "\nprecision highp float;\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec2 a_texCoord;\nattribute vec4 a_tangent;\n#if CC_USE_MORPH\nattribute float a_vertexId;\nint getVertexId() {\nreturn int(a_vertexId);\n}\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 uv = getPixelCoordFromLocation(location, cc_displacementTextureInfo.xy);\nreturn texture2D(tex, uv);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture2D(tex, x)),\ndecode32(texture2D(tex, y)),\ndecode32(texture2D(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nuniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nuniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nuniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nattr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nattr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nattr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_joints;\nattribute vec4 a_weights;\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nattribute highp vec4 a_jointAnimInfo;\n#endif\nuniform highp vec4 cc_jointTextureInfo;\nuniform highp vec4 cc_jointAnimInfo;\nuniform highp sampler2D cc_jointTexture;\n#else\nuniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\n#if USE_INSTANCING\nhighp float j = 3.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n#else\nhighp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n#endif\nhighp float invSize = cc_jointTextureInfo.w;\nhighp float y = floor(j * invSize);\nhighp float x = floor(j - y * cc_jointTextureInfo.x);\ny = (y + 0.5) * invSize;\nvec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\n#if USE_INSTANCING\nhighp float j = 12.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n#else\nhighp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n#endif\nhighp float invSize = cc_jointTextureInfo.w;\nhighp float y = floor(j * invSize);\nhighp float x = floor(j - y * cc_jointTextureInfo.x);\ny = (y + 0.5) * invSize;\nvec4 v1 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\nmat4 m = skinMatrix();\nattr.position = m * attr.position;\nattr.normal = (m * vec4(attr.normal, 0.0)).xyz;\nattr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matProj;\nuniform highp vec4 cc_cameraPos;\nuniform mediump vec4 cc_fogBase;\nuniform mediump vec4 cc_fogAdd;\n#if USE_INSTANCING\nattribute vec4 a_matWorld0;\nattribute vec4 a_matWorld1;\nattribute vec4 a_matWorld2;\n#if USE_LIGHTMAP\nattribute vec4 a_lightingMapUVParam;\n#endif\n#elif USE_BATCHING\nattribute float a_dyn_batch_id;\nuniform highp mat4 cc_matWorlds[10];\n#else\nuniform highp mat4 cc_matWorld;\nuniform highp mat4 cc_matWorldIT;\nuniform highp vec4 cc_lightingMapUVParam;\n#endif\nuniform vec4 tilingOffset;\nfloat LinearFog(vec4 pos) {\nvec4 wPos = pos;\nfloat cam_dis = distance(cc_cameraPos, wPos);\nfloat fogStart = cc_fogBase.x;\nfloat fogEnd = cc_fogBase.y;\nreturn clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = distance(cc_cameraPos, wPos) / fogAtten * 4.;\nfloat f = exp(-cam_dis * fogDensity);\nreturn f;\n}\nfloat ExpSquaredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = distance(cc_cameraPos, wPos) / fogAtten * 4.;\nfloat f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\nreturn f;\n}\nfloat LayeredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat _FogTop = cc_fogAdd.x;\nfloat _FogRange = cc_fogAdd.y;\nvec3 camWorldProj = cc_cameraPos.xyz;\ncamWorldProj.y = 0.;\nvec3 worldPosProj = wPos.xyz;\nworldPosProj.y = 0.;\nfloat fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\nfloat fDeltaY, fDensityIntegral;\nif (cc_cameraPos.y > _FogTop) {\nif (wPos.y < _FogTop) {\nfDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\nfDensityIntegral = fDeltaY * fDeltaY * 0.5;\n} else {\nfDeltaY = 0.;\nfDensityIntegral = 0.;\n}\n} else {\nif (wPos.y < _FogTop) {\nfloat fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfloat fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\nfDeltaY = abs(fDeltaA - fDeltaB);\nfDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n} else {\nfDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n}\n}\nfloat fDensity;\nif (fDeltaY != 0.) {\nfDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n} else {\nfDensity = 0.;\n}\nfloat f = exp(-fDensity);\nreturn f;\n}\nvarying float v_fog_factor;\nvarying highp vec4 v_shadowPos;\nuniform highp mat4 cc_matLightViewProj;\n#if CC_RECEIVE_SHADOW\nuniform sampler2D cc_shadowMap;\nuniform sampler2D cc_spotLightingMap;\n#endif\n#if USE_VERTEX_COLOR\nattribute vec4 a_color;\nvarying vec4 v_color;\n#endif\nvarying vec3 v_position;\nvarying vec3 v_normal;\nvarying vec2 v_uv;\nvarying vec2 v_uv1;\n#if USE_NORMAL_MAP\nvarying vec3 v_tangent;\nvarying vec3 v_bitangent;\n#endif\n#if HAS_SECOND_UV || USE_LIGHTMAP\nattribute vec2 a_texCoord1;\n#endif\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nvarying vec3 v_luv;\nvoid CCLightingMapCaclUV()\n{\n#if !USE_INSTANCING\nv_luv.xy = cc_lightingMapUVParam.xy + a_texCoord1 * cc_lightingMapUVParam.zw;\nv_luv.z = cc_lightingMapUVParam.z;\n#else\nv_luv.xy = a_lightingMapUVParam.xy + a_texCoord1 * a_lightingMapUVParam.zw;\nv_luv.z = a_lightingMapUVParam.z;\n#endif\n}\n#endif\nvoid main () {\nStandardVertInput In;\nIn.position = vec4(a_position, 1.0);\nIn.normal = a_normal;\nIn.tangent = a_tangent;\n#if CC_USE_MORPH\napplyMorph(In);\n#endif\n#if CC_USE_SKINNING\nCCSkin(In);\n#endif\nmat4 matWorld, matWorldIT;\n#if USE_INSTANCING\nmatWorld = mat4(\nvec4(a_matWorld0.xyz, 0.0),\nvec4(a_matWorld1.xyz, 0.0),\nvec4(a_matWorld2.xyz, 0.0),\nvec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n);\nmatWorldIT = matWorld;\n#elif USE_BATCHING\nmatWorld = cc_matWorlds[int(a_dyn_batch_id)];\nmatWorldIT = matWorld;\n#else\nmatWorld = cc_matWorld;\nmatWorldIT = cc_matWorldIT;\n#endif\nvec4 pos = matWorld * In.position;\nv_position = pos.xyz;\nv_normal = normalize((matWorldIT * vec4(In.normal, 0.0)).xyz);\n#if USE_NORMAL_MAP\nv_tangent = normalize((matWorld * vec4(In.tangent.xyz, 0.0)).xyz);\nv_bitangent = cross(v_normal, v_tangent) * In.tangent.w;\n#endif\nv_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n#if SAMPLE_FROM_RT\nv_uv = cc_cameraPos.w > 1.0 ? vec2(v_uv.x, 1.0 - v_uv.y) : v_uv;\n#endif\n#if HAS_SECOND_UV\nv_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw;\n#if SAMPLE_FROM_RT\nv_uv1 = cc_cameraPos.w > 1.0 ? vec2(v_uv1.x, 1.0 - v_uv1.y) : v_uv1;\n#endif\n#endif\n#if USE_VERTEX_COLOR\nv_color = a_color;\n#endif\n#if CC_USE_FOG == 0\nv_fog_factor = LinearFog(pos);\n#elif CC_USE_FOG == 1\nv_fog_factor = ExpFog(pos);\n#elif CC_USE_FOG == 2\nv_fog_factor = ExpSquaredFog(pos);\n#elif CC_USE_FOG == 3\nv_fog_factor = LayeredFog(pos);\n#else\nv_fog_factor = 1.0;\n#endif\nv_shadowPos = cc_matLightViewProj * pos;\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nCCLightingMapCaclUV();\n#endif\ngl_Position = cc_matProj * (cc_matView * matWorld) * In.position;\n}",
              "frag": "\n#ifdef GL_EXT_draw_buffers\n#extension GL_EXT_draw_buffers: enable\n#endif\n#ifdef GL_EXT_shader_texture_lod\n#extension GL_EXT_shader_texture_lod: enable\n#endif\nprecision highp float;\nuniform highp vec4 cc_cameraPos;\nuniform mediump vec4 cc_exposure;\nuniform mediump vec4 cc_mainLitDir;\nuniform mediump vec4 cc_mainLitColor;\nuniform mediump vec4 cc_ambientSky;\nuniform mediump vec4 cc_ambientGround;\nuniform mediump vec4 cc_fogColor;\nuniform vec4 albedo;\nuniform vec4 albedoScaleAndCutoff;\nuniform vec4 pbrParams;\nuniform vec4 emissive;\nuniform vec4 emissiveScaleParam;\nvarying float v_fog_factor;\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nuniform highp mat4 cc_matLightView;\nuniform lowp vec4 cc_shadowNFLSInfo;\nuniform lowp vec4 cc_shadowWHPBInfo;\nuniform lowp vec4 cc_shadowLPNNInfo;\nuniform lowp vec4 cc_shadowColor;\n#if CC_RECEIVE_SHADOW\nuniform sampler2D cc_shadowMap;\nuniform sampler2D cc_spotLightingMap;\nfloat CCGetLinearDepth (vec3 worldPos) {\nvec4 viewStartPos = cc_matLightView * vec4(worldPos.xyz, 1.0);\nfloat dist = length(viewStartPos.xyz);\nreturn cc_shadowNFLSInfo.x + (-dist / (cc_shadowNFLSInfo.y - cc_shadowNFLSInfo.x));\n}\nfloat CCGetShadowFactorHard (vec4 shadowPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nfloat shadow = 0.0;\nfloat closestDepth = 0.0;\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nclosestDepth = dot(texture2D(cc_shadowMap, clipPos.xy), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\n} else {\nclosestDepth = texture2D(cc_shadowMap, clipPos.xy).x;\n}\nshadow = step(closestDepth, clipPos.z- cc_shadowWHPBInfo.w);\nreturn shadow;\n}\nfloat CCGetShadowFactorSoft (vec4 shadowPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat offsetDepth = clipPos.z - cc_shadowWHPBInfo.w;\nvec2 oneTap = 1.0 / cc_shadowWHPBInfo.xy;\nvec2 clipPos_offset = clipPos.xy + oneTap;\nfloat block0, block1, block2, block3;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(dot(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock1 = step(dot(texture2D(cc_shadowMap, vec2(clipPos_offset.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock2 = step(dot(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock3 = step(dot(texture2D(cc_shadowMap, vec2(clipPos_offset.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\n} else {\nblock0 = step(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos.y)).x, offsetDepth);\nblock1 = step(texture2D(cc_shadowMap, vec2(clipPos_offset.x, clipPos.y)).x, offsetDepth);\nblock2 = step(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset.y)).x, offsetDepth);\nblock3 = step(texture2D(cc_shadowMap, vec2(clipPos_offset.x, clipPos_offset.y)).x, offsetDepth);\n}\nfloat coefX   = mod(clipPos.x, oneTap.x) * cc_shadowWHPBInfo.x;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block2, block3, coefX);\nfloat coefY   = mod(clipPos.y, oneTap.y) * cc_shadowWHPBInfo.y;;\nreturn mix(resultX, resultY, coefY);\n}\nfloat CCGetShadowFactorSoft2X (vec4 shadowPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat bias = cc_shadowWHPBInfo.w;\nfloat offsetDepth = clipPos.z - bias;\nvec2 mapSize = cc_shadowWHPBInfo.xy;\nvec2 oneTap = 1.0 / mapSize;\nfloat clipPos_offset_L = clipPos.x - oneTap.x;\nfloat clipPos_offset_R = clipPos.x + oneTap.x;\nfloat clipPos_offset_U = clipPos.y - oneTap.y;\nfloat clipPos_offset_D = clipPos.y + oneTap.y;\nfloat block0, block1, block2, block3, block4, block5, block6, block7, block8;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(dot(texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock1 = step(dot(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock2 = step(dot(texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock3 = step(dot(texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock4 = step(dot(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock5 = step(dot(texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock6 = step(dot(texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock7 = step(dot(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock8 = step(dot(texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\n} else {\nblock0 = step(texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_U)).x, offsetDepth);\nblock1 = step(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset_U)).x, offsetDepth);\nblock2 = step(texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_U)).x, offsetDepth);\nblock3 = step(texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos.y)).x, offsetDepth);\nblock4 = step(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos.y)).x, offsetDepth);\nblock5 = step(texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos.y)).x, offsetDepth);\nblock6 = step(texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_D)).x, offsetDepth);\nblock7 = step(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset_D)).x, offsetDepth);\nblock8 = step(texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_D)).x, offsetDepth);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * mapSize.x;\nfloat coefY = mod(clipPos.y, oneTap.y) * mapSize.y;\nfloat shadow = 0.0;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block3, block4, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block1, block2, coefX);\nresultY = mix(block4, block5, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block3, block4, coefX);\nresultY = mix(block6, block7, coefX);\nshadow += mix(resultX, resultY, coefY);\nresultX = mix(block4, block5, coefX);\nresultY = mix(block7, block8, coefX);\nshadow += mix(resultX, resultY, coefY);\nreturn shadow * 0.25;\n}\nfloat CCGetSpotLightShadowFactorHard (vec4 shadowPos, vec3 worldPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nfloat shadow = 0.0;\nfloat closestDepth = 0.0;\nfloat depth = 0.0;\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nif (cc_shadowLPNNInfo.y > 0.000001) {\nclosestDepth = dot(texture2D(cc_spotLightingMap, clipPos.xy), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\n} else {\nclosestDepth = texture2D(cc_spotLightingMap, clipPos.xy).x;\n}\nshadow = step(closestDepth, depth - cc_shadowWHPBInfo.w);\nreturn shadow;\n}\nfloat CCGetSpotLightShadowFactorSoft (vec4 shadowPos, vec3 worldPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nfloat offsetx = 1.0 / cc_shadowWHPBInfo.x;\nfloat offsety = 1.0 / cc_shadowWHPBInfo.y;\nfloat shadow = 0.0;\nfloat depth = 0.0;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nfloat closestDepth = dot(texture2D(cc_spotLightingMap, vec2(clipPos.x - offsetx, clipPos.y - offsety)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = dot(texture2D(cc_spotLightingMap, vec2(clipPos.x - offsetx, clipPos.y + offsety)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = dot(texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = dot(texture2D(cc_spotLightingMap, vec2(clipPos.x + offsetx, clipPos.y - offsety)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = dot(texture2D(cc_spotLightingMap, vec2(clipPos.x + offsetx, clipPos.y + offsety)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\n} else {\nfloat closestDepth = texture2D(cc_spotLightingMap, vec2(clipPos.x - offsetx, clipPos.y - offsety)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = texture2D(cc_spotLightingMap, vec2(clipPos.x - offsetx, clipPos.y + offsety)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = texture2D(cc_spotLightingMap, vec2(clipPos.x + offsetx, clipPos.y - offsety)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = texture2D(cc_spotLightingMap, vec2(clipPos.x + offsetx, clipPos.y + offsety)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\n}\nreturn shadow / 5.0;\n}\nfloat CCGetSpotLightShadowFactorSoft2X (vec4 shadowPos, vec3 worldPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nfloat offsetx = 1.0 / cc_shadowWHPBInfo.x;\nfloat offsety = 1.0 / cc_shadowWHPBInfo.y;\nfloat shadow = 0.0;\nfloat depth = 0.0;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nfor (int i = -1; i <= 1; i++) {\nfor (int j = -1; j <= 1; j++) {\nfloat closestDepth = dot(texture2D(cc_spotLightingMap, clipPos.xy + vec2(i, j) * vec2(offsetx, offsety)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\n}\n}\n} else {\nfor (int i = -1; i <= 1; i++) {\nfor (int j = -1; j <= 1; j++) {\nfloat closestDepth = texture2D(cc_spotLightingMap, clipPos.xy + vec2(i, j) * vec2(offsetx, offsety)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\n}\n}\n}\nreturn shadow / 9.0;\n}\n#endif\n#if CC_USE_IBL\nuniform samplerCube cc_environment;\nvec3 unpackRGBE (vec4 rgbe) {\nreturn rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\nvec4 fragTextureLod (sampler2D tex, vec2 coord, float lod) {\n#ifdef GL_EXT_shader_texture_lod\nreturn texture2DLodEXT(tex, coord, lod);\n#else\nreturn texture2D(tex, coord, lod);\n#endif\n}\nvec4 fragTextureLod (samplerCube tex, vec3 coord, float lod) {\n#ifdef GL_EXT_shader_texture_lod\nreturn textureCubeLodEXT(tex, coord, lod);\n#else\nreturn textureCube(tex, coord, lod);\n#endif\n}\n#endif\nfloat GGXMobile (float roughness, float NoH, vec3 H, vec3 N) {\nvec3 NxH = cross(N, H);\nfloat OneMinusNoHSqr = dot(NxH, NxH);\nfloat a = roughness * roughness;\nfloat n = NoH * a;\nfloat p = a / (OneMinusNoHSqr + n * n);\nreturn p * p;\n}\nfloat CalcSpecular (float roughness, float NoH, vec3 H, vec3 N) {\nreturn (roughness * 0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox (vec3 specular, float roughness, float NoV) {\nconst vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\nconst vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\nvec4 r = roughness * c0 + c1;\nfloat a004 = min(r.x * r.x, exp2(-9.28 * NoV)) * r.x + r.y;\nvec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;\nAB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\nreturn specular * AB.x + AB.y;\n}\nstruct StandardSurface {\nvec4 albedo;\nvec3 position;\nvec3 normal;\nvec3 emissive;\nvec3 lightmap;\nfloat lightmap_test;\nfloat roughness;\nfloat metallic;\nfloat occlusion;\n};\nvec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) {\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - s.position);\nfloat NV = max(abs(dot(N, V)), 0.001);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 L = normalize(-cc_mainLitDir.xyz);\nvec3 H = normalize(L + V);\nfloat NH = max(dot(N, H), 0.0);\nfloat NL = max(dot(N, L), 0.001);\nvec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w;\nvec3 diffuseContrib = diffuse;\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nif (s.lightmap_test > 0.0001) {\nfinalColor = s.lightmap.rgb;\n}\n#else\ndiffuseContrib /= 3.14159265359;\n#endif\nvec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\nvec3 dirlightContrib = (diffuseContrib + specularContrib);\n#if CC_RECEIVE_SHADOW\n{\nfloat pcf = cc_shadowWHPBInfo.z + 0.001;\nfloat shadowAttenuation = 0.0;\nfloat cosAngle = clamp(1.0 - dot(N, L.xyz), 0.0, 1.0);\nvec3 projWorldPos = shadowPos.xyz + cosAngle * cc_shadowLPNNInfo.z * N;\nvec4 pos = vec4(projWorldPos.xyz, shadowPos.w);\nif (pcf > 2.0) shadowAttenuation = CCGetShadowFactorSoft2X(pos);\nelse if (pcf > 1.0) shadowAttenuation = CCGetShadowFactorSoft(pos);\nelse shadowAttenuation = CCGetShadowFactorHard(pos);\nvec3 shadowColor = cc_shadowColor.rgb * cc_shadowColor.a + dirlightContrib.rgb * (1.0 - cc_shadowColor.a);\nif (cc_shadowNFLSInfo.w > 0.000001) {\ndirlightContrib.rgb = shadowColor.rgb * shadowAttenuation + dirlightContrib.rgb * (1.0 - shadowAttenuation);\n} else {\ndirlightContrib.rgb = shadowColor.rgb * shadowAttenuation * NL + dirlightContrib.rgb * (1.0 - shadowAttenuation * NL);\n}\n}\n#endif\nfinalColor *= dirlightContrib;\nfloat fAmb = 0.5 - N.y * 0.5;\nvec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\nfinalColor += (ambDiff.rgb * diffuse);\n#if CC_USE_IBL\nvec3 R = normalize(reflect(-V, N));\nvec4 envmap = fragTextureLod(cc_environment, R, s.roughness * cc_ambientGround.w);\n#if CC_USE_IBL == 2\nvec3 env = unpackRGBE(envmap);\n#else\nvec3 env = SRGBToLinear(envmap.rgb);\n#endif\nfinalColor += env * cc_ambientSky.w * specular;\n#endif\nfinalColor = finalColor * s.occlusion;\n#if CC_USE_HDR\ns.emissive *= cc_exposure.w;\n#endif\nfinalColor += s.emissive;\nreturn vec4(finalColor, s.albedo.a);\n}\nvec3 ACESToneMap (vec3 color) {\ncolor = min(color, vec3(8.0));\nconst float A = 2.51;\nconst float B = 0.03;\nconst float C = 2.43;\nconst float D = 0.59;\nconst float E = 0.14;\nreturn (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n#if !CC_USE_HDR\ncolor.rgb = sqrt(ACESToneMap(color.rgb));\n#endif\nreturn color;\n}\nvarying highp vec4 v_shadowPos;\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nvarying vec3 v_luv;\nuniform sampler2D cc_lightingMap;\nvec3 UnpackLightingmap(vec4 color) {\nvec3 c;\nfloat e = 1.0 + color.a * (8.0 - 1.0);\nc.r = color.r * e;\nc.g = color.g * e;\nc.b = color.b * e;\nreturn c;\n}\n#endif\nvarying vec3 v_position;\nvarying vec2 v_uv;\nvarying vec2 v_uv1;\nvarying vec3 v_normal;\n#if USE_VERTEX_COLOR\nvarying vec4 v_color;\n#endif\n#if USE_ALBEDO_MAP\nuniform sampler2D albedoMap;\n#endif\n#if USE_NORMAL_MAP\nvarying vec3 v_tangent;\nvarying vec3 v_bitangent;\nuniform sampler2D normalMap;\n#endif\n#if USE_PBR_MAP\nuniform sampler2D pbrMap;\n#endif\n#if USE_METALLIC_ROUGHNESS_MAP\nuniform sampler2D metallicRoughnessMap;\n#endif\n#if USE_OCCLUSION_MAP\nuniform sampler2D occlusionMap;\n#endif\n#if USE_EMISSIVE_MAP\nuniform sampler2D emissiveMap;\n#endif\n#if USE_ALPHA_TEST\n#endif\nvoid surf (out StandardSurface s) {\nvec4 baseColor = albedo;\n#if USE_VERTEX_COLOR\nbaseColor *= v_color;\n#endif\n#if USE_ALBEDO_MAP\nvec4 texColor = texture2D(albedoMap, ALBEDO_UV);\ntexColor.rgb = SRGBToLinear(texColor.rgb);\nbaseColor *= texColor;\n#endif\ns.albedo = baseColor;\ns.albedo.rgb *= albedoScaleAndCutoff.xyz;\n#if USE_ALPHA_TEST\nif (s.albedo.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard;\n#endif\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nvec4 lightColor = texture2D(cc_lightingMap, v_luv.xy);\ns.lightmap = UnpackLightingmap(lightColor);\ns.lightmap_test = v_luv.z;\n#endif\ns.normal = v_normal;\n#if USE_NORMAL_MAP\nvec3 nmmp = texture2D(normalMap, NORMAL_UV).xyz - vec3(0.5);\ns.normal =\n(nmmp.x * pbrParams.w) * normalize(v_tangent) +\n(nmmp.y * pbrParams.w) * normalize(v_bitangent) +\nnmmp.z * normalize(s.normal);\n#endif\ns.position = v_position;\nvec4 pbr = pbrParams;\n#if USE_PBR_MAP\nvec4 res = texture2D(pbrMap, PBR_UV);\npbr.x *= res.r;\npbr.y *= res.g;\npbr.z *= res.b;\n#endif\n#if USE_METALLIC_ROUGHNESS_MAP\nvec4 metallicRoughness = texture2D(metallicRoughnessMap, PBR_UV);\npbr.z *= metallicRoughness.b;\npbr.y *= metallicRoughness.g;\n#endif\n#if USE_OCCLUSION_MAP\npbr.x *= texture2D(occlusionMap, PBR_UV).r;\n#endif\ns.occlusion = clamp(pbr.x, 0.0, 0.96);\ns.roughness = clamp(pbr.y, 0.04, 1.0);\ns.metallic = pbr.z;\ns.emissive = emissive.rgb * emissiveScaleParam.xyz;\n#if USE_EMISSIVE_MAP\ns.emissive *= SRGBToLinear(texture2D(emissiveMap, EMISSIVE_UV).rgb);\n#endif\n}\n#if CC_FORWARD_ADD\n#if CC_PIPELINE_TYPE == 0\n# define LIGHTS_PER_PASS 1\n#else\n# define LIGHTS_PER_PASS 10\n#endif\nuniform highp vec4 cc_lightPos[LIGHTS_PER_PASS];\nuniform vec4 cc_lightColor[LIGHTS_PER_PASS];\nuniform vec4 cc_lightSizeRangeAngle[LIGHTS_PER_PASS];\nuniform vec4 cc_lightDir[LIGHTS_PER_PASS];\nfloat SmoothDistAtt (float distSqr, float invSqrAttRadius) {\nfloat factor = distSqr * invSqrAttRadius;\nfloat smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\nreturn smoothFactor * smoothFactor;\n}\nfloat GetDistAtt (float distSqr, float invSqrAttRadius) {\nfloat attenuation = 1.0 / max(distSqr, 0.01*0.01);\nattenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\nreturn attenuation;\n}\nfloat GetAngleAtt (vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\nfloat cd = dot(litDir, L);\nfloat attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\nreturn (attenuation * attenuation);\n}\nvec4 CCStandardShadingAdditive (StandardSurface s, vec4 shadowPos) {\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 diffuseContrib = diffuse / 3.14159265359;\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - s.position);\nfloat NV = max(abs(dot(N, V)), 0.001);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 finalColor = vec3(0.0);\nint numLights = CC_PIPELINE_TYPE == 0 ? LIGHTS_PER_PASS : int(cc_lightDir[0].w);\nfor (int i = 0; i < LIGHTS_PER_PASS; i++) {\nif (i >= numLights) break;\nvec3 SLU = cc_lightPos[i].xyz - s.position;\nvec3 SL = normalize(SLU);\nvec3 SH = normalize(SL + V);\nfloat SNL = max(dot(N, SL), 0.001);\nfloat SNH = max(dot(N, SH), 0.0);\nfloat distSqr = dot(SLU, SLU);\nfloat litRadius = cc_lightSizeRangeAngle[i].x;\nfloat litRadiusSqr = litRadius * litRadius;\nfloat illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\nfloat attRadiusSqrInv = 1.0 / max(cc_lightSizeRangeAngle[i].y, 0.01);\nattRadiusSqrInv *= attRadiusSqrInv;\nfloat att = GetDistAtt(distSqr, attRadiusSqrInv);\nvec3 lspec = specular * CalcSpecular(s.roughness, SNH, SH, N);\nif (cc_lightPos[i].w > 0.0) {\nfloat cosInner = max(dot(-cc_lightDir[i].xyz, SL), 0.01);\nfloat cosOuter = cc_lightSizeRangeAngle[i].z;\nfloat litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\nfloat litAngleOffset = -cosOuter * litAngleScale;\natt *= GetAngleAtt(SL, -cc_lightDir[i].xyz, litAngleScale, litAngleOffset);\n}\nvec3 lightColor = cc_lightColor[i].rgb;\n#if CC_RECEIVE_SHADOW\nif (cc_lightPos[i].w > 0.0) {\n{\nfloat pcf = cc_shadowWHPBInfo.z + 0.001;\nfloat shadowAttenuation = 0.0;\nfloat cosAngle = clamp(1.0 - dot(N, normalize(cc_lightPos[i].xyz - s.position.xyz)), 0.0, 1.0);\nvec3 projWorldPos = shadowPos.xyz + cosAngle * cc_shadowLPNNInfo.z * N;\nvec4 pos = vec4(projWorldPos.xyz, shadowPos.w);\nif (pcf > 2.0) shadowAttenuation = CCGetSpotLightShadowFactorSoft2X(pos, s.position);\nelse if (pcf > 1.0) shadowAttenuation = CCGetSpotLightShadowFactorSoft(pos, s.position);\nelse shadowAttenuation = CCGetSpotLightShadowFactorHard(pos, s.position);\nlightColor *= 1.0 - shadowAttenuation;\n}\n}\n#endif\nfinalColor += SNL * lightColor * cc_lightColor[i].w * illum * att * (diffuseContrib + lspec);\n}\nfinalColor = finalColor * s.occlusion;\nreturn vec4(finalColor, 0.0);\n}\nvoid main () {\nStandardSurface s; surf(s);\nvec4 color = CCStandardShadingAdditive(s, v_shadowPos);\ncolor = vec4(mix(CC_FORWARD_ADD > 0 ? vec3(0.0) : cc_fogColor.rgb, color.rgb, v_fog_factor), color.a);\ngl_FragData[0] = CCFragOutput(color);\n}\n#elif CC_PIPELINE_TYPE == 0\nvoid main () {\nStandardSurface s; surf(s);\nvec4 color = CCStandardShadingBase(s, v_shadowPos);\ncolor = vec4(mix(CC_FORWARD_ADD > 0 ? vec3(0.0) : cc_fogColor.rgb, color.rgb, v_fog_factor), color.a);\ngl_FragData[0] = CCFragOutput(color);\n}\n#elif CC_PIPELINE_TYPE == 1\nvoid main () {\nStandardSurface s; surf(s);\ngl_FragData[0] = s.albedo;\ngl_FragData[1] = vec4(s.position, s.roughness);\ngl_FragData[2] = vec4(s.normal, s.metallic);\ngl_FragData[3] = vec4(s.emissive, s.occlusion);\n}\n#endif"
            }, {
              "vert": "\nprecision highp float;\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec2 a_texCoord;\nattribute vec4 a_tangent;\n#if CC_USE_MORPH\nattribute float a_vertexId;\nint getVertexId() {\nreturn int(a_vertexId);\n}\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 uv = getPixelCoordFromLocation(location, cc_displacementTextureInfo.xy);\nreturn texture2D(tex, uv);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture2D(tex, x)),\ndecode32(texture2D(tex, y)),\ndecode32(texture2D(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nuniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nuniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nuniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nattr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nattr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nattr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_joints;\nattribute vec4 a_weights;\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nattribute highp vec4 a_jointAnimInfo;\n#endif\nuniform highp vec4 cc_jointTextureInfo;\nuniform highp vec4 cc_jointAnimInfo;\nuniform highp sampler2D cc_jointTexture;\n#else\nuniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\n#if USE_INSTANCING\nhighp float j = 3.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n#else\nhighp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n#endif\nhighp float invSize = cc_jointTextureInfo.w;\nhighp float y = floor(j * invSize);\nhighp float x = floor(j - y * cc_jointTextureInfo.x);\ny = (y + 0.5) * invSize;\nvec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\n#if USE_INSTANCING\nhighp float j = 12.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n#else\nhighp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n#endif\nhighp float invSize = cc_jointTextureInfo.w;\nhighp float y = floor(j * invSize);\nhighp float x = floor(j - y * cc_jointTextureInfo.x);\ny = (y + 0.5) * invSize;\nvec4 v1 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\nmat4 m = skinMatrix();\nattr.position = m * attr.position;\nattr.normal = (m * vec4(attr.normal, 0.0)).xyz;\nattr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\n#if USE_INSTANCING\nattribute vec4 a_matWorld0;\nattribute vec4 a_matWorld1;\nattribute vec4 a_matWorld2;\n#if USE_LIGHTMAP\nattribute vec4 a_lightingMapUVParam;\n#endif\n#elif USE_BATCHING\nattribute float a_dyn_batch_id;\nuniform highp mat4 cc_matWorlds[10];\n#else\nuniform highp mat4 cc_matWorld;\nuniform highp mat4 cc_matWorldIT;\n#endif\nuniform vec4 tilingOffset;\nuniform highp mat4 cc_matLightViewProj;\n#if HAS_SECOND_UV || USE_LIGHTMAP\nattribute vec2 a_texCoord1;\n#endif\nvarying vec2 v_uv;\nvarying vec2 v_uv1;\nvarying vec4 v_worldPos;\nvarying float v_clip_depth;\nvec4 vert () {\nStandardVertInput In;\nIn.position = vec4(a_position, 1.0);\nIn.normal = a_normal;\nIn.tangent = a_tangent;\n#if CC_USE_MORPH\napplyMorph(In);\n#endif\n#if CC_USE_SKINNING\nCCSkin(In);\n#endif\nmat4 matWorld, matWorldIT;\n#if USE_INSTANCING\nmatWorld = mat4(\nvec4(a_matWorld0.xyz, 0.0),\nvec4(a_matWorld1.xyz, 0.0),\nvec4(a_matWorld2.xyz, 0.0),\nvec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n);\nmatWorldIT = matWorld;\n#elif USE_BATCHING\nmatWorld = cc_matWorlds[int(a_dyn_batch_id)];\nmatWorldIT = matWorld;\n#else\nmatWorld = cc_matWorld;\nmatWorldIT = cc_matWorldIT;\n#endif\nv_worldPos = matWorld * In.position;\nvec4 clipPos = cc_matLightViewProj * v_worldPos;\nv_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n#if HAS_SECOND_UV\nv_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw;\n#endif\nv_clip_depth = clipPos.z / clipPos.w * 0.5 + 0.5;\nreturn clipPos;\n}\nvoid main() { gl_Position = vert(); }",
              "frag": "\nprecision highp float;\nuniform vec4 albedo;\nuniform vec4 albedoScaleAndCutoff;\nvec4 packDepthToRGBA (float depth) {\nvec4 ret = vec4(1.0, 255.0, 65025.0, 160581375.0) * depth;\nret = fract(ret);\nret -= ret.yzww * vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);\nreturn ret;\n}\nuniform highp mat4 cc_matLightView;\nuniform lowp vec4 cc_shadowNFLSInfo;\nuniform lowp vec4 cc_shadowLPNNInfo;\nvarying vec2 v_uv;\nvarying vec2 v_uv1;\nvarying vec4 v_worldPos;\nvarying float v_clip_depth;\n#if USE_ALBEDO_MAP\nuniform sampler2D albedoMap;\n#endif\n#if USE_ALPHA_TEST\n#endif\nvec4 frag () {\nvec4 baseColor = albedo;\n#if USE_ALBEDO_MAP\nbaseColor *= texture2D(albedoMap, ALBEDO_UV);\n#endif\n#if USE_ALPHA_TEST\nif (baseColor.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard;\n#endif\nif(cc_shadowLPNNInfo.x > 0.000001 && cc_shadowLPNNInfo.x < 1.999999) {\nif (cc_shadowNFLSInfo.z > 0.000001) {\nvec4 viewStartPos = cc_matLightView * v_worldPos;\nfloat dist = length(viewStartPos.xyz);\nfloat linearDepth = cc_shadowNFLSInfo.x + (-dist / (cc_shadowNFLSInfo.y - cc_shadowNFLSInfo.x));\nreturn vec4(linearDepth, 1.0, 1.0, 1.0);\n}\n}\nif (cc_shadowLPNNInfo.y > 0.000001) {\nreturn packDepthToRGBA(v_clip_depth);\n}\nreturn vec4(v_clip_depth, 1.0, 1.0, 1.0);\n}\nvoid main() { gl_FragColor = frag(); }"
            }], [{
              "vert": "\nprecision mediump float;\nuniform highp mat4 cc_matViewProj;\nuniform highp vec4 cc_cameraPos;\nuniform mediump vec4 cc_fogBase;\nuniform mediump vec4 cc_fogAdd;\nuniform highp mat4 cc_matWorld;\nfloat LinearFog(vec4 pos) {\nvec4 wPos = pos;\nfloat cam_dis = distance(cc_cameraPos, wPos);\nfloat fogStart = cc_fogBase.x;\nfloat fogEnd = cc_fogBase.y;\nreturn clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = distance(cc_cameraPos, wPos) / fogAtten * 4.;\nfloat f = exp(-cam_dis * fogDensity);\nreturn f;\n}\nfloat ExpSquaredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = distance(cc_cameraPos, wPos) / fogAtten * 4.;\nfloat f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\nreturn f;\n}\nfloat LayeredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat _FogTop = cc_fogAdd.x;\nfloat _FogRange = cc_fogAdd.y;\nvec3 camWorldProj = cc_cameraPos.xyz;\ncamWorldProj.y = 0.;\nvec3 worldPosProj = wPos.xyz;\nworldPosProj.y = 0.;\nfloat fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\nfloat fDeltaY, fDensityIntegral;\nif (cc_cameraPos.y > _FogTop) {\nif (wPos.y < _FogTop) {\nfDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\nfDensityIntegral = fDeltaY * fDeltaY * 0.5;\n} else {\nfDeltaY = 0.;\nfDensityIntegral = 0.;\n}\n} else {\nif (wPos.y < _FogTop) {\nfloat fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfloat fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\nfDeltaY = abs(fDeltaA - fDeltaB);\nfDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n} else {\nfDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n}\n}\nfloat fDensity;\nif (fDeltaY != 0.) {\nfDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n} else {\nfDensity = 0.;\n}\nfloat f = exp(-fDensity);\nreturn f;\n}\nvarying float v_fog_factor;\nvarying highp vec4 v_shadowPos;\nuniform highp mat4 cc_matLightViewProj;\n#if CC_RECEIVE_SHADOW\nuniform sampler2D cc_shadowMap;\nuniform sampler2D cc_spotLightingMap;\n#endif\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec2 a_texCoord;\nvarying highp vec3 v_position;\nvarying mediump vec3 v_normal;\n#if USE_NORMALMAP\nvarying mediump vec3 v_tangent;\nvarying mediump vec3 v_binormal;\n#endif\nvarying mediump vec2 uvw;\nvarying mediump vec2 uv0;\nvarying mediump vec2 uv1;\nvarying mediump vec2 uv2;\nvarying mediump vec2 uv3;\nvarying mediump vec3 luv;\nvarying mediump vec3 diffuse;\nuniform vec4 UVScale;\nuniform vec4 lightMapUVParam;\nvoid main () {\nvec3 worldPos;\nworldPos.x = cc_matWorld[3][0] + a_position.x;\nworldPos.y = cc_matWorld[3][1] + a_position.y;\nworldPos.z = cc_matWorld[3][2] + a_position.z;\nvec4 pos = vec4(worldPos, 1.0);\npos = cc_matViewProj * pos;\nuvw = a_texCoord;\nuv0 = a_position.xz * UVScale.x;\nuv1 = a_position.xz * UVScale.y;\nuv2 = a_position.xz * UVScale.z;\nuv3 = a_position.xz * UVScale.w;\n#if USE_LIGHTMAP\nluv.xy = lightMapUVParam.xy + a_texCoord * lightMapUVParam.zw;\nluv.z = lightMapUVParam.z;\n#endif\nv_position = worldPos;\nv_normal = a_normal;\n#if CC_USE_FOG == 0\nv_fog_factor = LinearFog(vec4(worldPos, 1.0));\n#elif CC_USE_FOG == 1\nv_fog_factor = ExpFog(vec4(worldPos, 1.0));\n#elif CC_USE_FOG == 2\nv_fog_factor = ExpSquaredFog(vec4(worldPos, 1.0));\n#elif CC_USE_FOG == 3\nv_fog_factor = LayeredFog(vec4(worldPos, 1.0));\n#else\nv_fog_factor = 1.0;\n#endif\n#if USE_NORMALMAP\nv_tangent = vec3(1.0, 0.0, 0.0);\nv_binormal = vec3(0.0, 0.0, 1.0);\nv_binormal = cross(v_tangent, a_normal);\nv_tangent = cross(a_normal, v_binormal);\n#endif\nv_shadowPos = cc_matLightViewProj * vec4(worldPos, 1.0);\ngl_Position = pos;\n}",
              "frag": "\n#ifdef GL_EXT_draw_buffers\n#extension GL_EXT_draw_buffers: enable\n#endif\n#ifdef GL_EXT_shader_texture_lod\n#extension GL_EXT_shader_texture_lod: enable\n#endif\nprecision highp float;\nuniform highp vec4 cc_cameraPos;\nuniform mediump vec4 cc_exposure;\nuniform mediump vec4 cc_mainLitDir;\nuniform mediump vec4 cc_mainLitColor;\nuniform mediump vec4 cc_ambientSky;\nuniform mediump vec4 cc_ambientGround;\nuniform mediump vec4 cc_fogColor;\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nuniform highp mat4 cc_matLightView;\nuniform lowp vec4 cc_shadowNFLSInfo;\nuniform lowp vec4 cc_shadowWHPBInfo;\nuniform lowp vec4 cc_shadowLPNNInfo;\nuniform lowp vec4 cc_shadowColor;\n#if CC_RECEIVE_SHADOW\nuniform sampler2D cc_shadowMap;\nuniform sampler2D cc_spotLightingMap;\nfloat CCGetLinearDepth (vec3 worldPos) {\nvec4 viewStartPos = cc_matLightView * vec4(worldPos.xyz, 1.0);\nfloat dist = length(viewStartPos.xyz);\nreturn cc_shadowNFLSInfo.x + (-dist / (cc_shadowNFLSInfo.y - cc_shadowNFLSInfo.x));\n}\nfloat CCGetShadowFactorHard (vec4 shadowPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nfloat shadow = 0.0;\nfloat closestDepth = 0.0;\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nclosestDepth = dot(texture2D(cc_shadowMap, clipPos.xy), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\n} else {\nclosestDepth = texture2D(cc_shadowMap, clipPos.xy).x;\n}\nshadow = step(closestDepth, clipPos.z- cc_shadowWHPBInfo.w);\nreturn shadow;\n}\nfloat CCGetShadowFactorSoft (vec4 shadowPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat offsetDepth = clipPos.z - cc_shadowWHPBInfo.w;\nvec2 oneTap = 1.0 / cc_shadowWHPBInfo.xy;\nvec2 clipPos_offset = clipPos.xy + oneTap;\nfloat block0, block1, block2, block3;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(dot(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock1 = step(dot(texture2D(cc_shadowMap, vec2(clipPos_offset.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock2 = step(dot(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock3 = step(dot(texture2D(cc_shadowMap, vec2(clipPos_offset.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\n} else {\nblock0 = step(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos.y)).x, offsetDepth);\nblock1 = step(texture2D(cc_shadowMap, vec2(clipPos_offset.x, clipPos.y)).x, offsetDepth);\nblock2 = step(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset.y)).x, offsetDepth);\nblock3 = step(texture2D(cc_shadowMap, vec2(clipPos_offset.x, clipPos_offset.y)).x, offsetDepth);\n}\nfloat coefX   = mod(clipPos.x, oneTap.x) * cc_shadowWHPBInfo.x;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block2, block3, coefX);\nfloat coefY   = mod(clipPos.y, oneTap.y) * cc_shadowWHPBInfo.y;;\nreturn mix(resultX, resultY, coefY);\n}\nfloat CCGetShadowFactorSoft2X (vec4 shadowPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat bias = cc_shadowWHPBInfo.w;\nfloat offsetDepth = clipPos.z - bias;\nvec2 mapSize = cc_shadowWHPBInfo.xy;\nvec2 oneTap = 1.0 / mapSize;\nfloat clipPos_offset_L = clipPos.x - oneTap.x;\nfloat clipPos_offset_R = clipPos.x + oneTap.x;\nfloat clipPos_offset_U = clipPos.y - oneTap.y;\nfloat clipPos_offset_D = clipPos.y + oneTap.y;\nfloat block0, block1, block2, block3, block4, block5, block6, block7, block8;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(dot(texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock1 = step(dot(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock2 = step(dot(texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock3 = step(dot(texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock4 = step(dot(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock5 = step(dot(texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock6 = step(dot(texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock7 = step(dot(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock8 = step(dot(texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\n} else {\nblock0 = step(texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_U)).x, offsetDepth);\nblock1 = step(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset_U)).x, offsetDepth);\nblock2 = step(texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_U)).x, offsetDepth);\nblock3 = step(texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos.y)).x, offsetDepth);\nblock4 = step(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos.y)).x, offsetDepth);\nblock5 = step(texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos.y)).x, offsetDepth);\nblock6 = step(texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_D)).x, offsetDepth);\nblock7 = step(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset_D)).x, offsetDepth);\nblock8 = step(texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_D)).x, offsetDepth);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * mapSize.x;\nfloat coefY = mod(clipPos.y, oneTap.y) * mapSize.y;\nfloat shadow = 0.0;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block3, block4, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block1, block2, coefX);\nresultY = mix(block4, block5, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block3, block4, coefX);\nresultY = mix(block6, block7, coefX);\nshadow += mix(resultX, resultY, coefY);\nresultX = mix(block4, block5, coefX);\nresultY = mix(block7, block8, coefX);\nshadow += mix(resultX, resultY, coefY);\nreturn shadow * 0.25;\n}\nfloat CCGetSpotLightShadowFactorHard (vec4 shadowPos, vec3 worldPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nfloat shadow = 0.0;\nfloat closestDepth = 0.0;\nfloat depth = 0.0;\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nif (cc_shadowLPNNInfo.y > 0.000001) {\nclosestDepth = dot(texture2D(cc_spotLightingMap, clipPos.xy), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\n} else {\nclosestDepth = texture2D(cc_spotLightingMap, clipPos.xy).x;\n}\nshadow = step(closestDepth, depth - cc_shadowWHPBInfo.w);\nreturn shadow;\n}\nfloat CCGetSpotLightShadowFactorSoft (vec4 shadowPos, vec3 worldPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nfloat offsetx = 1.0 / cc_shadowWHPBInfo.x;\nfloat offsety = 1.0 / cc_shadowWHPBInfo.y;\nfloat shadow = 0.0;\nfloat depth = 0.0;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nfloat closestDepth = dot(texture2D(cc_spotLightingMap, vec2(clipPos.x - offsetx, clipPos.y - offsety)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = dot(texture2D(cc_spotLightingMap, vec2(clipPos.x - offsetx, clipPos.y + offsety)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = dot(texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = dot(texture2D(cc_spotLightingMap, vec2(clipPos.x + offsetx, clipPos.y - offsety)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = dot(texture2D(cc_spotLightingMap, vec2(clipPos.x + offsetx, clipPos.y + offsety)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\n} else {\nfloat closestDepth = texture2D(cc_spotLightingMap, vec2(clipPos.x - offsetx, clipPos.y - offsety)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = texture2D(cc_spotLightingMap, vec2(clipPos.x - offsetx, clipPos.y + offsety)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = texture2D(cc_spotLightingMap, vec2(clipPos.x + offsetx, clipPos.y - offsety)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = texture2D(cc_spotLightingMap, vec2(clipPos.x + offsetx, clipPos.y + offsety)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\n}\nreturn shadow / 5.0;\n}\nfloat CCGetSpotLightShadowFactorSoft2X (vec4 shadowPos, vec3 worldPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nfloat offsetx = 1.0 / cc_shadowWHPBInfo.x;\nfloat offsety = 1.0 / cc_shadowWHPBInfo.y;\nfloat shadow = 0.0;\nfloat depth = 0.0;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nfor (int i = -1; i <= 1; i++) {\nfor (int j = -1; j <= 1; j++) {\nfloat closestDepth = dot(texture2D(cc_spotLightingMap, clipPos.xy + vec2(i, j) * vec2(offsetx, offsety)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\n}\n}\n} else {\nfor (int i = -1; i <= 1; i++) {\nfor (int j = -1; j <= 1; j++) {\nfloat closestDepth = texture2D(cc_spotLightingMap, clipPos.xy + vec2(i, j) * vec2(offsetx, offsety)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\n}\n}\n}\nreturn shadow / 9.0;\n}\n#endif\n#if CC_USE_IBL\nuniform samplerCube cc_environment;\nvec3 unpackRGBE (vec4 rgbe) {\nreturn rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\nvec4 fragTextureLod (sampler2D tex, vec2 coord, float lod) {\n#ifdef GL_EXT_shader_texture_lod\nreturn texture2DLodEXT(tex, coord, lod);\n#else\nreturn texture2D(tex, coord, lod);\n#endif\n}\nvec4 fragTextureLod (samplerCube tex, vec3 coord, float lod) {\n#ifdef GL_EXT_shader_texture_lod\nreturn textureCubeLodEXT(tex, coord, lod);\n#else\nreturn textureCube(tex, coord, lod);\n#endif\n}\n#endif\nfloat GGXMobile (float roughness, float NoH, vec3 H, vec3 N) {\nvec3 NxH = cross(N, H);\nfloat OneMinusNoHSqr = dot(NxH, NxH);\nfloat a = roughness * roughness;\nfloat n = NoH * a;\nfloat p = a / (OneMinusNoHSqr + n * n);\nreturn p * p;\n}\nfloat CalcSpecular (float roughness, float NoH, vec3 H, vec3 N) {\nreturn (roughness * 0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox (vec3 specular, float roughness, float NoV) {\nconst vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\nconst vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\nvec4 r = roughness * c0 + c1;\nfloat a004 = min(r.x * r.x, exp2(-9.28 * NoV)) * r.x + r.y;\nvec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;\nAB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\nreturn specular * AB.x + AB.y;\n}\nstruct StandardSurface {\nvec4 albedo;\nvec3 position;\nvec3 normal;\nvec3 emissive;\nvec3 lightmap;\nfloat lightmap_test;\nfloat roughness;\nfloat metallic;\nfloat occlusion;\n};\nvec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) {\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - s.position);\nfloat NV = max(abs(dot(N, V)), 0.001);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 L = normalize(-cc_mainLitDir.xyz);\nvec3 H = normalize(L + V);\nfloat NH = max(dot(N, H), 0.0);\nfloat NL = max(dot(N, L), 0.001);\nvec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w;\nvec3 diffuseContrib = diffuse;\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nif (s.lightmap_test > 0.0001) {\nfinalColor = s.lightmap.rgb;\n}\n#else\ndiffuseContrib /= 3.14159265359;\n#endif\nvec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\nvec3 dirlightContrib = (diffuseContrib + specularContrib);\n#if CC_RECEIVE_SHADOW\n{\nfloat pcf = cc_shadowWHPBInfo.z + 0.001;\nfloat shadowAttenuation = 0.0;\nfloat cosAngle = clamp(1.0 - dot(N, L.xyz), 0.0, 1.0);\nvec3 projWorldPos = shadowPos.xyz + cosAngle * cc_shadowLPNNInfo.z * N;\nvec4 pos = vec4(projWorldPos.xyz, shadowPos.w);\nif (pcf > 2.0) shadowAttenuation = CCGetShadowFactorSoft2X(pos);\nelse if (pcf > 1.0) shadowAttenuation = CCGetShadowFactorSoft(pos);\nelse shadowAttenuation = CCGetShadowFactorHard(pos);\nvec3 shadowColor = cc_shadowColor.rgb * cc_shadowColor.a + dirlightContrib.rgb * (1.0 - cc_shadowColor.a);\nif (cc_shadowNFLSInfo.w > 0.000001) {\ndirlightContrib.rgb = shadowColor.rgb * shadowAttenuation + dirlightContrib.rgb * (1.0 - shadowAttenuation);\n} else {\ndirlightContrib.rgb = shadowColor.rgb * shadowAttenuation * NL + dirlightContrib.rgb * (1.0 - shadowAttenuation * NL);\n}\n}\n#endif\nfinalColor *= dirlightContrib;\nfloat fAmb = 0.5 - N.y * 0.5;\nvec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\nfinalColor += (ambDiff.rgb * diffuse);\n#if CC_USE_IBL\nvec3 R = normalize(reflect(-V, N));\nvec4 envmap = fragTextureLod(cc_environment, R, s.roughness * cc_ambientGround.w);\n#if CC_USE_IBL == 2\nvec3 env = unpackRGBE(envmap);\n#else\nvec3 env = SRGBToLinear(envmap.rgb);\n#endif\nfinalColor += env * cc_ambientSky.w * specular;\n#endif\nfinalColor = finalColor * s.occlusion;\n#if CC_USE_HDR\ns.emissive *= cc_exposure.w;\n#endif\nfinalColor += s.emissive;\nreturn vec4(finalColor, s.albedo.a);\n}\nvec3 ACESToneMap (vec3 color) {\ncolor = min(color, vec3(8.0));\nconst float A = 2.51;\nconst float B = 0.03;\nconst float C = 2.43;\nconst float D = 0.59;\nconst float E = 0.14;\nreturn (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n#if !CC_USE_HDR\ncolor.rgb = sqrt(ACESToneMap(color.rgb));\n#endif\nreturn color;\n}\nvarying float v_fog_factor;\nvarying highp vec4 v_shadowPos;\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nvarying vec3 v_luv;\nuniform sampler2D cc_lightingMap;\nvec3 UnpackLightingmap(vec4 color) {\nvec3 c;\nfloat e = 1.0 + color.a * (8.0 - 1.0);\nc.r = color.r * e;\nc.g = color.g * e;\nc.b = color.b * e;\nreturn c;\n}\n#endif\nvarying highp vec3 v_position;\nvarying mediump vec3 v_normal;\n#if USE_NORMALMAP\nvarying mediump vec3 v_tangent;\nvarying mediump vec3 v_binormal;\n#endif\nvarying mediump vec2 uvw;\nvarying mediump vec2 uv0;\nvarying mediump vec2 uv1;\nvarying mediump vec2 uv2;\nvarying mediump vec2 uv3;\nvarying mediump vec3 diffuse;\nvarying mediump vec3 luv;\nuniform vec4 metallic;\nuniform vec4 roughness;\nuniform sampler2D weightMap;\nuniform sampler2D detailMap0;\nuniform sampler2D detailMap1;\nuniform sampler2D detailMap2;\nuniform sampler2D detailMap3;\nuniform sampler2D normalMap0;\nuniform sampler2D normalMap1;\nuniform sampler2D normalMap2;\nuniform sampler2D normalMap3;\nuniform sampler2D lightMap;\nvoid surf (out StandardSurface s) {\n#if LAYERS > 1\nvec4 w = texture2D(weightMap, uvw);\n#endif\nvec4 baseColor = vec4(0, 0, 0, 0);\n#if LAYERS == 1\nbaseColor = texture2D(detailMap0, uv0);\n#elif LAYERS == 2\nbaseColor += texture2D(detailMap0, uv0) * w.r;\nbaseColor += texture2D(detailMap1, uv1) * w.g;\n#elif LAYERS == 3\nbaseColor += texture2D(detailMap0, uv0) * w.r;\nbaseColor += texture2D(detailMap1, uv1) * w.g;\nbaseColor += texture2D(detailMap2, uv2) * w.b;\n#elif LAYERS == 4\nbaseColor += texture2D(detailMap0, uv0) * w.r;\nbaseColor += texture2D(detailMap1, uv1) * w.g;\nbaseColor += texture2D(detailMap2, uv2) * w.b;\nbaseColor += texture2D(detailMap3, uv3) * w.a;\n#else\nbaseColor = texture2D(detailMap0, uv0);\n#endif\ns.position = v_position;\n#if USE_NORMALMAP\nvec4 baseNormal = vec4(0, 0, 0, 0);\n#if LAYERS == 1\nbaseNormal = texture2D(normalMap0, uv0);\n#elif LAYERS == 2\nbaseNormal += texture2D(normalMap0, uv0) * w.r;\nbaseNormal += texture2D(normalMap1, uv1) * w.g;\n#elif LAYERS == 3\nbaseNormal += texture2D(normalMap0, uv0) * w.r;\nbaseNormal += texture2D(normalMap1, uv1) * w.g;\nbaseNormal += texture2D(normalMap2, uv2) * w.b;\n#elif LAYERS == 4\nbaseNormal += texture2D(normalMap0, uv0) * w.r;\nbaseNormal += texture2D(normalMap1, uv1) * w.g;\nbaseNormal += texture2D(normalMap2, uv2) * w.b;\nbaseNormal += texture2D(normalMap3, uv3) * w.a;\n#else\nbaseNormal = texture2D(normalMap0, uv0);\n#endif\nvec3 nmmp = baseNormal.xyz - vec3(0.5);\ns.normal =\nnmmp.x * normalize(v_tangent) +\nnmmp.y * normalize(v_binormal) +\nnmmp.z * normalize(v_normal);\n#else\ns.normal = v_normal;\n#endif\ns.albedo = vec4(SRGBToLinear(baseColor.rgb), 1.0);\ns.occlusion = 1.0;\n#if USE_PBR\ns.roughness = 0.0;\n#if LAYERS == 1\ns.roughness = roughness.x;\n#elif LAYERS == 2\ns.roughness += roughness.x * w.r;\ns.roughness += roughness.y * w.g;\n#elif LAYERS == 3\ns.roughness += roughness.x * w.r;\ns.roughness += roughness.y * w.g;\ns.roughness += roughness.z * w.b;\n#elif LAYERS == 4\ns.roughness += roughness.x * w.r;\ns.roughness += roughness.y * w.g;\ns.roughness += roughness.z * w.b;\ns.roughness += roughness.w * w.a;\n#else\ns.roughness = 1.0;\n#endif\ns.metallic = 0.0;\n#if LAYERS == 1\ns.metallic = metallic.x;\n#elif LAYERS == 2\ns.metallic += metallic.x * w.r;\ns.metallic += metallic.y * w.g;\n#elif LAYERS == 3\ns.metallic += metallic.x * w.r;\ns.metallic += metallic.y * w.g;\ns.metallic += metallic.z * w.b;\n#elif LAYERS == 4\ns.metallic += metallic.x * w.r;\ns.metallic += metallic.y * w.g;\ns.metallic += metallic.z * w.b;\ns.metallic += metallic.w * w.a;\n#else\ns.metallic = 0.0;\n#endif\n#else\ns.roughness = 1.0;\ns.metallic = 0.0;\n#endif\ns.emissive = vec3(0.0, 0.0, 0.0);\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nvec4 lightColor = texture2D(lightMap, luv.xy);\ns.lightmap = UnpackLightingmap(lightColor);\ns.lightmap_test = luv.z;\n#endif\n}\n#if CC_FORWARD_ADD\n#if CC_PIPELINE_TYPE == 0\n# define LIGHTS_PER_PASS 1\n#else\n# define LIGHTS_PER_PASS 10\n#endif\nuniform highp vec4 cc_lightPos[LIGHTS_PER_PASS];\nuniform vec4 cc_lightColor[LIGHTS_PER_PASS];\nuniform vec4 cc_lightSizeRangeAngle[LIGHTS_PER_PASS];\nuniform vec4 cc_lightDir[LIGHTS_PER_PASS];\nfloat SmoothDistAtt (float distSqr, float invSqrAttRadius) {\nfloat factor = distSqr * invSqrAttRadius;\nfloat smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\nreturn smoothFactor * smoothFactor;\n}\nfloat GetDistAtt (float distSqr, float invSqrAttRadius) {\nfloat attenuation = 1.0 / max(distSqr, 0.01*0.01);\nattenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\nreturn attenuation;\n}\nfloat GetAngleAtt (vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\nfloat cd = dot(litDir, L);\nfloat attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\nreturn (attenuation * attenuation);\n}\nvec4 CCStandardShadingAdditive (StandardSurface s, vec4 shadowPos) {\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 diffuseContrib = diffuse / 3.14159265359;\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - s.position);\nfloat NV = max(abs(dot(N, V)), 0.001);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 finalColor = vec3(0.0);\nint numLights = CC_PIPELINE_TYPE == 0 ? LIGHTS_PER_PASS : int(cc_lightDir[0].w);\nfor (int i = 0; i < LIGHTS_PER_PASS; i++) {\nif (i >= numLights) break;\nvec3 SLU = cc_lightPos[i].xyz - s.position;\nvec3 SL = normalize(SLU);\nvec3 SH = normalize(SL + V);\nfloat SNL = max(dot(N, SL), 0.001);\nfloat SNH = max(dot(N, SH), 0.0);\nfloat distSqr = dot(SLU, SLU);\nfloat litRadius = cc_lightSizeRangeAngle[i].x;\nfloat litRadiusSqr = litRadius * litRadius;\nfloat illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\nfloat attRadiusSqrInv = 1.0 / max(cc_lightSizeRangeAngle[i].y, 0.01);\nattRadiusSqrInv *= attRadiusSqrInv;\nfloat att = GetDistAtt(distSqr, attRadiusSqrInv);\nvec3 lspec = specular * CalcSpecular(s.roughness, SNH, SH, N);\nif (cc_lightPos[i].w > 0.0) {\nfloat cosInner = max(dot(-cc_lightDir[i].xyz, SL), 0.01);\nfloat cosOuter = cc_lightSizeRangeAngle[i].z;\nfloat litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\nfloat litAngleOffset = -cosOuter * litAngleScale;\natt *= GetAngleAtt(SL, -cc_lightDir[i].xyz, litAngleScale, litAngleOffset);\n}\nvec3 lightColor = cc_lightColor[i].rgb;\n#if CC_RECEIVE_SHADOW\nif (cc_lightPos[i].w > 0.0) {\n{\nfloat pcf = cc_shadowWHPBInfo.z + 0.001;\nfloat shadowAttenuation = 0.0;\nfloat cosAngle = clamp(1.0 - dot(N, normalize(cc_lightPos[i].xyz - s.position.xyz)), 0.0, 1.0);\nvec3 projWorldPos = shadowPos.xyz + cosAngle * cc_shadowLPNNInfo.z * N;\nvec4 pos = vec4(projWorldPos.xyz, shadowPos.w);\nif (pcf > 2.0) shadowAttenuation = CCGetSpotLightShadowFactorSoft2X(pos, s.position);\nelse if (pcf > 1.0) shadowAttenuation = CCGetSpotLightShadowFactorSoft(pos, s.position);\nelse shadowAttenuation = CCGetSpotLightShadowFactorHard(pos, s.position);\nlightColor *= 1.0 - shadowAttenuation;\n}\n}\n#endif\nfinalColor += SNL * lightColor * cc_lightColor[i].w * illum * att * (diffuseContrib + lspec);\n}\nfinalColor = finalColor * s.occlusion;\nreturn vec4(finalColor, 0.0);\n}\nvoid main () {\nStandardSurface s; surf(s);\nvec4 color = CCStandardShadingAdditive(s, v_shadowPos);\ncolor = vec4(mix(CC_FORWARD_ADD > 0 ? vec3(0.0) : cc_fogColor.rgb, color.rgb, v_fog_factor), color.a);\ngl_FragData[0] = CCFragOutput(color);\n}\n#elif CC_PIPELINE_TYPE == 0\nvoid main () {\nStandardSurface s; surf(s);\nvec4 color = CCStandardShadingBase(s, v_shadowPos);\ncolor = vec4(mix(CC_FORWARD_ADD > 0 ? vec3(0.0) : cc_fogColor.rgb, color.rgb, v_fog_factor), color.a);\ngl_FragData[0] = CCFragOutput(color);\n}\n#elif CC_PIPELINE_TYPE == 1\nvoid main () {\nStandardSurface s; surf(s);\ngl_FragData[0] = s.albedo;\ngl_FragData[1] = vec4(s.position, s.roughness);\ngl_FragData[2] = vec4(s.normal, s.metallic);\ngl_FragData[3] = vec4(s.emissive, s.occlusion);\n}\n#endif"
            }, {
              "vert": "\nprecision highp float;\nuniform highp mat4 cc_matWorld;\nuniform highp mat4 cc_matLightViewProj;\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec2 a_texCoord;\nvarying vec2 v_clip_depth;\nvec4 vert () {\nvec4 worldPos;\nworldPos.x = cc_matWorld[3][0] + a_position.x;\nworldPos.y = cc_matWorld[3][1] + a_position.y;\nworldPos.z = cc_matWorld[3][2] + a_position.z;\nworldPos.w = 1.0;\nvec4 clipPos = cc_matLightViewProj * worldPos;\nv_clip_depth = clipPos.zw;\nreturn clipPos;\n}\nvoid main() { gl_Position = vert(); }",
              "frag": "\nprecision highp float;\nvec4 packDepthToRGBA (float depth) {\nvec4 ret = vec4(1.0, 255.0, 65025.0, 160581375.0) * depth;\nret = fract(ret);\nret -= ret.yzww * vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);\nreturn ret;\n}\nvarying vec2 v_clip_depth;\nvec4 frag () {\nreturn packDepthToRGBA(v_clip_depth.x / v_clip_depth.y * 0.5 + 0.5);\n}\nvoid main() { gl_FragColor = frag(); }"
            }], [{
              "vert": "\nprecision highp float;\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec2 a_texCoord;\nattribute vec4 a_tangent;\n#if CC_USE_MORPH\nattribute float a_vertexId;\nint getVertexId() {\nreturn int(a_vertexId);\n}\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 uv = getPixelCoordFromLocation(location, cc_displacementTextureInfo.xy);\nreturn texture2D(tex, uv);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture2D(tex, x)),\ndecode32(texture2D(tex, y)),\ndecode32(texture2D(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nuniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nuniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nuniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nattr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nattr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nattr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_joints;\nattribute vec4 a_weights;\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nattribute highp vec4 a_jointAnimInfo;\n#endif\nuniform highp vec4 cc_jointTextureInfo;\nuniform highp vec4 cc_jointAnimInfo;\nuniform highp sampler2D cc_jointTexture;\n#else\nuniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\n#if USE_INSTANCING\nhighp float j = 3.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n#else\nhighp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n#endif\nhighp float invSize = cc_jointTextureInfo.w;\nhighp float y = floor(j * invSize);\nhighp float x = floor(j - y * cc_jointTextureInfo.x);\ny = (y + 0.5) * invSize;\nvec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\n#if USE_INSTANCING\nhighp float j = 12.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n#else\nhighp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n#endif\nhighp float invSize = cc_jointTextureInfo.w;\nhighp float y = floor(j * invSize);\nhighp float x = floor(j - y * cc_jointTextureInfo.x);\ny = (y + 0.5) * invSize;\nvec4 v1 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\nmat4 m = skinMatrix();\nattr.position = m * attr.position;\nattr.normal = (m * vec4(attr.normal, 0.0)).xyz;\nattr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matProj;\nuniform highp vec4 cc_cameraPos;\nuniform mediump vec4 cc_fogBase;\nuniform mediump vec4 cc_fogAdd;\n#if USE_INSTANCING\nattribute vec4 a_matWorld0;\nattribute vec4 a_matWorld1;\nattribute vec4 a_matWorld2;\n#if USE_LIGHTMAP\nattribute vec4 a_lightingMapUVParam;\n#endif\n#elif USE_BATCHING\nattribute float a_dyn_batch_id;\nuniform highp mat4 cc_matWorlds[10];\n#else\nuniform highp mat4 cc_matWorld;\n#endif\nfloat LinearFog(vec4 pos) {\nvec4 wPos = pos;\nfloat cam_dis = distance(cc_cameraPos, wPos);\nfloat fogStart = cc_fogBase.x;\nfloat fogEnd = cc_fogBase.y;\nreturn clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = distance(cc_cameraPos, wPos) / fogAtten * 4.;\nfloat f = exp(-cam_dis * fogDensity);\nreturn f;\n}\nfloat ExpSquaredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = distance(cc_cameraPos, wPos) / fogAtten * 4.;\nfloat f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\nreturn f;\n}\nfloat LayeredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat _FogTop = cc_fogAdd.x;\nfloat _FogRange = cc_fogAdd.y;\nvec3 camWorldProj = cc_cameraPos.xyz;\ncamWorldProj.y = 0.;\nvec3 worldPosProj = wPos.xyz;\nworldPosProj.y = 0.;\nfloat fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\nfloat fDeltaY, fDensityIntegral;\nif (cc_cameraPos.y > _FogTop) {\nif (wPos.y < _FogTop) {\nfDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\nfDensityIntegral = fDeltaY * fDeltaY * 0.5;\n} else {\nfDeltaY = 0.;\nfDensityIntegral = 0.;\n}\n} else {\nif (wPos.y < _FogTop) {\nfloat fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfloat fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\nfDeltaY = abs(fDeltaA - fDeltaB);\nfDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n} else {\nfDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n}\n}\nfloat fDensity;\nif (fDeltaY != 0.) {\nfDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n} else {\nfDensity = 0.;\n}\nfloat f = exp(-fDensity);\nreturn f;\n}\nvarying float v_fog_factor;\n#if USE_VERTEX_COLOR\nattribute lowp vec4 a_color;\nvarying lowp vec4 v_color;\n#endif\n#if USE_TEXTURE\nvarying vec2 v_uv;\nuniform vec4 tilingOffset;\n#endif\nvec4 vert () {\nvec4 position;\nposition = vec4(a_position, 1.0);\n#if CC_USE_MORPH\napplyMorph(position);\n#endif\n#if CC_USE_SKINNING\nCCSkin(position);\n#endif\nmat4 matWorld;\n#if USE_INSTANCING\nmatWorld = mat4(\nvec4(a_matWorld0.xyz, 0.0),\nvec4(a_matWorld1.xyz, 0.0),\nvec4(a_matWorld2.xyz, 0.0),\nvec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n);\n#elif USE_BATCHING\nmatWorld = cc_matWorlds[int(a_dyn_batch_id)];\n#else\nmatWorld = cc_matWorld;\n#endif\n#if USE_TEXTURE\nv_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n#if SAMPLE_FROM_RT\nv_uv = cc_cameraPos.w > 1.0 ? vec2(v_uv.x, 1.0 - v_uv.y) : v_uv;\n#endif\n#endif\n#if USE_VERTEX_COLOR\nv_color = a_color;\n#endif\n#if CC_USE_FOG == 0\nv_fog_factor = LinearFog(matWorld * position);\n#elif CC_USE_FOG == 1\nv_fog_factor = ExpFog(matWorld * position);\n#elif CC_USE_FOG == 2\nv_fog_factor = ExpSquaredFog(matWorld * position);\n#elif CC_USE_FOG == 3\nv_fog_factor = LayeredFog(matWorld * position);\n#else\nv_fog_factor = 1.0;\n#endif\nreturn cc_matProj * (cc_matView * matWorld) * position;\n}\nvoid main() { gl_Position = vert(); }",
              "frag": "\nprecision highp float;\nuniform mediump vec4 cc_exposure;\nuniform mediump vec4 cc_fogColor;\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n#if CC_USE_HDR\ncolor.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n#endif\nreturn color;\n}\nvarying float v_fog_factor;\n#if USE_ALPHA_TEST\n#endif\n#if USE_TEXTURE\nvarying vec2 v_uv;\nuniform sampler2D mainTexture;\n#endif\nuniform vec4 mainColor;\nuniform vec4 colorScaleAndCutoff;\n#if USE_VERTEX_COLOR\nvarying lowp vec4 v_color;\n#endif\nvec4 frag () {\nvec4 o = mainColor;\no.rgb *= colorScaleAndCutoff.xyz;\n#if USE_VERTEX_COLOR\no *= v_color;\n#endif\n#if USE_TEXTURE\no *= texture2D(mainTexture, v_uv);\n#endif\n#if USE_ALPHA_TEST\nif (o.ALPHA_TEST_CHANNEL < colorScaleAndCutoff.w) discard;\n#endif\no = vec4(mix(CC_FORWARD_ADD > 0 ? vec3(0.0) : cc_fogColor.rgb, o.rgb, v_fog_factor), o.a);\nreturn CCFragOutput(o);\n}\nvoid main() { gl_FragColor = frag(); }"
            }], [{
              "vert": "\nprecision highp float;\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec2 a_texCoord;\nattribute vec4 a_tangent;\nuniform highp vec4 cc_cameraPos;\nvarying vec2 v_uv;\nvoid main () {\nvec4 position;\nposition = vec4(a_position, 1.0);\nposition.xy = cc_cameraPos.w == 0.0 ? vec2(position.xy.x, -position.xy.y) : position.xy;\ngl_Position = vec4(position.x, position.y, 1.0, 1.0);\nv_uv = a_texCoord;\n}",
              "frag": "\n#ifdef GL_EXT_shader_texture_lod\n#extension GL_EXT_shader_texture_lod: enable\n#endif\nprecision highp float;\nuniform highp vec4 cc_cameraPos;\nuniform mediump vec4 cc_exposure;\nuniform mediump vec4 cc_mainLitDir;\nuniform mediump vec4 cc_mainLitColor;\nuniform mediump vec4 cc_ambientSky;\nuniform mediump vec4 cc_ambientGround;\nuniform mediump vec4 cc_fogColor;\nuniform mediump vec4 cc_fogBase;\nuniform mediump vec4 cc_fogAdd;\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nuniform highp mat4 cc_matLightView;\nuniform highp mat4 cc_matLightViewProj;\nuniform lowp vec4 cc_shadowNFLSInfo;\nuniform lowp vec4 cc_shadowWHPBInfo;\nuniform lowp vec4 cc_shadowLPNNInfo;\nuniform lowp vec4 cc_shadowColor;\n#if CC_RECEIVE_SHADOW\nuniform sampler2D cc_shadowMap;\nuniform sampler2D cc_spotLightingMap;\nfloat CCGetLinearDepth (vec3 worldPos) {\nvec4 viewStartPos = cc_matLightView * vec4(worldPos.xyz, 1.0);\nfloat dist = length(viewStartPos.xyz);\nreturn cc_shadowNFLSInfo.x + (-dist / (cc_shadowNFLSInfo.y - cc_shadowNFLSInfo.x));\n}\nfloat CCGetShadowFactorHard (vec4 shadowPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nfloat shadow = 0.0;\nfloat closestDepth = 0.0;\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nclosestDepth = dot(texture2D(cc_shadowMap, clipPos.xy), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\n} else {\nclosestDepth = texture2D(cc_shadowMap, clipPos.xy).x;\n}\nshadow = step(closestDepth, clipPos.z- cc_shadowWHPBInfo.w);\nreturn shadow;\n}\nfloat CCGetShadowFactorSoft (vec4 shadowPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat offsetDepth = clipPos.z - cc_shadowWHPBInfo.w;\nvec2 oneTap = 1.0 / cc_shadowWHPBInfo.xy;\nvec2 clipPos_offset = clipPos.xy + oneTap;\nfloat block0, block1, block2, block3;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(dot(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock1 = step(dot(texture2D(cc_shadowMap, vec2(clipPos_offset.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock2 = step(dot(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock3 = step(dot(texture2D(cc_shadowMap, vec2(clipPos_offset.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\n} else {\nblock0 = step(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos.y)).x, offsetDepth);\nblock1 = step(texture2D(cc_shadowMap, vec2(clipPos_offset.x, clipPos.y)).x, offsetDepth);\nblock2 = step(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset.y)).x, offsetDepth);\nblock3 = step(texture2D(cc_shadowMap, vec2(clipPos_offset.x, clipPos_offset.y)).x, offsetDepth);\n}\nfloat coefX   = mod(clipPos.x, oneTap.x) * cc_shadowWHPBInfo.x;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block2, block3, coefX);\nfloat coefY   = mod(clipPos.y, oneTap.y) * cc_shadowWHPBInfo.y;;\nreturn mix(resultX, resultY, coefY);\n}\nfloat CCGetShadowFactorSoft2X (vec4 shadowPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat bias = cc_shadowWHPBInfo.w;\nfloat offsetDepth = clipPos.z - bias;\nvec2 mapSize = cc_shadowWHPBInfo.xy;\nvec2 oneTap = 1.0 / mapSize;\nfloat clipPos_offset_L = clipPos.x - oneTap.x;\nfloat clipPos_offset_R = clipPos.x + oneTap.x;\nfloat clipPos_offset_U = clipPos.y - oneTap.y;\nfloat clipPos_offset_D = clipPos.y + oneTap.y;\nfloat block0, block1, block2, block3, block4, block5, block6, block7, block8;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(dot(texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock1 = step(dot(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock2 = step(dot(texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock3 = step(dot(texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock4 = step(dot(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock5 = step(dot(texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock6 = step(dot(texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock7 = step(dot(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock8 = step(dot(texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\n} else {\nblock0 = step(texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_U)).x, offsetDepth);\nblock1 = step(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset_U)).x, offsetDepth);\nblock2 = step(texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_U)).x, offsetDepth);\nblock3 = step(texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos.y)).x, offsetDepth);\nblock4 = step(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos.y)).x, offsetDepth);\nblock5 = step(texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos.y)).x, offsetDepth);\nblock6 = step(texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_D)).x, offsetDepth);\nblock7 = step(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset_D)).x, offsetDepth);\nblock8 = step(texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_D)).x, offsetDepth);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * mapSize.x;\nfloat coefY = mod(clipPos.y, oneTap.y) * mapSize.y;\nfloat shadow = 0.0;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block3, block4, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block1, block2, coefX);\nresultY = mix(block4, block5, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block3, block4, coefX);\nresultY = mix(block6, block7, coefX);\nshadow += mix(resultX, resultY, coefY);\nresultX = mix(block4, block5, coefX);\nresultY = mix(block7, block8, coefX);\nshadow += mix(resultX, resultY, coefY);\nreturn shadow * 0.25;\n}\nfloat CCGetSpotLightShadowFactorHard (vec4 shadowPos, vec3 worldPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nfloat shadow = 0.0;\nfloat closestDepth = 0.0;\nfloat depth = 0.0;\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nif (cc_shadowLPNNInfo.y > 0.000001) {\nclosestDepth = dot(texture2D(cc_spotLightingMap, clipPos.xy), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\n} else {\nclosestDepth = texture2D(cc_spotLightingMap, clipPos.xy).x;\n}\nshadow = step(closestDepth, depth - cc_shadowWHPBInfo.w);\nreturn shadow;\n}\nfloat CCGetSpotLightShadowFactorSoft (vec4 shadowPos, vec3 worldPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nfloat offsetx = 1.0 / cc_shadowWHPBInfo.x;\nfloat offsety = 1.0 / cc_shadowWHPBInfo.y;\nfloat shadow = 0.0;\nfloat depth = 0.0;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nfloat closestDepth = dot(texture2D(cc_spotLightingMap, vec2(clipPos.x - offsetx, clipPos.y - offsety)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = dot(texture2D(cc_spotLightingMap, vec2(clipPos.x - offsetx, clipPos.y + offsety)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = dot(texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = dot(texture2D(cc_spotLightingMap, vec2(clipPos.x + offsetx, clipPos.y - offsety)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = dot(texture2D(cc_spotLightingMap, vec2(clipPos.x + offsetx, clipPos.y + offsety)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\n} else {\nfloat closestDepth = texture2D(cc_spotLightingMap, vec2(clipPos.x - offsetx, clipPos.y - offsety)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = texture2D(cc_spotLightingMap, vec2(clipPos.x - offsetx, clipPos.y + offsety)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = texture2D(cc_spotLightingMap, vec2(clipPos.x + offsetx, clipPos.y - offsety)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = texture2D(cc_spotLightingMap, vec2(clipPos.x + offsetx, clipPos.y + offsety)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\n}\nreturn shadow / 5.0;\n}\nfloat CCGetSpotLightShadowFactorSoft2X (vec4 shadowPos, vec3 worldPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nfloat offsetx = 1.0 / cc_shadowWHPBInfo.x;\nfloat offsety = 1.0 / cc_shadowWHPBInfo.y;\nfloat shadow = 0.0;\nfloat depth = 0.0;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nfor (int i = -1; i <= 1; i++) {\nfor (int j = -1; j <= 1; j++) {\nfloat closestDepth = dot(texture2D(cc_spotLightingMap, clipPos.xy + vec2(i, j) * vec2(offsetx, offsety)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\n}\n}\n} else {\nfor (int i = -1; i <= 1; i++) {\nfor (int j = -1; j <= 1; j++) {\nfloat closestDepth = texture2D(cc_spotLightingMap, clipPos.xy + vec2(i, j) * vec2(offsetx, offsety)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\n}\n}\n}\nreturn shadow / 9.0;\n}\n#endif\n#if CC_USE_IBL\nuniform samplerCube cc_environment;\nvec3 unpackRGBE (vec4 rgbe) {\nreturn rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\nvec4 fragTextureLod (sampler2D tex, vec2 coord, float lod) {\n#ifdef GL_EXT_shader_texture_lod\nreturn texture2DLodEXT(tex, coord, lod);\n#else\nreturn texture2D(tex, coord, lod);\n#endif\n}\nvec4 fragTextureLod (samplerCube tex, vec3 coord, float lod) {\n#ifdef GL_EXT_shader_texture_lod\nreturn textureCubeLodEXT(tex, coord, lod);\n#else\nreturn textureCube(tex, coord, lod);\n#endif\n}\n#endif\nfloat GGXMobile (float roughness, float NoH, vec3 H, vec3 N) {\nvec3 NxH = cross(N, H);\nfloat OneMinusNoHSqr = dot(NxH, NxH);\nfloat a = roughness * roughness;\nfloat n = NoH * a;\nfloat p = a / (OneMinusNoHSqr + n * n);\nreturn p * p;\n}\nfloat CalcSpecular (float roughness, float NoH, vec3 H, vec3 N) {\nreturn (roughness * 0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox (vec3 specular, float roughness, float NoV) {\nconst vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\nconst vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\nvec4 r = roughness * c0 + c1;\nfloat a004 = min(r.x * r.x, exp2(-9.28 * NoV)) * r.x + r.y;\nvec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;\nAB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\nreturn specular * AB.x + AB.y;\n}\nstruct StandardSurface {\nvec4 albedo;\nvec3 position;\nvec3 normal;\nvec3 emissive;\nvec3 lightmap;\nfloat lightmap_test;\nfloat roughness;\nfloat metallic;\nfloat occlusion;\n};\nvec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) {\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - s.position);\nfloat NV = max(abs(dot(N, V)), 0.001);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 L = normalize(-cc_mainLitDir.xyz);\nvec3 H = normalize(L + V);\nfloat NH = max(dot(N, H), 0.0);\nfloat NL = max(dot(N, L), 0.001);\nvec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w;\nvec3 diffuseContrib = diffuse;\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nif (s.lightmap_test > 0.0001) {\nfinalColor = s.lightmap.rgb;\n}\n#else\ndiffuseContrib /= 3.14159265359;\n#endif\nvec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\nvec3 dirlightContrib = (diffuseContrib + specularContrib);\n#if CC_RECEIVE_SHADOW\n{\nfloat pcf = cc_shadowWHPBInfo.z + 0.001;\nfloat shadowAttenuation = 0.0;\nfloat cosAngle = clamp(1.0 - dot(N, L.xyz), 0.0, 1.0);\nvec3 projWorldPos = shadowPos.xyz + cosAngle * cc_shadowLPNNInfo.z * N;\nvec4 pos = vec4(projWorldPos.xyz, shadowPos.w);\nif (pcf > 2.0) shadowAttenuation = CCGetShadowFactorSoft2X(pos);\nelse if (pcf > 1.0) shadowAttenuation = CCGetShadowFactorSoft(pos);\nelse shadowAttenuation = CCGetShadowFactorHard(pos);\nvec3 shadowColor = cc_shadowColor.rgb * cc_shadowColor.a + dirlightContrib.rgb * (1.0 - cc_shadowColor.a);\nif (cc_shadowNFLSInfo.w > 0.000001) {\ndirlightContrib.rgb = shadowColor.rgb * shadowAttenuation + dirlightContrib.rgb * (1.0 - shadowAttenuation);\n} else {\ndirlightContrib.rgb = shadowColor.rgb * shadowAttenuation * NL + dirlightContrib.rgb * (1.0 - shadowAttenuation * NL);\n}\n}\n#endif\nfinalColor *= dirlightContrib;\nfloat fAmb = 0.5 - N.y * 0.5;\nvec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\nfinalColor += (ambDiff.rgb * diffuse);\n#if CC_USE_IBL\nvec3 R = normalize(reflect(-V, N));\nvec4 envmap = fragTextureLod(cc_environment, R, s.roughness * cc_ambientGround.w);\n#if CC_USE_IBL == 2\nvec3 env = unpackRGBE(envmap);\n#else\nvec3 env = SRGBToLinear(envmap.rgb);\n#endif\nfinalColor += env * cc_ambientSky.w * specular;\n#endif\nfinalColor = finalColor * s.occlusion;\n#if CC_USE_HDR\ns.emissive *= cc_exposure.w;\n#endif\nfinalColor += s.emissive;\nreturn vec4(finalColor, s.albedo.a);\n}\n#if CC_PIPELINE_TYPE == 0\n# define LIGHTS_PER_PASS 1\n#else\n# define LIGHTS_PER_PASS 10\n#endif\nuniform highp vec4 cc_lightPos[LIGHTS_PER_PASS];\nuniform vec4 cc_lightColor[LIGHTS_PER_PASS];\nuniform vec4 cc_lightSizeRangeAngle[LIGHTS_PER_PASS];\nuniform vec4 cc_lightDir[LIGHTS_PER_PASS];\nfloat SmoothDistAtt (float distSqr, float invSqrAttRadius) {\nfloat factor = distSqr * invSqrAttRadius;\nfloat smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\nreturn smoothFactor * smoothFactor;\n}\nfloat GetDistAtt (float distSqr, float invSqrAttRadius) {\nfloat attenuation = 1.0 / max(distSqr, 0.01*0.01);\nattenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\nreturn attenuation;\n}\nfloat GetAngleAtt (vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\nfloat cd = dot(litDir, L);\nfloat attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\nreturn (attenuation * attenuation);\n}\nvec4 CCStandardShadingAdditive (StandardSurface s, vec4 shadowPos) {\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 diffuseContrib = diffuse / 3.14159265359;\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - s.position);\nfloat NV = max(abs(dot(N, V)), 0.001);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 finalColor = vec3(0.0);\nint numLights = CC_PIPELINE_TYPE == 0 ? LIGHTS_PER_PASS : int(cc_lightDir[0].w);\nfor (int i = 0; i < LIGHTS_PER_PASS; i++) {\nif (i >= numLights) break;\nvec3 SLU = cc_lightPos[i].xyz - s.position;\nvec3 SL = normalize(SLU);\nvec3 SH = normalize(SL + V);\nfloat SNL = max(dot(N, SL), 0.001);\nfloat SNH = max(dot(N, SH), 0.0);\nfloat distSqr = dot(SLU, SLU);\nfloat litRadius = cc_lightSizeRangeAngle[i].x;\nfloat litRadiusSqr = litRadius * litRadius;\nfloat illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\nfloat attRadiusSqrInv = 1.0 / max(cc_lightSizeRangeAngle[i].y, 0.01);\nattRadiusSqrInv *= attRadiusSqrInv;\nfloat att = GetDistAtt(distSqr, attRadiusSqrInv);\nvec3 lspec = specular * CalcSpecular(s.roughness, SNH, SH, N);\nif (cc_lightPos[i].w > 0.0) {\nfloat cosInner = max(dot(-cc_lightDir[i].xyz, SL), 0.01);\nfloat cosOuter = cc_lightSizeRangeAngle[i].z;\nfloat litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\nfloat litAngleOffset = -cosOuter * litAngleScale;\natt *= GetAngleAtt(SL, -cc_lightDir[i].xyz, litAngleScale, litAngleOffset);\n}\nvec3 lightColor = cc_lightColor[i].rgb;\n#if CC_RECEIVE_SHADOW\nif (cc_lightPos[i].w > 0.0) {\n{\nfloat pcf = cc_shadowWHPBInfo.z + 0.001;\nfloat shadowAttenuation = 0.0;\nfloat cosAngle = clamp(1.0 - dot(N, normalize(cc_lightPos[i].xyz - s.position.xyz)), 0.0, 1.0);\nvec3 projWorldPos = shadowPos.xyz + cosAngle * cc_shadowLPNNInfo.z * N;\nvec4 pos = vec4(projWorldPos.xyz, shadowPos.w);\nif (pcf > 2.0) shadowAttenuation = CCGetSpotLightShadowFactorSoft2X(pos, s.position);\nelse if (pcf > 1.0) shadowAttenuation = CCGetSpotLightShadowFactorSoft(pos, s.position);\nelse shadowAttenuation = CCGetSpotLightShadowFactorHard(pos, s.position);\nlightColor *= 1.0 - shadowAttenuation;\n}\n}\n#endif\nfinalColor += SNL * lightColor * cc_lightColor[i].w * illum * att * (diffuseContrib + lspec);\n}\nfinalColor = finalColor * s.occlusion;\nreturn vec4(finalColor, 0.0);\n}\nvec3 ACESToneMap (vec3 color) {\ncolor = min(color, vec3(8.0));\nconst float A = 2.51;\nconst float B = 0.03;\nconst float C = 2.43;\nconst float D = 0.59;\nconst float E = 0.14;\nreturn (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n#if !CC_USE_HDR\ncolor.rgb = sqrt(ACESToneMap(color.rgb));\n#endif\nreturn color;\n}\nfloat LinearFog(vec4 pos) {\nvec4 wPos = pos;\nfloat cam_dis = distance(cc_cameraPos, wPos);\nfloat fogStart = cc_fogBase.x;\nfloat fogEnd = cc_fogBase.y;\nreturn clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = distance(cc_cameraPos, wPos) / fogAtten * 4.;\nfloat f = exp(-cam_dis * fogDensity);\nreturn f;\n}\nfloat ExpSquaredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = distance(cc_cameraPos, wPos) / fogAtten * 4.;\nfloat f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\nreturn f;\n}\nfloat LayeredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat _FogTop = cc_fogAdd.x;\nfloat _FogRange = cc_fogAdd.y;\nvec3 camWorldProj = cc_cameraPos.xyz;\ncamWorldProj.y = 0.;\nvec3 worldPosProj = wPos.xyz;\nworldPosProj.y = 0.;\nfloat fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\nfloat fDeltaY, fDensityIntegral;\nif (cc_cameraPos.y > _FogTop) {\nif (wPos.y < _FogTop) {\nfDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\nfDensityIntegral = fDeltaY * fDeltaY * 0.5;\n} else {\nfDeltaY = 0.;\nfDensityIntegral = 0.;\n}\n} else {\nif (wPos.y < _FogTop) {\nfloat fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfloat fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\nfDeltaY = abs(fDeltaA - fDeltaB);\nfDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n} else {\nfDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n}\n}\nfloat fDensity;\nif (fDeltaY != 0.) {\nfDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n} else {\nfDensity = 0.;\n}\nfloat f = exp(-fDensity);\nreturn f;\n}\nvarying vec2 v_uv;\nuniform sampler2D cc_gbuffer_albedoMap;\nuniform sampler2D cc_gbuffer_positionMap;\nuniform sampler2D cc_gbuffer_normalMap;\nuniform sampler2D cc_gbuffer_emissiveMap;\nvoid main () {\nStandardSurface s;\nvec4 albedoMap = texture2D(cc_gbuffer_albedoMap,v_uv);\nvec4 positionMap = texture2D(cc_gbuffer_positionMap,v_uv);\nvec4 normalMap = texture2D(cc_gbuffer_normalMap,v_uv);\nvec4 emissiveMap = texture2D(cc_gbuffer_emissiveMap,v_uv);\ns.albedo = albedoMap;\ns.position = positionMap.xyz;\ns.roughness = positionMap.w;\ns.normal = normalMap.xyz;\ns.metallic = normalMap.w;\ns.emissive = emissiveMap.xyz;\ns.occlusion = emissiveMap.w;\nfloat fogFactor;\n#if CC_USE_FOG == 0\nfogFactor = LinearFog(vec4(s.position, 1));\n#elif CC_USE_FOG == 1\nfogFactor = ExpFog(vec4(s.position, 1));\n#elif CC_USE_FOG == 2\nfogFactor = ExpSquaredFog(vec4(s.position, 1));\n#elif CC_USE_FOG == 3\nfogFactor = LayeredFog(vec4(s.position, 1));\n#else\nfogFactor = 1.0;\n#endif\nvec4 shadowPos;\nshadowPos = cc_matLightViewProj * vec4(s.position, 1);\nvec4 color = CCStandardShadingBase(s, shadowPos) +\nCCStandardShadingAdditive(s, shadowPos);\ncolor = vec4(mix(CC_FORWARD_ADD > 0 ? vec3(0.0) : cc_fogColor.rgb, color.rgb, fogFactor), color.a);\ngl_FragColor = CCFragOutput(color);\n}"
            }], [{
              "vert": "\nprecision highp float;\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec2 a_texCoord;\nattribute vec4 a_tangent;\n#if CC_USE_MORPH\nattribute float a_vertexId;\nint getVertexId() {\nreturn int(a_vertexId);\n}\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 uv = getPixelCoordFromLocation(location, cc_displacementTextureInfo.xy);\nreturn texture2D(tex, uv);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture2D(tex, x)),\ndecode32(texture2D(tex, y)),\ndecode32(texture2D(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nuniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nuniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nuniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nattr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nattr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nattr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_joints;\nattribute vec4 a_weights;\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nattribute highp vec4 a_jointAnimInfo;\n#endif\nuniform highp vec4 cc_jointTextureInfo;\nuniform highp vec4 cc_jointAnimInfo;\nuniform highp sampler2D cc_jointTexture;\n#else\nuniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\n#if USE_INSTANCING\nhighp float j = 3.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n#else\nhighp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n#endif\nhighp float invSize = cc_jointTextureInfo.w;\nhighp float y = floor(j * invSize);\nhighp float x = floor(j - y * cc_jointTextureInfo.x);\ny = (y + 0.5) * invSize;\nvec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\n#if USE_INSTANCING\nhighp float j = 12.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n#else\nhighp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n#endif\nhighp float invSize = cc_jointTextureInfo.w;\nhighp float y = floor(j * invSize);\nhighp float x = floor(j - y * cc_jointTextureInfo.x);\ny = (y + 0.5) * invSize;\nvec4 v1 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\nmat4 m = skinMatrix();\nattr.position = m * attr.position;\nattr.normal = (m * vec4(attr.normal, 0.0)).xyz;\nattr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matProj;\n#if USE_INSTANCING\nattribute vec4 a_matWorld0;\nattribute vec4 a_matWorld1;\nattribute vec4 a_matWorld2;\n#if USE_LIGHTMAP\nattribute vec4 a_lightingMapUVParam;\n#endif\n#elif USE_BATCHING\nattribute float a_dyn_batch_id;\nuniform highp mat4 cc_matWorlds[10];\n#else\nuniform highp mat4 cc_matWorld;\n#endif\nuniform highp mat4 cc_matLightPlaneProj;\nvec4 vert () {\nvec4 position;\nposition = vec4(a_position, 1.0);\n#if CC_USE_MORPH\napplyMorph(position);\n#endif\n#if CC_USE_SKINNING\nCCSkin(position);\n#endif\nmat4 matWorld;\n#if USE_INSTANCING\nmatWorld = mat4(\nvec4(a_matWorld0.xyz, 0.0),\nvec4(a_matWorld1.xyz, 0.0),\nvec4(a_matWorld2.xyz, 0.0),\nvec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n);\n#elif USE_BATCHING\nmatWorld = cc_matWorlds[int(a_dyn_batch_id)];\n#else\nmatWorld = cc_matWorld;\n#endif\nposition = cc_matProj * (cc_matView * cc_matLightPlaneProj * matWorld) * position;\nposition.z -= 0.0001;\nreturn position;\n}\nvoid main() { gl_Position = vert(); }",
              "frag": "\nprecision mediump float;\nuniform lowp vec4 cc_shadowColor;\nuniform mediump vec4 cc_exposure;\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n#if CC_USE_HDR\ncolor.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n#endif\nreturn color;\n}\nvec4 frag () {\nreturn CCFragOutput(cc_shadowColor);\n}\nvoid main() { gl_FragColor = frag(); }"
            }], [{
              "vert": "\nprecision highp float;\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec2 a_texCoord;\nattribute vec4 a_tangent;\n#if CC_USE_MORPH\nattribute float a_vertexId;\nint getVertexId() {\nreturn int(a_vertexId);\n}\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 uv = getPixelCoordFromLocation(location, cc_displacementTextureInfo.xy);\nreturn texture2D(tex, uv);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture2D(tex, x)),\ndecode32(texture2D(tex, y)),\ndecode32(texture2D(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nuniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nuniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nuniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nattr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nattr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nattr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_joints;\nattribute vec4 a_weights;\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nattribute highp vec4 a_jointAnimInfo;\n#endif\nuniform highp vec4 cc_jointTextureInfo;\nuniform highp vec4 cc_jointAnimInfo;\nuniform highp sampler2D cc_jointTexture;\n#else\nuniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\n#if USE_INSTANCING\nhighp float j = 3.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n#else\nhighp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n#endif\nhighp float invSize = cc_jointTextureInfo.w;\nhighp float y = floor(j * invSize);\nhighp float x = floor(j - y * cc_jointTextureInfo.x);\ny = (y + 0.5) * invSize;\nvec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\n#if USE_INSTANCING\nhighp float j = 12.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n#else\nhighp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n#endif\nhighp float invSize = cc_jointTextureInfo.w;\nhighp float y = floor(j * invSize);\nhighp float x = floor(j - y * cc_jointTextureInfo.x);\ny = (y + 0.5) * invSize;\nvec4 v1 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\nmat4 m = skinMatrix();\nattr.position = m * attr.position;\nattr.normal = (m * vec4(attr.normal, 0.0)).xyz;\nattr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform highp vec4 cc_cameraPos;\nvarying vec2 v_uv;\nvoid main () {\nStandardVertInput In;\nIn.position = vec4(a_position, 1.0);\nIn.normal = a_normal;\nIn.tangent = a_tangent;\n#if CC_USE_MORPH\napplyMorph(In);\n#endif\n#if CC_USE_SKINNING\nCCSkin(In);\n#endif\nIn.position.xy = cc_cameraPos.w == 0.0 ? vec2(In.position.xy.x, -In.position.xy.y) : In.position.xy;\ngl_Position = In.position;\ngl_Position.y = gl_Position.y;\nv_uv = a_texCoord;\n}",
              "frag": "\nprecision highp float;\nuniform mediump vec4 cc_screenSize;\nvarying vec2 v_uv;\nuniform sampler2D cc_lighting_resultMap;\nvoid texcoords(vec2 fragCoord, vec2 resolution,\nout vec2 v_rgbNW, out vec2 v_rgbNE,\nout vec2 v_rgbSW, out vec2 v_rgbSE,\nout vec2 v_rgbM) {\nvec2 inverseVP = 1.0 / resolution.xy;\nv_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\nv_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\nv_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\nv_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\nv_rgbM = vec2(fragCoord * inverseVP);\n}\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 resolution,\nvec2 v_rgbNW, vec2 v_rgbNE,\nvec2 v_rgbSW, vec2 v_rgbSE,\nvec2 v_rgbM) {\nvec4 color;\nmediump vec2 inverseVP = vec2(1.0 / resolution.x, 1.0 / resolution.y);\nvec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\nvec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\nvec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\nvec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\nvec4 texColor = texture2D(tex, v_rgbM);\nvec3 rgbM  = texColor.xyz;\nvec3 luma = vec3(0.299, 0.587, 0.114);\nfloat lumaNW = dot(rgbNW, luma);\nfloat lumaNE = dot(rgbNE, luma);\nfloat lumaSW = dot(rgbSW, luma);\nfloat lumaSE = dot(rgbSE, luma);\nfloat lumaM  = dot(rgbM,  luma);\nfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\nfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\nmediump vec2 dir;\ndir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\ndir.y =  ((lumaNW + lumaSW) - (lumaNE + lumaSE));\nfloat dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n(0.25 * (1.0 / 8.0)), (1.0/ 128.0));\nfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\ndir = min(vec2(8.0, 8.0),\nmax(vec2(-8.0, -8.0),\ndir * rcpDirMin)) * inverseVP;\nvec3 rgbA = 0.5 * (\ntexture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\ntexture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\nvec3 rgbB = rgbA * 0.5 + 0.25 * (\ntexture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\ntexture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\nfloat lumaB = dot(rgbB, luma);\nif ((lumaB < lumaMin) || (lumaB > lumaMax))\ncolor = vec4(rgbA, texColor.a);\nelse\ncolor = vec4(rgbB, texColor.a);\nreturn color;\n}\nvoid main () {\nmediump vec2 v_rgbNW;\nmediump vec2 v_rgbNE;\nmediump vec2 v_rgbSW;\nmediump vec2 v_rgbSE;\nmediump vec2 v_rgbM;\nvec2 resolution = cc_screenSize.xy;\nvec2 fragCoord = v_uv * resolution;\ntexcoords(fragCoord, resolution, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\ngl_FragColor = fxaa(cc_lighting_resultMap, fragCoord, resolution, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}"
            }], [{
              "vert": "\nprecision highp float;\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matProj;\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec2 a_texCoord;\nattribute vec4 a_tangent;\nvarying mediump vec4 viewDir;\nvec4 vert () {\nviewDir = vec4(a_position, 1.0);\nmat4 matViewRotOnly = mat4(mat3(cc_matView));\nmat4 matProj = cc_matProj;\nif (matProj[3].w > 0.0) {\nvec2 scale = vec2(48.0, 24.0);\nmatProj[0].xy *= scale;\nmatProj[1].xy *= scale;\nmatProj[2].zw = vec2(-1.0);\nmatProj[3].zw = vec2(0.0);\n}\nvec4 pos = matProj * matViewRotOnly * viewDir;\npos.z = 0.99999 * pos.w;\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }",
              "frag": "\nprecision mediump float;\nuniform mediump vec4 cc_ambientSky;\nuniform samplerCube cc_environment;\nvec3 unpackRGBE (vec4 rgbe) {\nreturn rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nvec3 ACESToneMap (vec3 color) {\ncolor = min(color, vec3(8.0));\nconst float A = 2.51;\nconst float B = 0.03;\nconst float C = 2.43;\nconst float D = 0.59;\nconst float E = 0.14;\nreturn (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n#if !CC_USE_HDR\ncolor.rgb = sqrt(ACESToneMap(color.rgb));\n#endif\nreturn color;\n}\nvarying mediump vec4 viewDir;\nvec4 frag () {\n#if USE_RGBE_CUBEMAP\nvec3 c = unpackRGBE(textureCube(cc_environment, viewDir.xyz));\n#else\nvec3 c = SRGBToLinear(textureCube(cc_environment, viewDir.xyz).rgb);\n#endif\nreturn CCFragOutput(vec4(c * cc_ambientSky.w, 1.0));\n}\nvoid main() { gl_FragColor = frag(); }"
            }], [{
              "vert": "\nprecision mediump float;\nuniform highp mat4 cc_matViewProj;\nattribute vec3 a_position;\nattribute vec4 a_color;\nvarying vec2 v_uv;\nuniform vec4 offset;\nuniform vec4 digits[20];\nfloat getComponent(vec4 v, float i) {\nif (i < 1.0) { return v.x; }\nelse if (i < 2.0) { return v.y; }\nelse if (i < 3.0) { return v.z; }\nelse { return v.w; }\n}\nvec4 vert () {\nvec4 position = cc_matViewProj * vec4(a_position, 1.0);\nposition.xy += offset.xy;\nv_uv = a_color.xy;\nif (a_color.z >= 0.0) {\nfloat n = getComponent(digits[int(a_color.z)], a_color.w);\nv_uv += vec2(offset.z * n, 0.0);\n}\nreturn position;\n}\nvoid main() { gl_Position = vert(); }",
              "frag": "\nprecision mediump float;\nuniform mediump vec4 cc_exposure;\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n#if CC_USE_HDR\ncolor.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n#endif\nreturn color;\n}\nvarying vec2 v_uv;\nuniform sampler2D mainTexture;\nvec4 frag () {\nreturn CCFragOutput(texture2D(mainTexture, v_uv));\n}\nvoid main() { gl_FragColor = frag(); }"
            }], [{
              "vert": "\nprecision mediump float;\nattribute vec2 a_position;\nattribute vec2 a_texCoord;\nvarying vec2 v_uv;\nvarying float v_percent;\nuniform vec4 u_buffer0;\nuniform vec4 u_buffer1;\nuniform mat4 u_projection;\nvec4 vert () {\nvec2 worldPos = a_position * u_buffer1.xy + u_buffer1.zw;\nvec2 clipSpace = worldPos / u_buffer0.xy * 2.0 - 1.0;\nvec4 screenPos = u_projection * vec4(clipSpace, 0.0, 1.0);\nv_uv = a_texCoord;\nv_percent = u_buffer0.z;\nreturn screenPos;\n}\nvoid main() { gl_Position = vert(); }",
              "frag": "\nprecision mediump float;\nvarying vec2 v_uv;\nvarying float v_percent;\nuniform sampler2D mainTexture;\nvec4 frag () {\nvec4 color = texture2D(mainTexture, v_uv);\nfloat precent = clamp(v_percent, 0.0, 1.0);\ncolor.xyz *= precent;\nreturn color;\n}\nvoid main() { gl_FragColor = frag(); }"
            }]];

            var glsl3 = [[{
              "vert": "\nprecision mediump float;\nlayout(std140) uniform Constants {\nvec4 mainTiling_Offset;\nvec4 frameTile_velLenScale;\nvec4 scale;\n};\nlayout(std140) uniform CCGlobal {\nhighp   vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp   mat4 cc_matView;\nhighp   mat4 cc_matViewInv;\nhighp   mat4 cc_matProj;\nhighp   mat4 cc_matProjInv;\nhighp   mat4 cc_matViewProj;\nhighp   mat4 cc_matViewProjInv;\nhighp   vec4 cc_cameraPos;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\n};\nlayout(std140) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\n};\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\nmat3 m = mat3(xAxis,yAxis,zAxis);\nfloat trace = m[0][0] + m[1][1] + m[2][2];\nvec4 quat;\nif (trace > 0.) {\nfloat s = 0.5 / sqrt(trace + 1.0);\nquat.w = 0.25 / s;\nquat.x = (m[2][1] - m[1][2]) * s;\nquat.y = (m[0][2] - m[2][0]) * s;\nquat.z = (m[1][0] - m[0][1]) * s;\n} else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\nfloat s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\nquat.w = (m[2][1] - m[1][2]) / s;\nquat.x = 0.25 * s;\nquat.y = (m[0][1] + m[1][0]) / s;\nquat.z = (m[0][2] + m[2][0]) / s;\n} else if (m[1][1] > m[2][2]) {\nfloat s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\nquat.w = (m[0][2] - m[2][0]) / s;\nquat.x = (m[0][1] + m[1][0]) / s;\nquat.y = 0.25 * s;\nquat.z = (m[1][2] + m[2][1]) / s;\n} else {\nfloat s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\nquat.w = (m[1][0] - m[0][1]) / s;\nquat.x = (m[0][2] + m[2][0]) / s;\nquat.y = (m[1][2] + m[2][1]) / s;\nquat.z = 0.25 * s;\n}\nfloat len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\nif (len > 0.) {\nlen = 1. / sqrt(len);\nquat.x = quat.x * len;\nquat.y = quat.y * len;\nquat.z = quat.z * len;\nquat.w = quat.w * len;\n}\nreturn quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\nfloat x = angle.x / 2.;\nfloat y = angle.y / 2.;\nfloat z = angle.z / 2.;\nfloat sx = sin(x);\nfloat cx = cos(x);\nfloat sy = sin(y);\nfloat cy = cos(y);\nfloat sz = sin(z);\nfloat cz = cos(z);\nvec4 quat = vec4(0);\nquat.x = sx * cy * cz + cx * sy * sz;\nquat.y = cx * sy * cz + sx * cy * sz;\nquat.z = cx * cy * sz - sx * sy * cz;\nquat.w = cx * cy * cz - sx * sy * sz;\nreturn quat;\n}\nvec4 quatMultiply (vec4 a, vec4 b){\nvec4 quat;\nquat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\nquat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\nquat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\nquat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\nreturn quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\nfloat ix = q.w * v.x + q.y * v.z - q.z * v.y;\nfloat iy = q.w * v.y + q.z * v.x - q.x * v.z;\nfloat iz = q.w * v.z + q.x * v.y - q.y * v.x;\nfloat iw = -q.x * v.x - q.y * v.y - q.z * v.z;\nv.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\nv.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\nv.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\nvec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\nvec4 rotQuat = quatMultiply(viewQuat, q);\nrotateVecFromQuat(pos, rotQuat);\nreturn pos;\n}\nvoid rotateCorner (inout vec2 corner, float angle){\nfloat xOS = cos(angle) * corner.x - sin(angle) * corner.y;\nfloat yOS = sin(angle) * corner.x + cos(angle) * corner.y;\ncorner.x = xOS;\ncorner.y = yOS;\n}\nout mediump vec2 uv;\nout mediump vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n, mat4 viewInv\n) {\nvec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\nvec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\nvec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\nvec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\npos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n}\nin vec3 a_position;\nin vec2 a_texCoord;\nin vec4 a_color;\nlayout(std140) uniform builtin {\nvec4 cc_size_rotation;\n};\nvec4 vs_main() {\nvec4 pos = vec4(a_position, 1);\npos = cc_matWorld * pos;\nvec2 vertOffset = a_texCoord.xy - 0.5;\ncomputeVertPos(pos, vertOffset, quaternionFromEuler(vec3(0., 0., cc_size_rotation.z)), vec3(cc_size_rotation.xy, 0.), cc_matViewInv);\npos = cc_matViewProj * pos;\nuv = a_texCoord.xy;\ncolor = a_color;\nreturn pos;\n}\nvoid main() { gl_Position = vs_main(); }",
              "frag": "\nprecision mediump float;\nlayout(std140) uniform CCGlobal {\nhighp   vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp   mat4 cc_matView;\nhighp   mat4 cc_matViewInv;\nhighp   mat4 cc_matProj;\nhighp   mat4 cc_matProjInv;\nhighp   mat4 cc_matViewProj;\nhighp   mat4 cc_matViewProjInv;\nhighp   vec4 cc_cameraPos;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\n};\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n#if CC_USE_HDR\ncolor.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n#endif\nreturn color;\n}\nin vec2 uv;\nin vec4 color;\nuniform sampler2D mainTexture;\nlayout(std140) uniform FragConstants {\nvec4 tintColor;\n};\nvec4 add () {\nvec4 col = 2.0 * color * tintColor * texture(mainTexture, uv);\nreturn CCFragOutput(col);\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = add(); }"
            }], [{
              "vert": "\nprecision highp float;\nin vec3 a_position;\nvec4 vert () {\nvec4 pos = vec4(a_position, 1);\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }",
              "frag": "\nprecision highp float;\nvec4 frag () {\nvec4 o = vec4(1.0);\nreturn o;\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }"
            }], [{
              "vert": "\nprecision highp float;\nlayout(std140) uniform CCGlobal {\nhighp   vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp   mat4 cc_matView;\nhighp   mat4 cc_matViewInv;\nhighp   mat4 cc_matProj;\nhighp   mat4 cc_matProjInv;\nhighp   mat4 cc_matViewProj;\nhighp   mat4 cc_matViewProjInv;\nhighp   vec4 cc_cameraPos;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\n};\nlayout(std140) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\n};\nin vec3 a_position;\nin vec4 a_color;\nout vec4 v_color;\nin float a_dist;\nout float v_dist;\nvec4 vert () {\nvec4 pos = vec4(a_position, 1);\npos = cc_matViewProj * cc_matWorld * pos;\nv_color = a_color;\nv_dist = a_dist;\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }",
              "frag": "\nprecision highp float;\nin vec4 v_color;\nin float v_dist;\nvec4 frag () {\nvec4 o = v_color;\nfloat aa = fwidth(v_dist);\nfloat alpha = 1. - smoothstep(-aa, 0., abs(v_dist) - 1.0);\no.rgb *= o.a;\no *= alpha;\nreturn o;\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }"
            }], [{
              "vert": "\nprecision mediump float;\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\nmat3 m = mat3(xAxis,yAxis,zAxis);\nfloat trace = m[0][0] + m[1][1] + m[2][2];\nvec4 quat;\nif (trace > 0.) {\nfloat s = 0.5 / sqrt(trace + 1.0);\nquat.w = 0.25 / s;\nquat.x = (m[2][1] - m[1][2]) * s;\nquat.y = (m[0][2] - m[2][0]) * s;\nquat.z = (m[1][0] - m[0][1]) * s;\n} else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\nfloat s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\nquat.w = (m[2][1] - m[1][2]) / s;\nquat.x = 0.25 * s;\nquat.y = (m[0][1] + m[1][0]) / s;\nquat.z = (m[0][2] + m[2][0]) / s;\n} else if (m[1][1] > m[2][2]) {\nfloat s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\nquat.w = (m[0][2] - m[2][0]) / s;\nquat.x = (m[0][1] + m[1][0]) / s;\nquat.y = 0.25 * s;\nquat.z = (m[1][2] + m[2][1]) / s;\n} else {\nfloat s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\nquat.w = (m[1][0] - m[0][1]) / s;\nquat.x = (m[0][2] + m[2][0]) / s;\nquat.y = (m[1][2] + m[2][1]) / s;\nquat.z = 0.25 * s;\n}\nfloat len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\nif (len > 0.) {\nlen = 1. / sqrt(len);\nquat.x = quat.x * len;\nquat.y = quat.y * len;\nquat.z = quat.z * len;\nquat.w = quat.w * len;\n}\nreturn quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\nfloat x = angle.x / 2.;\nfloat y = angle.y / 2.;\nfloat z = angle.z / 2.;\nfloat sx = sin(x);\nfloat cx = cos(x);\nfloat sy = sin(y);\nfloat cy = cos(y);\nfloat sz = sin(z);\nfloat cz = cos(z);\nvec4 quat = vec4(0);\nquat.x = sx * cy * cz + cx * sy * sz;\nquat.y = cx * sy * cz + sx * cy * sz;\nquat.z = cx * cy * sz - sx * sy * cz;\nquat.w = cx * cy * cz - sx * sy * sz;\nreturn quat;\n}\nmat4 matrixFromRT (vec4 q, vec3 p){\nfloat x2 = q.x + q.x;\nfloat y2 = q.y + q.y;\nfloat z2 = q.z + q.z;\nfloat xx = q.x * x2;\nfloat xy = q.x * y2;\nfloat xz = q.x * z2;\nfloat yy = q.y * y2;\nfloat yz = q.y * z2;\nfloat zz = q.z * z2;\nfloat wx = q.w * x2;\nfloat wy = q.w * y2;\nfloat wz = q.w * z2;\nreturn mat4(\n1. - (yy + zz), xy + wz, xz - wy, 0,\nxy - wz, 1. - (xx + zz), yz + wx, 0,\nxz + wy, yz - wx, 1. - (xx + yy), 0,\np.x, p.y, p.z, 1\n);\n}\nmat4 matFromRTS (vec4 q, vec3 t, vec3 s){\nfloat x = q.x, y = q.y, z = q.z, w = q.w;\nfloat x2 = x + x;\nfloat y2 = y + y;\nfloat z2 = z + z;\nfloat xx = x * x2;\nfloat xy = x * y2;\nfloat xz = x * z2;\nfloat yy = y * y2;\nfloat yz = y * z2;\nfloat zz = z * z2;\nfloat wx = w * x2;\nfloat wy = w * y2;\nfloat wz = w * z2;\nfloat sx = s.x;\nfloat sy = s.y;\nfloat sz = s.z;\nreturn mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n(xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n(xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\nt.x, t.y, t.z, 1);\n}\nvec4 quatMultiply (vec4 a, vec4 b){\nvec4 quat;\nquat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\nquat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\nquat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\nquat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\nreturn quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\nfloat ix = q.w * v.x + q.y * v.z - q.z * v.y;\nfloat iy = q.w * v.y + q.z * v.x - q.x * v.z;\nfloat iz = q.w * v.z + q.x * v.y - q.y * v.x;\nfloat iw = -q.x * v.x - q.y * v.y - q.z * v.z;\nv.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\nv.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\nv.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\nvec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\nvec4 rotQuat = quatMultiply(viewQuat, q);\nrotateVecFromQuat(pos, rotQuat);\nreturn pos;\n}\nvoid rotateCorner (inout vec2 corner, float angle){\nfloat xOS = cos(angle) * corner.x - sin(angle) * corner.y;\nfloat yOS = sin(angle) * corner.x + cos(angle) * corner.y;\ncorner.x = xOS;\ncorner.y = yOS;\n}\nlayout(std140) uniform Constants {\nvec4 mainTiling_Offset;\nvec4 frameTile_velLenScale;\nvec4 scale;\n};\nlayout(std140) uniform CCGlobal {\nhighp   vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp   mat4 cc_matView;\nhighp   mat4 cc_matViewInv;\nhighp   mat4 cc_matProj;\nhighp   mat4 cc_matProjInv;\nhighp   mat4 cc_matViewProj;\nhighp   mat4 cc_matViewProjInv;\nhighp   vec4 cc_cameraPos;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\n};\nlayout(std140) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\n};\nout mediump vec2 uv;\nout mediump vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if CC_RENDER_MODE == 0 || CC_RENDER_MODE == 3\n, mat4 viewInv\n#endif\n#if CC_RENDER_MODE == 1\n, vec3 eye\n, vec4 velocity\n, float velocityScale\n, float lengthScale\n, float xIndex\n#endif\n) {\n#if CC_RENDER_MODE == 0\nvec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\nvec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\nvec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\nvec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\npos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_RENDER_MODE == 1\nvec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\nvec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\npos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_RENDER_MODE == 2\nvec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\nvec3 camX = vec3(1, 0, 0);\nvec3 camY = vec3(0, 0, -1);\npos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_RENDER_MODE == 3\nvec2 viewSpaceVert = vec2(vertOffset.x * s.x, vertOffset.y * s.y);\nrotateCorner(viewSpaceVert, q.z);\nvec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\nvec3 camY = vec3(0, 1, 0);\nvec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\npos.xyz += offset;\n#else\npos.x += vertOffset.x;\npos.y += vertOffset.y;\n#endif\n}\nvec2 computeUV (float frameIndex, vec2 vertIndex, vec2 frameTile){\nvec2 aniUV = vec2(0, floor(frameIndex * frameTile.y));\naniUV.x = floor(frameIndex * frameTile.x * frameTile.y - aniUV.y * frameTile.x);\n#if CC_RENDER_MODE != 4\nvertIndex.y = 1. - vertIndex.y;\n#endif\nreturn (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nlayout(std140) uniform SampleConstants {\nvec4 u_sampleInfo;\n};\nlayout(std140) uniform TickConstants {\nvec4 u_worldRot;\nvec4 u_timeDelta;\n};\nin vec4 a_position_starttime;\nin vec4 a_size_uv;\nin vec4 a_rotation_uv;\nin vec4 a_color;\nin vec4 a_dir_life;\nin float a_rndSeed;\n#if CC_RENDER_MODE == 4\nin vec3 a_texCoord;\nin vec3 a_texCoord3;\nin vec3 a_normal;\nin vec4 a_color1;\n#endif\nvec3 unpackCurveData (sampler2D tex, vec2 coord) {\nvec4 a = texture(tex, coord);\nvec4 b = texture(tex, coord + u_sampleInfo.y);\nfloat c = fract(coord.x * u_sampleInfo.x);\nreturn mix(a.xyz, b.xyz, c);\n}\nvec3 unpackCurveData (sampler2D tex, vec2 coord, out float w) {\nvec4 a = texture(tex, coord);\nvec4 b = texture(tex, coord + u_sampleInfo.y);\nfloat c = fract(coord.x * u_sampleInfo.x);\nw = mix(a.w, b.w, c);\nreturn mix(a.xyz, b.xyz, c);\n}\nfloat pseudoRandom (float seed) {\nseed = mod(seed, 233280.);\nfloat q = (seed * 9301. + 49297.) / 233280.;\nreturn fract(q);\n}\n#if COLOR_OVER_TIME_MODULE_ENABLE\nuniform sampler2D color_over_time_tex0;\nlayout(std140) uniform ColorConstant {\nint u_color_mode;\n};\n#endif\n#if ROTATION_OVER_TIME_MODULE_ENABLE\nuniform sampler2D rotation_over_time_tex0;\nlayout(std140) uniform RotationConstant {\nint u_rotation_mode;\n};\n#endif\n#if SIZE_OVER_TIME_MODULE_ENABLE\nuniform sampler2D size_over_time_tex0;\nlayout(std140) uniform SizeConstant {\nint u_size_mode;\n};\n#endif\n#if FORCE_OVER_TIME_MODULE_ENABLE\nuniform sampler2D force_over_time_tex0;\nlayout(std140) uniform ForceConstant {\nint u_force_mode;\nint u_force_space;\n};\n#endif\n#if VELOCITY_OVER_TIME_MODULE_ENABLE\nuniform sampler2D velocity_over_time_tex0;\nlayout(std140) uniform VelocityConstant {\nint u_velocity_mode;\nint u_velocity_space;\n};\n#endif\n#if TEXTURE_ANIMATION_MODULE_ENABLE\nuniform sampler2D texture_animation_tex0;\nlayout(std140) uniform AnimationConstant {\nvec4 u_anim_info;\n};\n#endif\nfloat repeat (float t, float length) {\nreturn t - floor(t / length) * length;\n}\nvec4 rotateQuat (vec4 p, vec4 q) {\nvec3 iv = cross(q.xyz, p.xyz) + q.w * p.xyz;\nvec3 res = p.xyz + 2.0 * cross(q.xyz, iv);\nreturn vec4(res.xyz, p.w);\n}\nvec4 gpvs_main () {\nfloat activeTime = u_timeDelta.x - a_position_starttime.w;\nfloat normalizedTime = clamp(activeTime / a_dir_life.w, 0.0, 1.0);\nvec2 timeCoord0 = vec2(normalizedTime, 0.);\nvec2 timeCoord1 = vec2(normalizedTime, 1.);\n#if CC_RENDER_MODE == 4\nvec2 vertIdx = vec2(a_texCoord.x, a_texCoord.y);\n#else\nvec2 vertIdx = vec2(a_size_uv.w, a_rotation_uv.w);\n#endif\nvec4 velocity = vec4(a_dir_life.xyz, 0.);\nvec4 pos = vec4(a_position_starttime.xyz, 1.);\nvec3 size = a_size_uv.xyz;\n#if SIZE_OVER_TIME_MODULE_ENABLE\nif (u_size_mode == 1) {\nsize *= unpackCurveData(size_over_time_tex0, timeCoord0);\n} else {\nvec3 size_0 = unpackCurveData(size_over_time_tex0, timeCoord0);\nvec3 size_1 = unpackCurveData(size_over_time_tex0, timeCoord1);\nfloat factor_s = pseudoRandom(a_rndSeed + 39825.);\nsize *= mix(size_0, size_1, factor_s);\n}\n#endif\nvec3 compScale = scale.xyz * size;\n#if FORCE_OVER_TIME_MODULE_ENABLE\nvec3 forceAnim = vec3(0.);\nif (u_force_mode == 1) {\nforceAnim = unpackCurveData(force_over_time_tex0, timeCoord0);\n} else {\nvec3 force_0 = unpackCurveData(force_over_time_tex0, timeCoord0);\nvec3 force_1 = unpackCurveData(force_over_time_tex0, timeCoord1);\nfloat factor_f =  pseudoRandom(a_rndSeed + 212165.);\nforceAnim = mix(force_0, force_1, factor_f);\n}\nvec4 forceTrack = vec4(forceAnim, 0.);\nif (u_force_space == 0) {\nforceTrack = rotateQuat(forceTrack, u_worldRot);\n}\nvelocity.xyz += forceTrack.xyz;\n#endif\n#if VELOCITY_OVER_TIME_MODULE_ENABLE\nfloat speedModifier0 = 1.;\nfloat speedModifier1 = 1.;\nvec3 velocityAnim = vec3(0.);\nif (u_velocity_mode == 1) {\nvelocityAnim = unpackCurveData(velocity_over_time_tex0, timeCoord0, speedModifier0);\n} else {\nvec3 vectory_0 = unpackCurveData(velocity_over_time_tex0, timeCoord0, speedModifier0);\nvec3 vectory_1 = unpackCurveData(velocity_over_time_tex0, timeCoord1, speedModifier1);\nfloat factor_v = pseudoRandom(a_rndSeed + 197866.);\nvelocityAnim = mix(vectory_0, vectory_1, factor_v);\nspeedModifier0 = mix(speedModifier0, speedModifier1, factor_v);\n}\nvec4 velocityTrack = vec4(velocityAnim, 0.);\nif (u_velocity_space == 0) {\nvelocityTrack = rotateQuat(velocityTrack, u_worldRot);\n}\nvelocity.xyz += velocityTrack.xyz;\nvelocity.xyz *= speedModifier0;\n#endif\npos.xyz += velocity.xyz * normalizedTime * a_dir_life.w;\n#if !CC_USE_WORLD_SPACE\npos = cc_matWorld * pos;\n#if CC_RENDER_MODE == 1\nvelocity = rotateQuat(velocity, u_worldRot);\n#endif\n#endif\nvec3 rotation = a_rotation_uv.xyz;\n#if ROTATION_OVER_TIME_MODULE_ENABLE\nif (u_rotation_mode == 1) {\nrotation += unpackCurveData(rotation_over_time_tex0, timeCoord0) * normalizedTime * a_dir_life.w;\n} else {\nvec3 rotation_0 = unpackCurveData(rotation_over_time_tex0, timeCoord0);\nvec3 rotation_1 = unpackCurveData(rotation_over_time_tex0, timeCoord1);\nfloat factor_r = pseudoRandom(a_rndSeed + 125292.);\nrotation += mix(rotation_0, rotation_1, factor_r) * normalizedTime * a_dir_life.w;\n}\n#endif\n#if COLOR_OVER_TIME_MODULE_ENABLE\nif (u_color_mode == 1) {\ncolor = a_color * texture(color_over_time_tex0, timeCoord0);\n} else {\nvec4 color_0 = texture(color_over_time_tex0, timeCoord0);\nvec4 color_1 = texture(color_over_time_tex0, timeCoord1);\nfloat factor_c = pseudoRandom(a_rndSeed + 91041.);\ncolor = a_color * mix(color_0, color_1, factor_c);\n}\n#else\ncolor = a_color;\n#endif\n#if CC_RENDER_MODE != 4\nvec2 cornerOffset = vec2((vertIdx - 0.5));\n#if CC_RENDER_MODE == 0\nvec3 rotEuler = rotation.xyz;\n#elif CC_RENDER_MODE == 1\nvec3 rotEuler = vec3(0.);\n#else\nvec3 rotEuler = vec3(0., 0., rotation.z);\n#endif\ncomputeVertPos(pos, cornerOffset, quaternionFromEuler(rotEuler), compScale\n#if CC_RENDER_MODE == 0 || CC_RENDER_MODE == 3\n, cc_matViewInv\n#endif\n#if CC_RENDER_MODE == 1\n, cc_cameraPos.xyz\n, velocity\n, frameTile_velLenScale.z\n, frameTile_velLenScale.w\n, a_size_uv.w\n#endif\n);\n#else\nmat4 xformNoScale = matrixFromRT(quaternionFromEuler(rotation), pos.xyz);\nmat4 xform = matFromRTS(quaternionFromEuler(rotation), pos.xyz, compScale);\npos = xform * vec4(a_texCoord3, 1);\nvec4 normal = xformNoScale * vec4(a_normal, 0);\ncolor *= a_color1;\n#endif\npos = cc_matViewProj * pos;\nfloat frameIndex = 0.;\n#if TEXTURE_ANIMATION_MODULE_ENABLE\nfloat startFrame = 0.;\nvec3 frameInfo = vec3(0.);\nif (int(u_anim_info.x) == 1) {\nframeInfo = unpackCurveData(texture_animation_tex0, timeCoord0);\n} else {\nvec3 frameInfo0 = unpackCurveData(texture_animation_tex0, timeCoord0);\nvec3 frameInfo1 = unpackCurveData(texture_animation_tex0, timeCoord1);\nfloat factor_t = pseudoRandom(a_rndSeed + 90794.);\nframeInfo = mix(frameInfo0, frameInfo1, factor_t);\n}\nstartFrame = frameInfo.x / u_anim_info.y;\nframeIndex = repeat(u_anim_info.z * (frameInfo.y + startFrame), 1.);\n#endif\nuv = computeUV(frameIndex, vertIdx, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw;\nreturn pos;\n}\nvoid main() { gl_Position = gpvs_main(); }",
              "frag": "\nprecision mediump float;\nlayout(std140) uniform CCGlobal {\nhighp   vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp   mat4 cc_matView;\nhighp   mat4 cc_matViewInv;\nhighp   mat4 cc_matProj;\nhighp   mat4 cc_matProjInv;\nhighp   mat4 cc_matViewProj;\nhighp   mat4 cc_matViewProjInv;\nhighp   vec4 cc_cameraPos;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\n};\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n#if CC_USE_HDR\ncolor.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n#endif\nreturn color;\n}\nin vec2 uv;\nin vec4 color;\nuniform sampler2D mainTexture;\nlayout(std140) uniform FragConstants {\nvec4 tintColor;\n};\nvec4 add () {\nvec4 col = 2.0 * color * tintColor * texture(mainTexture, uv);\nreturn CCFragOutput(col);\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = add(); }"
            }], [{
              "vert": "\nprecision mediump float;\nlayout(std140) uniform Constants {\nvec4 mainTiling_Offset;\nvec4 frameTile_velLenScale;\nvec4 scale;\n};\nlayout(std140) uniform CCGlobal {\nhighp   vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp   mat4 cc_matView;\nhighp   mat4 cc_matViewInv;\nhighp   mat4 cc_matProj;\nhighp   mat4 cc_matProjInv;\nhighp   mat4 cc_matViewProj;\nhighp   mat4 cc_matViewProjInv;\nhighp   vec4 cc_cameraPos;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\n};\nlayout(std140) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\n};\nout mediump vec2 uv;\nout mediump vec4 color;\nin vec3 a_position;\nin vec4 a_texCoord;\nin vec3 a_texCoord1;\nin vec3 a_texCoord2;\nin vec4 a_color;\n#if CC_DRAW_WIRE_FRAME\nout vec3 vBarycentric;\n#endif\nvec4 vs_main() {\nhighp vec4 pos = vec4(a_position, 1);\nvec4 velocity = vec4(a_texCoord1.xyz, 0);\n#if !CC_USE_WORLD_SPACE\npos = cc_matWorld * pos;\nvelocity = cc_matWorld * velocity;\n#endif\nfloat vertOffset = (a_texCoord.x - 0.5) * a_texCoord.y;\nvec3 camUp = normalize(cross(pos.xyz - cc_cameraPos.xyz, velocity.xyz));\npos.xyz += camUp * vertOffset;\npos = cc_matViewProj * pos;\nuv = a_texCoord.zw * mainTiling_Offset.xy + mainTiling_Offset.zw;;\ncolor = a_color;\n#if CC_DRAW_WIRE_FRAME\nvBarycentric = a_texCoord2;\n#endif\nreturn pos;\n}\nvoid main() { gl_Position = vs_main(); }",
              "frag": "\nprecision mediump float;\nlayout(std140) uniform CCGlobal {\nhighp   vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp   mat4 cc_matView;\nhighp   mat4 cc_matViewInv;\nhighp   mat4 cc_matProj;\nhighp   mat4 cc_matProjInv;\nhighp   mat4 cc_matViewProj;\nhighp   mat4 cc_matViewProjInv;\nhighp   vec4 cc_cameraPos;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\n};\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n#if CC_USE_HDR\ncolor.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n#endif\nreturn color;\n}\nin vec2 uv;\nin vec4 color;\n#if CC_DRAW_WIRE_FRAME\nin vec3 vBarycentric;\n#endif\nuniform sampler2D mainTexture;\nlayout(std140) uniform FragConstants {\nvec4 tintColor;\n};\nvec4 add () {\nvec4 col = 2.0 * color * tintColor * texture(mainTexture, uv);\n#if CC_DRAW_WIRE_FRAME\nif (any(lessThan(vBarycentric, vec3(0.02)))) {\ncol = vec4(0., 1., 1., 1.);\n}\n#endif\nreturn CCFragOutput(col);\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = add(); }"
            }], [{
              "vert": "\nprecision highp float;\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\nmat3 m = mat3(xAxis,yAxis,zAxis);\nfloat trace = m[0][0] + m[1][1] + m[2][2];\nvec4 quat;\nif (trace > 0.) {\nfloat s = 0.5 / sqrt(trace + 1.0);\nquat.w = 0.25 / s;\nquat.x = (m[2][1] - m[1][2]) * s;\nquat.y = (m[0][2] - m[2][0]) * s;\nquat.z = (m[1][0] - m[0][1]) * s;\n} else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\nfloat s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\nquat.w = (m[2][1] - m[1][2]) / s;\nquat.x = 0.25 * s;\nquat.y = (m[0][1] + m[1][0]) / s;\nquat.z = (m[0][2] + m[2][0]) / s;\n} else if (m[1][1] > m[2][2]) {\nfloat s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\nquat.w = (m[0][2] - m[2][0]) / s;\nquat.x = (m[0][1] + m[1][0]) / s;\nquat.y = 0.25 * s;\nquat.z = (m[1][2] + m[2][1]) / s;\n} else {\nfloat s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\nquat.w = (m[1][0] - m[0][1]) / s;\nquat.x = (m[0][2] + m[2][0]) / s;\nquat.y = (m[1][2] + m[2][1]) / s;\nquat.z = 0.25 * s;\n}\nfloat len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\nif (len > 0.) {\nlen = 1. / sqrt(len);\nquat.x = quat.x * len;\nquat.y = quat.y * len;\nquat.z = quat.z * len;\nquat.w = quat.w * len;\n}\nreturn quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\nfloat x = angle.x / 2.;\nfloat y = angle.y / 2.;\nfloat z = angle.z / 2.;\nfloat sx = sin(x);\nfloat cx = cos(x);\nfloat sy = sin(y);\nfloat cy = cos(y);\nfloat sz = sin(z);\nfloat cz = cos(z);\nvec4 quat = vec4(0);\nquat.x = sx * cy * cz + cx * sy * sz;\nquat.y = cx * sy * cz + sx * cy * sz;\nquat.z = cx * cy * sz - sx * sy * cz;\nquat.w = cx * cy * cz - sx * sy * sz;\nreturn quat;\n}\nmat4 matrixFromRT (vec4 q, vec3 p){\nfloat x2 = q.x + q.x;\nfloat y2 = q.y + q.y;\nfloat z2 = q.z + q.z;\nfloat xx = q.x * x2;\nfloat xy = q.x * y2;\nfloat xz = q.x * z2;\nfloat yy = q.y * y2;\nfloat yz = q.y * z2;\nfloat zz = q.z * z2;\nfloat wx = q.w * x2;\nfloat wy = q.w * y2;\nfloat wz = q.w * z2;\nreturn mat4(\n1. - (yy + zz), xy + wz, xz - wy, 0,\nxy - wz, 1. - (xx + zz), yz + wx, 0,\nxz + wy, yz - wx, 1. - (xx + yy), 0,\np.x, p.y, p.z, 1\n);\n}\nmat4 matFromRTS (vec4 q, vec3 t, vec3 s){\nfloat x = q.x, y = q.y, z = q.z, w = q.w;\nfloat x2 = x + x;\nfloat y2 = y + y;\nfloat z2 = z + z;\nfloat xx = x * x2;\nfloat xy = x * y2;\nfloat xz = x * z2;\nfloat yy = y * y2;\nfloat yz = y * z2;\nfloat zz = z * z2;\nfloat wx = w * x2;\nfloat wy = w * y2;\nfloat wz = w * z2;\nfloat sx = s.x;\nfloat sy = s.y;\nfloat sz = s.z;\nreturn mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n(xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n(xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\nt.x, t.y, t.z, 1);\n}\nvec4 quatMultiply (vec4 a, vec4 b){\nvec4 quat;\nquat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\nquat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\nquat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\nquat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\nreturn quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\nfloat ix = q.w * v.x + q.y * v.z - q.z * v.y;\nfloat iy = q.w * v.y + q.z * v.x - q.x * v.z;\nfloat iz = q.w * v.z + q.x * v.y - q.y * v.x;\nfloat iw = -q.x * v.x - q.y * v.y - q.z * v.z;\nv.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\nv.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\nv.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\nvec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\nvec4 rotQuat = quatMultiply(viewQuat, q);\nrotateVecFromQuat(pos, rotQuat);\nreturn pos;\n}\nvoid rotateCorner (inout vec2 corner, float angle){\nfloat xOS = cos(angle) * corner.x - sin(angle) * corner.y;\nfloat yOS = sin(angle) * corner.x + cos(angle) * corner.y;\ncorner.x = xOS;\ncorner.y = yOS;\n}\nlayout(std140) uniform Constants {\nvec4 mainTiling_Offset;\nvec4 frameTile_velLenScale;\nvec4 scale;\n};\nlayout(std140) uniform CCGlobal {\nhighp   vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp   mat4 cc_matView;\nhighp   mat4 cc_matViewInv;\nhighp   mat4 cc_matProj;\nhighp   mat4 cc_matProjInv;\nhighp   mat4 cc_matViewProj;\nhighp   mat4 cc_matViewProjInv;\nhighp   vec4 cc_cameraPos;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\n};\nlayout(std140) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\n};\nout mediump vec2 uv;\nout mediump vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if CC_RENDER_MODE == 0 || CC_RENDER_MODE == 3\n, mat4 viewInv\n#endif\n#if CC_RENDER_MODE == 1\n, vec3 eye\n, vec4 velocity\n, float velocityScale\n, float lengthScale\n, float xIndex\n#endif\n) {\n#if CC_RENDER_MODE == 0\nvec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\nvec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\nvec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\nvec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\npos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_RENDER_MODE == 1\nvec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\nvec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\npos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_RENDER_MODE == 2\nvec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\nvec3 camX = vec3(1, 0, 0);\nvec3 camY = vec3(0, 0, -1);\npos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_RENDER_MODE == 3\nvec2 viewSpaceVert = vec2(vertOffset.x * s.x, vertOffset.y * s.y);\nrotateCorner(viewSpaceVert, q.z);\nvec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\nvec3 camY = vec3(0, 1, 0);\nvec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\npos.xyz += offset;\n#else\npos.x += vertOffset.x;\npos.y += vertOffset.y;\n#endif\n}\nvec2 computeUV (float frameIndex, vec2 vertIndex, vec2 frameTile){\nvec2 aniUV = vec2(0, floor(frameIndex * frameTile.y));\naniUV.x = floor(frameIndex * frameTile.x * frameTile.y - aniUV.y * frameTile.x);\n#if CC_RENDER_MODE != 4\nvertIndex.y = 1. - vertIndex.y;\n#endif\nreturn (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nin vec3 a_position;\nin vec3 a_texCoord;\nin vec3 a_texCoord1;\nin vec3 a_texCoord2;\nin vec4 a_color;\n#if CC_RENDER_MODE == 1\nin vec3 a_color1;\n#endif\n#if CC_RENDER_MODE == 4\nin vec3 a_texCoord3;\nin vec3 a_normal;\nin vec4 a_color1;\n#endif\nvec4 lpvs_main () {\nvec3 compScale = scale.xyz * a_texCoord1;\nvec4 pos = vec4(a_position, 1);\n#if CC_RENDER_MODE == 1\nvec4 velocity = vec4(a_color1.xyz, 0);\n#endif\n#if !CC_USE_WORLD_SPACE\npos = cc_matWorld * pos;\n#if CC_RENDER_MODE == 1\nvelocity = cc_matWorld * velocity;\n#endif\n#endif\n#if CC_RENDER_MODE != 4\nvec2 cornerOffset = vec2((a_texCoord.xy - 0.5));\n#if CC_RENDER_MODE == 0\nvec3 rotEuler = a_texCoord2;\n#elif CC_RENDER_MODE == 1\nvec3 rotEuler = vec3(0.);\n#else\nvec3 rotEuler = vec3(0., 0., a_texCoord2.z);\n#endif\ncomputeVertPos(pos, cornerOffset, quaternionFromEuler(rotEuler), compScale\n#if CC_RENDER_MODE == 0 || CC_RENDER_MODE == 3\n, cc_matViewInv\n#endif\n#if CC_RENDER_MODE == 1\n, cc_cameraPos.xyz\n, velocity\n, frameTile_velLenScale.z\n, frameTile_velLenScale.w\n, a_texCoord.x\n#endif\n);\ncolor = a_color;\n#else\nmat4 xformNoScale = matrixFromRT(quaternionFromEuler(a_texCoord2), pos.xyz);\nmat4 xform = matFromRTS(quaternionFromEuler(a_texCoord2), pos.xyz, compScale);\npos = xform * vec4(a_texCoord3, 1);\nvec4 normal = xformNoScale * vec4(a_normal, 0);\ncolor = a_color * a_color1;\n#endif\nuv = computeUV(a_texCoord.z, a_texCoord.xy, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw;\npos = cc_matViewProj * pos;\nreturn pos;\n}\nvoid main() { gl_Position = lpvs_main(); }",
              "frag": "\nprecision mediump float;\nlayout(std140) uniform CCGlobal {\nhighp   vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp   mat4 cc_matView;\nhighp   mat4 cc_matViewInv;\nhighp   mat4 cc_matProj;\nhighp   mat4 cc_matProjInv;\nhighp   mat4 cc_matViewProj;\nhighp   mat4 cc_matViewProjInv;\nhighp   vec4 cc_cameraPos;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\n};\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n#if CC_USE_HDR\ncolor.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n#endif\nreturn color;\n}\nin vec2 uv;\nin vec4 color;\nuniform sampler2D mainTexture;\nlayout(std140) uniform FragConstants {\nvec4 tintColor;\n};\nvec4 add () {\nvec4 col = 2.0 * color * tintColor * texture(mainTexture, uv);\nreturn CCFragOutput(col);\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = add(); }"
            }], [{
              "vert": "\nprecision highp float;\nlayout(std140) uniform CCGlobal {\nhighp   vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp   mat4 cc_matView;\nhighp   mat4 cc_matViewInv;\nhighp   mat4 cc_matProj;\nhighp   mat4 cc_matProjInv;\nhighp   mat4 cc_matViewProj;\nhighp   mat4 cc_matViewProjInv;\nhighp   vec4 cc_cameraPos;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\n};\n#if USE_LOCAL\nlayout(std140) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\n};\n#endif\nin vec3 a_position;\nin vec2 a_texCoord;\nin vec4 a_color;\nout vec4 v_light;\nout vec2 uv0;\n#if TWO_COLORED\nin vec4 a_color2;\nout vec4 v_dark;\n#endif\nvec4 vert () {\nvec4 pos = vec4(a_position, 1);\n#if USE_LOCAL\npos = cc_matWorld * pos;\n#endif\npos = cc_matViewProj * pos;\nuv0 = a_texCoord;\nv_light = a_color;\n#if TWO_COLORED\nv_dark = a_color2;\n#endif\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }",
              "frag": "\nprecision highp float;\n#if USE_ALPHA_TEST\nlayout(std140) uniform ALPHA_TEST_DATA {\nfloat alphaThreshold;\n};\n#endif\nvoid ALPHA_TEST (in vec4 color) {\n#if USE_ALPHA_TEST\nif (color.a < alphaThreshold) discard;\n#endif\n}\nvoid ALPHA_TEST (in float alpha) {\n#if USE_ALPHA_TEST\nif (alpha < alphaThreshold) discard;\n#endif\n}\nin vec4 v_light;\n#if TWO_COLORED\nin vec4 v_dark;\n#endif\nin vec2 uv0;\nuniform sampler2D cc_spriteTexture;\nvec4 frag () {\nvec4 o = vec4(1, 1, 1, 1);\n#if TWO_COLORED\nvec4 texColor = vec4(1, 1, 1, 1);\ntexColor *= texture(cc_spriteTexture, uv0);\no.a = texColor.a * v_light.a;\no.rgb = ((texColor.a - 1.0) * v_dark.a + 1.0 - texColor.rgb) * v_dark.rgb + texColor.rgb * v_light.rgb;\n#else\no *= texture(cc_spriteTexture, uv0);\no *= v_light;\n#endif\nALPHA_TEST(o);\nreturn o;\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }"
            }], [{
              "vert": "\nprecision highp float;\nlayout(std140) uniform CCGlobal {\nhighp   vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp   mat4 cc_matView;\nhighp   mat4 cc_matViewInv;\nhighp   mat4 cc_matProj;\nhighp   mat4 cc_matProjInv;\nhighp   mat4 cc_matViewProj;\nhighp   mat4 cc_matViewProjInv;\nhighp   vec4 cc_cameraPos;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\n};\n#if USE_LOCAL\nlayout(std140) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\n};\n#endif\n#if SAMPLE_FROM_RT\n#endif\nin vec3 a_position;\nin vec2 a_texCoord;\nin vec4 a_color;\nout vec4 color;\nout vec2 uv0;\nvec4 vert () {\nvec4 pos = vec4(a_position, 1);\n#if USE_LOCAL\npos = cc_matWorld * pos;\n#endif\n#if USE_PIXEL_ALIGNMENT\npos = cc_matView * pos;\npos.xyz = floor(pos.xyz);\npos = cc_matProj * pos;\n#else\npos = cc_matViewProj * pos;\n#endif\nuv0 = a_texCoord;\n#if SAMPLE_FROM_RT\nuv0 = cc_cameraPos.w > 1.0 ? vec2(uv0.x, 1.0 - uv0.y) : uv0;\n#endif\ncolor = a_color;\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }",
              "frag": "\nprecision highp float;\nvec4 CCSampleWithAlphaSeparated(sampler2D tex, vec2 uv) {\n#if CC_USE_EMBEDDED_ALPHA\nreturn vec4(texture(tex, uv).rgb, texture(tex, uv + vec2(0.0, 0.5)).r);\n#else\nreturn texture(tex, uv);\n#endif\n}\n#if USE_ALPHA_TEST\nlayout(std140) uniform ALPHA_TEST_DATA {\nfloat alphaThreshold;\n};\n#endif\nvoid ALPHA_TEST (in vec4 color) {\n#if USE_ALPHA_TEST\nif (color.a < alphaThreshold) discard;\n#endif\n}\nvoid ALPHA_TEST (in float alpha) {\n#if USE_ALPHA_TEST\nif (alpha < alphaThreshold) discard;\n#endif\n}\nin vec4 color;\n#if USE_TEXTURE\nin vec2 uv0;\nuniform sampler2D cc_spriteTexture;\n#endif\nvec4 frag () {\nvec4 o = vec4(1, 1, 1, 1);\n#if USE_TEXTURE\no *= CCSampleWithAlphaSeparated(cc_spriteTexture, uv0);\n#if IS_GRAY\nfloat gray  = 0.2126 * o.r + 0.7152 * o.g + 0.0722 * o.b;\no.r = o.g = o.b = gray;\n#endif\n#endif\no *= color;\nALPHA_TEST(o);\nreturn o;\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }"
            }], [{
              "vert": "\nprecision highp float;\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec2 a_texCoord;\nin vec4 a_tangent;\n#if CC_USE_MORPH\nin float a_vertexId;\nint getVertexId() {\nreturn int(a_vertexId);\n}\nlayout(std140) uniform CCMorph {\nvec4 cc_displacementWeights[15];\nvec4 cc_displacementTextureInfo;\n};\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int pixelIndex) {\nivec2 texSize = textureSize(tex, 0);\nreturn texelFetch(tex, ivec2(pixelIndex % texSize.x, pixelIndex / texSize.x), 0);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture(tex, x)),\ndecode32(texture(tex, y)),\ndecode32(texture(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nuniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nuniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nuniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nattr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nattr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nattr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_joints;\nin vec4 a_weights;\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nin highp vec4 a_jointAnimInfo;\n#endif\nlayout(std140) uniform CCSkinningTexture {\nhighp vec4 cc_jointTextureInfo;\n};\nlayout(std140) uniform CCSkinningAnimation {\nhighp vec4 cc_jointAnimInfo;\n};\nuniform highp sampler2D cc_jointTexture;\n#else\nlayout(std140) uniform CCSkinning {\nhighp vec4 cc_joints[30 * 3];\n};\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\n#if USE_INSTANCING\nhighp float j = 3.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n#else\nhighp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n#endif\nhighp float invSize = cc_jointTextureInfo.w;\nhighp float y = floor(j * invSize);\nhighp float x = floor(j - y * cc_jointTextureInfo.x);\ny = (y + 0.5) * invSize;\nvec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\n#if USE_INSTANCING\nhighp float j = 12.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n#else\nhighp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n#endif\nhighp float invSize = cc_jointTextureInfo.w;\nhighp float y = floor(j * invSize);\nhighp float x = floor(j - y * cc_jointTextureInfo.x);\ny = (y + 0.5) * invSize;\nvec4 v1 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\nmat4 m = skinMatrix();\nattr.position = m * attr.position;\nattr.normal = (m * vec4(attr.normal, 0.0)).xyz;\nattr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nlayout(std140) uniform CCGlobal {\nhighp   vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp   mat4 cc_matView;\nhighp   mat4 cc_matViewInv;\nhighp   mat4 cc_matProj;\nhighp   mat4 cc_matProjInv;\nhighp   mat4 cc_matViewProj;\nhighp   mat4 cc_matViewProjInv;\nhighp   vec4 cc_cameraPos;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\n};\n#if USE_INSTANCING\nin vec4 a_matWorld0;\nin vec4 a_matWorld1;\nin vec4 a_matWorld2;\n#if USE_LIGHTMAP\nin vec4 a_lightingMapUVParam;\n#endif\n#elif USE_BATCHING\nin float a_dyn_batch_id;\nlayout(std140) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#else\nlayout(std140) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\n};\n#endif\nlayout(std140) uniform Constants {\nvec4 tilingOffset;\nvec4 albedo;\nvec4 albedoScaleAndCutoff;\nvec4 pbrParams;\nvec4 emissive;\nvec4 emissiveScaleParam;\n};\nfloat LinearFog(vec4 pos) {\nvec4 wPos = pos;\nfloat cam_dis = distance(cc_cameraPos, wPos);\nfloat fogStart = cc_fogBase.x;\nfloat fogEnd = cc_fogBase.y;\nreturn clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = distance(cc_cameraPos, wPos) / fogAtten * 4.;\nfloat f = exp(-cam_dis * fogDensity);\nreturn f;\n}\nfloat ExpSquaredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = distance(cc_cameraPos, wPos) / fogAtten * 4.;\nfloat f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\nreturn f;\n}\nfloat LayeredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat _FogTop = cc_fogAdd.x;\nfloat _FogRange = cc_fogAdd.y;\nvec3 camWorldProj = cc_cameraPos.xyz;\ncamWorldProj.y = 0.;\nvec3 worldPosProj = wPos.xyz;\nworldPosProj.y = 0.;\nfloat fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\nfloat fDeltaY, fDensityIntegral;\nif (cc_cameraPos.y > _FogTop) {\nif (wPos.y < _FogTop) {\nfDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\nfDensityIntegral = fDeltaY * fDeltaY * 0.5;\n} else {\nfDeltaY = 0.;\nfDensityIntegral = 0.;\n}\n} else {\nif (wPos.y < _FogTop) {\nfloat fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfloat fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\nfDeltaY = abs(fDeltaA - fDeltaB);\nfDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n} else {\nfDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n}\n}\nfloat fDensity;\nif (fDeltaY != 0.) {\nfDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n} else {\nfDensity = 0.;\n}\nfloat f = exp(-fDensity);\nreturn f;\n}\nout float v_fog_factor;\nout highp vec4 v_shadowPos;\nlayout(std140) uniform CCShadow {\nhighp mat4 cc_matLightPlaneProj;\nhighp mat4 cc_matLightView;\nhighp mat4 cc_matLightViewProj;\nlowp  vec4 cc_shadowNFLSInfo;\nlowp  vec4 cc_shadowWHPBInfo;\nlowp  vec4 cc_shadowLPNNInfo;\nlowp  vec4 cc_shadowColor;\n};\n#if CC_RECEIVE_SHADOW\nuniform sampler2D cc_shadowMap;\nuniform sampler2D cc_spotLightingMap;\n#endif\n#if USE_VERTEX_COLOR\nin vec4 a_color;\nout vec4 v_color;\n#endif\nout vec3 v_position;\nout vec3 v_normal;\nout vec2 v_uv;\nout vec2 v_uv1;\n#if USE_NORMAL_MAP\nout vec3 v_tangent;\nout vec3 v_bitangent;\n#endif\n#if HAS_SECOND_UV || USE_LIGHTMAP\nin vec2 a_texCoord1;\n#endif\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nout vec3 v_luv;\nvoid CCLightingMapCaclUV()\n{\n#if !USE_INSTANCING\nv_luv.xy = cc_lightingMapUVParam.xy + a_texCoord1 * cc_lightingMapUVParam.zw;\nv_luv.z = cc_lightingMapUVParam.z;\n#else\nv_luv.xy = a_lightingMapUVParam.xy + a_texCoord1 * a_lightingMapUVParam.zw;\nv_luv.z = a_lightingMapUVParam.z;\n#endif\n}\n#endif\nvoid main () {\nStandardVertInput In;\nIn.position = vec4(a_position, 1.0);\nIn.normal = a_normal;\nIn.tangent = a_tangent;\n#if CC_USE_MORPH\napplyMorph(In);\n#endif\n#if CC_USE_SKINNING\nCCSkin(In);\n#endif\nmat4 matWorld, matWorldIT;\n#if USE_INSTANCING\nmatWorld = mat4(\nvec4(a_matWorld0.xyz, 0.0),\nvec4(a_matWorld1.xyz, 0.0),\nvec4(a_matWorld2.xyz, 0.0),\nvec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n);\nmatWorldIT = matWorld;\n#elif USE_BATCHING\nmatWorld = cc_matWorlds[int(a_dyn_batch_id)];\nmatWorldIT = matWorld;\n#else\nmatWorld = cc_matWorld;\nmatWorldIT = cc_matWorldIT;\n#endif\nvec4 pos = matWorld * In.position;\nv_position = pos.xyz;\nv_normal = normalize((matWorldIT * vec4(In.normal, 0.0)).xyz);\n#if USE_NORMAL_MAP\nv_tangent = normalize((matWorld * vec4(In.tangent.xyz, 0.0)).xyz);\nv_bitangent = cross(v_normal, v_tangent) * In.tangent.w;\n#endif\nv_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n#if SAMPLE_FROM_RT\nv_uv = cc_cameraPos.w > 1.0 ? vec2(v_uv.x, 1.0 - v_uv.y) : v_uv;\n#endif\n#if HAS_SECOND_UV\nv_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw;\n#if SAMPLE_FROM_RT\nv_uv1 = cc_cameraPos.w > 1.0 ? vec2(v_uv1.x, 1.0 - v_uv1.y) : v_uv1;\n#endif\n#endif\n#if USE_VERTEX_COLOR\nv_color = a_color;\n#endif\n#if CC_USE_FOG == 0\nv_fog_factor = LinearFog(pos);\n#elif CC_USE_FOG == 1\nv_fog_factor = ExpFog(pos);\n#elif CC_USE_FOG == 2\nv_fog_factor = ExpSquaredFog(pos);\n#elif CC_USE_FOG == 3\nv_fog_factor = LayeredFog(pos);\n#else\nv_fog_factor = 1.0;\n#endif\nv_shadowPos = cc_matLightViewProj * pos;\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nCCLightingMapCaclUV();\n#endif\ngl_Position = cc_matProj * (cc_matView * matWorld) * In.position;\n}",
              "frag": "\nprecision highp float;\nlayout(std140) uniform CCGlobal {\nhighp   vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp   mat4 cc_matView;\nhighp   mat4 cc_matViewInv;\nhighp   mat4 cc_matProj;\nhighp   mat4 cc_matProjInv;\nhighp   mat4 cc_matViewProj;\nhighp   mat4 cc_matViewProjInv;\nhighp   vec4 cc_cameraPos;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\n};\nlayout(std140) uniform Constants {\nvec4 tilingOffset;\nvec4 albedo;\nvec4 albedoScaleAndCutoff;\nvec4 pbrParams;\nvec4 emissive;\nvec4 emissiveScaleParam;\n};\nin float v_fog_factor;\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nlayout(std140) uniform CCShadow {\nhighp mat4 cc_matLightPlaneProj;\nhighp mat4 cc_matLightView;\nhighp mat4 cc_matLightViewProj;\nlowp  vec4 cc_shadowNFLSInfo;\nlowp  vec4 cc_shadowWHPBInfo;\nlowp  vec4 cc_shadowLPNNInfo;\nlowp  vec4 cc_shadowColor;\n};\n#if CC_RECEIVE_SHADOW\nuniform sampler2D cc_shadowMap;\nuniform sampler2D cc_spotLightingMap;\nfloat CCGetLinearDepth (vec3 worldPos) {\nvec4 viewStartPos = cc_matLightView * vec4(worldPos.xyz, 1.0);\nfloat dist = length(viewStartPos.xyz);\nreturn cc_shadowNFLSInfo.x + (-dist / (cc_shadowNFLSInfo.y - cc_shadowNFLSInfo.x));\n}\nfloat CCGetShadowFactorHard (vec4 shadowPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nfloat shadow = 0.0;\nfloat closestDepth = 0.0;\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nclosestDepth = dot(texture(cc_shadowMap, clipPos.xy), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\n} else {\nclosestDepth = texture(cc_shadowMap, clipPos.xy).x;\n}\nshadow = step(closestDepth, clipPos.z- cc_shadowWHPBInfo.w);\nreturn shadow;\n}\nfloat CCGetShadowFactorSoft (vec4 shadowPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat offsetDepth = clipPos.z - cc_shadowWHPBInfo.w;\nvec2 oneTap = 1.0 / cc_shadowWHPBInfo.xy;\nvec2 clipPos_offset = clipPos.xy + oneTap;\nfloat block0, block1, block2, block3;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock1 = step(dot(texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock2 = step(dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock3 = step(dot(texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\n} else {\nblock0 = step(texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)).x, offsetDepth);\nblock1 = step(texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos.y)).x, offsetDepth);\nblock2 = step(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset.y)).x, offsetDepth);\nblock3 = step(texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos_offset.y)).x, offsetDepth);\n}\nfloat coefX   = mod(clipPos.x, oneTap.x) * cc_shadowWHPBInfo.x;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block2, block3, coefX);\nfloat coefY   = mod(clipPos.y, oneTap.y) * cc_shadowWHPBInfo.y;;\nreturn mix(resultX, resultY, coefY);\n}\nfloat CCGetShadowFactorSoft2X (vec4 shadowPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat bias = cc_shadowWHPBInfo.w;\nfloat offsetDepth = clipPos.z - bias;\nvec2 mapSize = cc_shadowWHPBInfo.xy;\nvec2 oneTap = 1.0 / mapSize;\nfloat clipPos_offset_L = clipPos.x - oneTap.x;\nfloat clipPos_offset_R = clipPos.x + oneTap.x;\nfloat clipPos_offset_U = clipPos.y - oneTap.y;\nfloat clipPos_offset_D = clipPos.y + oneTap.y;\nfloat block0, block1, block2, block3, block4, block5, block6, block7, block8;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(dot(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock1 = step(dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock2 = step(dot(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock3 = step(dot(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock4 = step(dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock5 = step(dot(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock6 = step(dot(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock7 = step(dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock8 = step(dot(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\n} else {\nblock0 = step(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_U)).x, offsetDepth);\nblock1 = step(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_U)).x, offsetDepth);\nblock2 = step(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_U)).x, offsetDepth);\nblock3 = step(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos.y)).x, offsetDepth);\nblock4 = step(texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)).x, offsetDepth);\nblock5 = step(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos.y)).x, offsetDepth);\nblock6 = step(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_D)).x, offsetDepth);\nblock7 = step(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_D)).x, offsetDepth);\nblock8 = step(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_D)).x, offsetDepth);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * mapSize.x;\nfloat coefY = mod(clipPos.y, oneTap.y) * mapSize.y;\nfloat shadow = 0.0;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block3, block4, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block1, block2, coefX);\nresultY = mix(block4, block5, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block3, block4, coefX);\nresultY = mix(block6, block7, coefX);\nshadow += mix(resultX, resultY, coefY);\nresultX = mix(block4, block5, coefX);\nresultY = mix(block7, block8, coefX);\nshadow += mix(resultX, resultY, coefY);\nreturn shadow * 0.25;\n}\nfloat CCGetSpotLightShadowFactorHard (vec4 shadowPos, vec3 worldPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nfloat shadow = 0.0;\nfloat closestDepth = 0.0;\nfloat depth = 0.0;\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nif (cc_shadowLPNNInfo.y > 0.000001) {\nclosestDepth = dot(texture(cc_spotLightingMap, clipPos.xy), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\n} else {\nclosestDepth = texture(cc_spotLightingMap, clipPos.xy).x;\n}\nshadow = step(closestDepth, depth - cc_shadowWHPBInfo.w);\nreturn shadow;\n}\nfloat CCGetSpotLightShadowFactorSoft (vec4 shadowPos, vec3 worldPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nfloat offsetx = 1.0 / cc_shadowWHPBInfo.x;\nfloat offsety = 1.0 / cc_shadowWHPBInfo.y;\nfloat shadow = 0.0;\nfloat depth = 0.0;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nfloat closestDepth = dot(texture(cc_spotLightingMap, vec2(clipPos.x - offsetx, clipPos.y - offsety)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = dot(texture(cc_spotLightingMap, vec2(clipPos.x - offsetx, clipPos.y + offsety)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = dot(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = dot(texture(cc_spotLightingMap, vec2(clipPos.x + offsetx, clipPos.y - offsety)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = dot(texture(cc_spotLightingMap, vec2(clipPos.x + offsetx, clipPos.y + offsety)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\n} else {\nfloat closestDepth = texture(cc_spotLightingMap, vec2(clipPos.x - offsetx, clipPos.y - offsety)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = texture(cc_spotLightingMap, vec2(clipPos.x - offsetx, clipPos.y + offsety)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = texture(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = texture(cc_spotLightingMap, vec2(clipPos.x + offsetx, clipPos.y - offsety)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = texture(cc_spotLightingMap, vec2(clipPos.x + offsetx, clipPos.y + offsety)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\n}\nreturn shadow / 5.0;\n}\nfloat CCGetSpotLightShadowFactorSoft2X (vec4 shadowPos, vec3 worldPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nfloat offsetx = 1.0 / cc_shadowWHPBInfo.x;\nfloat offsety = 1.0 / cc_shadowWHPBInfo.y;\nfloat shadow = 0.0;\nfloat depth = 0.0;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nfor (int i = -1; i <= 1; i++) {\nfor (int j = -1; j <= 1; j++) {\nfloat closestDepth = dot(texture(cc_spotLightingMap, clipPos.xy + vec2(i, j) * vec2(offsetx, offsety)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\n}\n}\n} else {\nfor (int i = -1; i <= 1; i++) {\nfor (int j = -1; j <= 1; j++) {\nfloat closestDepth = texture(cc_spotLightingMap, clipPos.xy + vec2(i, j) * vec2(offsetx, offsety)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\n}\n}\n}\nreturn shadow / 9.0;\n}\n#endif\n#if CC_USE_IBL\nuniform samplerCube cc_environment;\nvec3 unpackRGBE (vec4 rgbe) {\nreturn rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\nvec4 fragTextureLod (sampler2D tex, vec2 coord, float lod) {\nreturn textureLod(tex, coord, lod);\n}\nvec4 fragTextureLod (samplerCube tex, vec3 coord, float lod) {\nreturn textureLod(tex, coord, lod);\n}\n#endif\nfloat GGXMobile (float roughness, float NoH, vec3 H, vec3 N) {\nvec3 NxH = cross(N, H);\nfloat OneMinusNoHSqr = dot(NxH, NxH);\nfloat a = roughness * roughness;\nfloat n = NoH * a;\nfloat p = a / (OneMinusNoHSqr + n * n);\nreturn p * p;\n}\nfloat CalcSpecular (float roughness, float NoH, vec3 H, vec3 N) {\nreturn (roughness * 0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox (vec3 specular, float roughness, float NoV) {\nconst vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\nconst vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\nvec4 r = roughness * c0 + c1;\nfloat a004 = min(r.x * r.x, exp2(-9.28 * NoV)) * r.x + r.y;\nvec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;\nAB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\nreturn specular * AB.x + AB.y;\n}\nstruct StandardSurface {\nvec4 albedo;\nvec3 position;\nvec3 normal;\nvec3 emissive;\nvec3 lightmap;\nfloat lightmap_test;\nfloat roughness;\nfloat metallic;\nfloat occlusion;\n};\nvec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) {\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - s.position);\nfloat NV = max(abs(dot(N, V)), 0.001);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 L = normalize(-cc_mainLitDir.xyz);\nvec3 H = normalize(L + V);\nfloat NH = max(dot(N, H), 0.0);\nfloat NL = max(dot(N, L), 0.001);\nvec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w;\nvec3 diffuseContrib = diffuse;\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nif (s.lightmap_test > 0.0001) {\nfinalColor = s.lightmap.rgb;\n}\n#else\ndiffuseContrib /= 3.14159265359;\n#endif\nvec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\nvec3 dirlightContrib = (diffuseContrib + specularContrib);\n#if CC_RECEIVE_SHADOW\n{\nfloat pcf = cc_shadowWHPBInfo.z + 0.001;\nfloat shadowAttenuation = 0.0;\nfloat cosAngle = clamp(1.0 - dot(N, L.xyz), 0.0, 1.0);\nvec3 projWorldPos = shadowPos.xyz + cosAngle * cc_shadowLPNNInfo.z * N;\nvec4 pos = vec4(projWorldPos.xyz, shadowPos.w);\nif (pcf > 2.0) shadowAttenuation = CCGetShadowFactorSoft2X(pos);\nelse if (pcf > 1.0) shadowAttenuation = CCGetShadowFactorSoft(pos);\nelse shadowAttenuation = CCGetShadowFactorHard(pos);\nvec3 shadowColor = cc_shadowColor.rgb * cc_shadowColor.a + dirlightContrib.rgb * (1.0 - cc_shadowColor.a);\nif (cc_shadowNFLSInfo.w > 0.000001) {\ndirlightContrib.rgb = shadowColor.rgb * shadowAttenuation + dirlightContrib.rgb * (1.0 - shadowAttenuation);\n} else {\ndirlightContrib.rgb = shadowColor.rgb * shadowAttenuation * NL + dirlightContrib.rgb * (1.0 - shadowAttenuation * NL);\n}\n}\n#endif\nfinalColor *= dirlightContrib;\nfloat fAmb = 0.5 - N.y * 0.5;\nvec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\nfinalColor += (ambDiff.rgb * diffuse);\n#if CC_USE_IBL\nvec3 R = normalize(reflect(-V, N));\nvec4 envmap = fragTextureLod(cc_environment, R, s.roughness * cc_ambientGround.w);\n#if CC_USE_IBL == 2\nvec3 env = unpackRGBE(envmap);\n#else\nvec3 env = SRGBToLinear(envmap.rgb);\n#endif\nfinalColor += env * cc_ambientSky.w * specular;\n#endif\nfinalColor = finalColor * s.occlusion;\n#if CC_USE_HDR\ns.emissive *= cc_exposure.w;\n#endif\nfinalColor += s.emissive;\nreturn vec4(finalColor, s.albedo.a);\n}\nvec3 ACESToneMap (vec3 color) {\ncolor = min(color, vec3(8.0));\nconst float A = 2.51;\nconst float B = 0.03;\nconst float C = 2.43;\nconst float D = 0.59;\nconst float E = 0.14;\nreturn (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n#if !CC_USE_HDR\ncolor.rgb = sqrt(ACESToneMap(color.rgb));\n#endif\nreturn color;\n}\nin highp vec4 v_shadowPos;\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nin vec3 v_luv;\nuniform sampler2D cc_lightingMap;\nvec3 UnpackLightingmap(vec4 color) {\nvec3 c;\nfloat e = 1.0 + color.a * (8.0 - 1.0);\nc.r = color.r * e;\nc.g = color.g * e;\nc.b = color.b * e;\nreturn c;\n}\n#endif\nin vec3 v_position;\nin vec2 v_uv;\nin vec2 v_uv1;\nin vec3 v_normal;\n#if USE_VERTEX_COLOR\nin vec4 v_color;\n#endif\n#if USE_ALBEDO_MAP\nuniform sampler2D albedoMap;\n#endif\n#if USE_NORMAL_MAP\nin vec3 v_tangent;\nin vec3 v_bitangent;\nuniform sampler2D normalMap;\n#endif\n#if USE_PBR_MAP\nuniform sampler2D pbrMap;\n#endif\n#if USE_METALLIC_ROUGHNESS_MAP\nuniform sampler2D metallicRoughnessMap;\n#endif\n#if USE_OCCLUSION_MAP\nuniform sampler2D occlusionMap;\n#endif\n#if USE_EMISSIVE_MAP\nuniform sampler2D emissiveMap;\n#endif\n#if USE_ALPHA_TEST\n#endif\nvoid surf (out StandardSurface s) {\nvec4 baseColor = albedo;\n#if USE_VERTEX_COLOR\nbaseColor *= v_color;\n#endif\n#if USE_ALBEDO_MAP\nvec4 texColor = texture(albedoMap, ALBEDO_UV);\ntexColor.rgb = SRGBToLinear(texColor.rgb);\nbaseColor *= texColor;\n#endif\ns.albedo = baseColor;\ns.albedo.rgb *= albedoScaleAndCutoff.xyz;\n#if USE_ALPHA_TEST\nif (s.albedo.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard;\n#endif\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nvec4 lightColor = texture(cc_lightingMap, v_luv.xy);\ns.lightmap = UnpackLightingmap(lightColor);\ns.lightmap_test = v_luv.z;\n#endif\ns.normal = v_normal;\n#if USE_NORMAL_MAP\nvec3 nmmp = texture(normalMap, NORMAL_UV).xyz - vec3(0.5);\ns.normal =\n(nmmp.x * pbrParams.w) * normalize(v_tangent) +\n(nmmp.y * pbrParams.w) * normalize(v_bitangent) +\nnmmp.z * normalize(s.normal);\n#endif\ns.position = v_position;\nvec4 pbr = pbrParams;\n#if USE_PBR_MAP\nvec4 res = texture(pbrMap, PBR_UV);\npbr.x *= res.r;\npbr.y *= res.g;\npbr.z *= res.b;\n#endif\n#if USE_METALLIC_ROUGHNESS_MAP\nvec4 metallicRoughness = texture(metallicRoughnessMap, PBR_UV);\npbr.z *= metallicRoughness.b;\npbr.y *= metallicRoughness.g;\n#endif\n#if USE_OCCLUSION_MAP\npbr.x *= texture(occlusionMap, PBR_UV).r;\n#endif\ns.occlusion = clamp(pbr.x, 0.0, 0.96);\ns.roughness = clamp(pbr.y, 0.04, 1.0);\ns.metallic = pbr.z;\ns.emissive = emissive.rgb * emissiveScaleParam.xyz;\n#if USE_EMISSIVE_MAP\ns.emissive *= SRGBToLinear(texture(emissiveMap, EMISSIVE_UV).rgb);\n#endif\n}\n#if CC_FORWARD_ADD\n#if CC_PIPELINE_TYPE == 0\n# define LIGHTS_PER_PASS 1\n#else\n# define LIGHTS_PER_PASS 10\n#endif\nlayout(std140) uniform CCForwardLight {\nhighp vec4 cc_lightPos[LIGHTS_PER_PASS];\nvec4 cc_lightColor[LIGHTS_PER_PASS];\nvec4 cc_lightSizeRangeAngle[LIGHTS_PER_PASS];\nvec4 cc_lightDir[LIGHTS_PER_PASS];\n};\nfloat SmoothDistAtt (float distSqr, float invSqrAttRadius) {\nfloat factor = distSqr * invSqrAttRadius;\nfloat smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\nreturn smoothFactor * smoothFactor;\n}\nfloat GetDistAtt (float distSqr, float invSqrAttRadius) {\nfloat attenuation = 1.0 / max(distSqr, 0.01*0.01);\nattenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\nreturn attenuation;\n}\nfloat GetAngleAtt (vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\nfloat cd = dot(litDir, L);\nfloat attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\nreturn (attenuation * attenuation);\n}\nvec4 CCStandardShadingAdditive (StandardSurface s, vec4 shadowPos) {\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 diffuseContrib = diffuse / 3.14159265359;\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - s.position);\nfloat NV = max(abs(dot(N, V)), 0.001);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 finalColor = vec3(0.0);\nint numLights = CC_PIPELINE_TYPE == 0 ? LIGHTS_PER_PASS : int(cc_lightDir[0].w);\nfor (int i = 0; i < LIGHTS_PER_PASS; i++) {\nif (i >= numLights) break;\nvec3 SLU = cc_lightPos[i].xyz - s.position;\nvec3 SL = normalize(SLU);\nvec3 SH = normalize(SL + V);\nfloat SNL = max(dot(N, SL), 0.001);\nfloat SNH = max(dot(N, SH), 0.0);\nfloat distSqr = dot(SLU, SLU);\nfloat litRadius = cc_lightSizeRangeAngle[i].x;\nfloat litRadiusSqr = litRadius * litRadius;\nfloat illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\nfloat attRadiusSqrInv = 1.0 / max(cc_lightSizeRangeAngle[i].y, 0.01);\nattRadiusSqrInv *= attRadiusSqrInv;\nfloat att = GetDistAtt(distSqr, attRadiusSqrInv);\nvec3 lspec = specular * CalcSpecular(s.roughness, SNH, SH, N);\nif (cc_lightPos[i].w > 0.0) {\nfloat cosInner = max(dot(-cc_lightDir[i].xyz, SL), 0.01);\nfloat cosOuter = cc_lightSizeRangeAngle[i].z;\nfloat litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\nfloat litAngleOffset = -cosOuter * litAngleScale;\natt *= GetAngleAtt(SL, -cc_lightDir[i].xyz, litAngleScale, litAngleOffset);\n}\nvec3 lightColor = cc_lightColor[i].rgb;\n#if CC_RECEIVE_SHADOW\nif (cc_lightPos[i].w > 0.0) {\n{\nfloat pcf = cc_shadowWHPBInfo.z + 0.001;\nfloat shadowAttenuation = 0.0;\nfloat cosAngle = clamp(1.0 - dot(N, normalize(cc_lightPos[i].xyz - s.position.xyz)), 0.0, 1.0);\nvec3 projWorldPos = shadowPos.xyz + cosAngle * cc_shadowLPNNInfo.z * N;\nvec4 pos = vec4(projWorldPos.xyz, shadowPos.w);\nif (pcf > 2.0) shadowAttenuation = CCGetSpotLightShadowFactorSoft2X(pos, s.position);\nelse if (pcf > 1.0) shadowAttenuation = CCGetSpotLightShadowFactorSoft(pos, s.position);\nelse shadowAttenuation = CCGetSpotLightShadowFactorHard(pos, s.position);\nlightColor *= 1.0 - shadowAttenuation;\n}\n}\n#endif\nfinalColor += SNL * lightColor * cc_lightColor[i].w * illum * att * (diffuseContrib + lspec);\n}\nfinalColor = finalColor * s.occlusion;\nreturn vec4(finalColor, 0.0);\n}\nlayout(location = 0) out vec4 fragColorX;\nvoid main () {\nStandardSurface s; surf(s);\nvec4 color = CCStandardShadingAdditive(s, v_shadowPos);\ncolor = vec4(mix(CC_FORWARD_ADD > 0 ? vec3(0.0) : cc_fogColor.rgb, color.rgb, v_fog_factor), color.a);\nfragColorX = CCFragOutput(color);\n}\n#elif CC_PIPELINE_TYPE == 0\nlayout(location = 0) out vec4 fragColorX;\nvoid main () {\nStandardSurface s; surf(s);\nvec4 color = CCStandardShadingBase(s, v_shadowPos);\ncolor = vec4(mix(CC_FORWARD_ADD > 0 ? vec3(0.0) : cc_fogColor.rgb, color.rgb, v_fog_factor), color.a);\nfragColorX = CCFragOutput(color);\n}\n#elif CC_PIPELINE_TYPE == 1\nlayout(location = 0) out vec4 fragColor0;\nlayout(location = 1) out vec4 fragColor1;\nlayout(location = 2) out vec4 fragColor2;\nlayout(location = 3) out vec4 fragColor3;\nvoid main () {\nStandardSurface s; surf(s);\nfragColor0 = s.albedo;\nfragColor1 = vec4(s.position, s.roughness);\nfragColor2 = vec4(s.normal, s.metallic);\nfragColor3 = vec4(s.emissive, s.occlusion);\n}\n#endif"
            }, {
              "vert": "\nprecision highp float;\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec2 a_texCoord;\nin vec4 a_tangent;\n#if CC_USE_MORPH\nin float a_vertexId;\nint getVertexId() {\nreturn int(a_vertexId);\n}\nlayout(std140) uniform CCMorph {\nvec4 cc_displacementWeights[15];\nvec4 cc_displacementTextureInfo;\n};\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int pixelIndex) {\nivec2 texSize = textureSize(tex, 0);\nreturn texelFetch(tex, ivec2(pixelIndex % texSize.x, pixelIndex / texSize.x), 0);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture(tex, x)),\ndecode32(texture(tex, y)),\ndecode32(texture(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nuniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nuniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nuniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nattr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nattr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nattr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_joints;\nin vec4 a_weights;\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nin highp vec4 a_jointAnimInfo;\n#endif\nlayout(std140) uniform CCSkinningTexture {\nhighp vec4 cc_jointTextureInfo;\n};\nlayout(std140) uniform CCSkinningAnimation {\nhighp vec4 cc_jointAnimInfo;\n};\nuniform highp sampler2D cc_jointTexture;\n#else\nlayout(std140) uniform CCSkinning {\nhighp vec4 cc_joints[30 * 3];\n};\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\n#if USE_INSTANCING\nhighp float j = 3.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n#else\nhighp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n#endif\nhighp float invSize = cc_jointTextureInfo.w;\nhighp float y = floor(j * invSize);\nhighp float x = floor(j - y * cc_jointTextureInfo.x);\ny = (y + 0.5) * invSize;\nvec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\n#if USE_INSTANCING\nhighp float j = 12.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n#else\nhighp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n#endif\nhighp float invSize = cc_jointTextureInfo.w;\nhighp float y = floor(j * invSize);\nhighp float x = floor(j - y * cc_jointTextureInfo.x);\ny = (y + 0.5) * invSize;\nvec4 v1 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\nmat4 m = skinMatrix();\nattr.position = m * attr.position;\nattr.normal = (m * vec4(attr.normal, 0.0)).xyz;\nattr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\n#if USE_INSTANCING\nin vec4 a_matWorld0;\nin vec4 a_matWorld1;\nin vec4 a_matWorld2;\n#if USE_LIGHTMAP\nin vec4 a_lightingMapUVParam;\n#endif\n#elif USE_BATCHING\nin float a_dyn_batch_id;\nlayout(std140) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#else\nlayout(std140) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\n};\n#endif\nlayout(std140) uniform Constants {\nvec4 tilingOffset;\nvec4 albedo;\nvec4 albedoScaleAndCutoff;\nvec4 pbrParams;\nvec4 emissive;\nvec4 emissiveScaleParam;\n};\nlayout(std140) uniform CCShadow {\nhighp mat4 cc_matLightPlaneProj;\nhighp mat4 cc_matLightView;\nhighp mat4 cc_matLightViewProj;\nlowp  vec4 cc_shadowNFLSInfo;\nlowp  vec4 cc_shadowWHPBInfo;\nlowp  vec4 cc_shadowLPNNInfo;\nlowp  vec4 cc_shadowColor;\n};\n#if HAS_SECOND_UV || USE_LIGHTMAP\nin vec2 a_texCoord1;\n#endif\nout vec2 v_uv;\nout vec2 v_uv1;\nout vec4 v_worldPos;\nout float v_clip_depth;\nvec4 vert () {\nStandardVertInput In;\nIn.position = vec4(a_position, 1.0);\nIn.normal = a_normal;\nIn.tangent = a_tangent;\n#if CC_USE_MORPH\napplyMorph(In);\n#endif\n#if CC_USE_SKINNING\nCCSkin(In);\n#endif\nmat4 matWorld, matWorldIT;\n#if USE_INSTANCING\nmatWorld = mat4(\nvec4(a_matWorld0.xyz, 0.0),\nvec4(a_matWorld1.xyz, 0.0),\nvec4(a_matWorld2.xyz, 0.0),\nvec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n);\nmatWorldIT = matWorld;\n#elif USE_BATCHING\nmatWorld = cc_matWorlds[int(a_dyn_batch_id)];\nmatWorldIT = matWorld;\n#else\nmatWorld = cc_matWorld;\nmatWorldIT = cc_matWorldIT;\n#endif\nv_worldPos = matWorld * In.position;\nvec4 clipPos = cc_matLightViewProj * v_worldPos;\nv_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n#if HAS_SECOND_UV\nv_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw;\n#endif\nv_clip_depth = clipPos.z / clipPos.w * 0.5 + 0.5;\nreturn clipPos;\n}\nvoid main() { gl_Position = vert(); }",
              "frag": "\nprecision highp float;\nlayout(std140) uniform Constants {\nvec4 tilingOffset;\nvec4 albedo;\nvec4 albedoScaleAndCutoff;\nvec4 pbrParams;\nvec4 emissive;\nvec4 emissiveScaleParam;\n};\nvec4 packDepthToRGBA (float depth) {\nvec4 ret = vec4(1.0, 255.0, 65025.0, 160581375.0) * depth;\nret = fract(ret);\nret -= ret.yzww * vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);\nreturn ret;\n}\nlayout(std140) uniform CCShadow {\nhighp mat4 cc_matLightPlaneProj;\nhighp mat4 cc_matLightView;\nhighp mat4 cc_matLightViewProj;\nlowp  vec4 cc_shadowNFLSInfo;\nlowp  vec4 cc_shadowWHPBInfo;\nlowp  vec4 cc_shadowLPNNInfo;\nlowp  vec4 cc_shadowColor;\n};\nin vec2 v_uv;\nin vec2 v_uv1;\nin vec4 v_worldPos;\nin float v_clip_depth;\n#if USE_ALBEDO_MAP\nuniform sampler2D albedoMap;\n#endif\n#if USE_ALPHA_TEST\n#endif\nvec4 frag () {\nvec4 baseColor = albedo;\n#if USE_ALBEDO_MAP\nbaseColor *= texture(albedoMap, ALBEDO_UV);\n#endif\n#if USE_ALPHA_TEST\nif (baseColor.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard;\n#endif\nif(cc_shadowLPNNInfo.x > 0.000001 && cc_shadowLPNNInfo.x < 1.999999) {\nif (cc_shadowNFLSInfo.z > 0.000001) {\nvec4 viewStartPos = cc_matLightView * v_worldPos;\nfloat dist = length(viewStartPos.xyz);\nfloat linearDepth = cc_shadowNFLSInfo.x + (-dist / (cc_shadowNFLSInfo.y - cc_shadowNFLSInfo.x));\nreturn vec4(linearDepth, 1.0, 1.0, 1.0);\n}\n}\nif (cc_shadowLPNNInfo.y > 0.000001) {\nreturn packDepthToRGBA(v_clip_depth);\n}\nreturn vec4(v_clip_depth, 1.0, 1.0, 1.0);\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }"
            }], [{
              "vert": "\nprecision mediump float;\nlayout(std140) uniform CCGlobal {\nhighp   vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp   mat4 cc_matView;\nhighp   mat4 cc_matViewInv;\nhighp   mat4 cc_matProj;\nhighp   mat4 cc_matProjInv;\nhighp   mat4 cc_matViewProj;\nhighp   mat4 cc_matViewProjInv;\nhighp   vec4 cc_cameraPos;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\n};\nlayout(std140) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\n};\nfloat LinearFog(vec4 pos) {\nvec4 wPos = pos;\nfloat cam_dis = distance(cc_cameraPos, wPos);\nfloat fogStart = cc_fogBase.x;\nfloat fogEnd = cc_fogBase.y;\nreturn clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = distance(cc_cameraPos, wPos) / fogAtten * 4.;\nfloat f = exp(-cam_dis * fogDensity);\nreturn f;\n}\nfloat ExpSquaredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = distance(cc_cameraPos, wPos) / fogAtten * 4.;\nfloat f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\nreturn f;\n}\nfloat LayeredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat _FogTop = cc_fogAdd.x;\nfloat _FogRange = cc_fogAdd.y;\nvec3 camWorldProj = cc_cameraPos.xyz;\ncamWorldProj.y = 0.;\nvec3 worldPosProj = wPos.xyz;\nworldPosProj.y = 0.;\nfloat fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\nfloat fDeltaY, fDensityIntegral;\nif (cc_cameraPos.y > _FogTop) {\nif (wPos.y < _FogTop) {\nfDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\nfDensityIntegral = fDeltaY * fDeltaY * 0.5;\n} else {\nfDeltaY = 0.;\nfDensityIntegral = 0.;\n}\n} else {\nif (wPos.y < _FogTop) {\nfloat fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfloat fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\nfDeltaY = abs(fDeltaA - fDeltaB);\nfDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n} else {\nfDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n}\n}\nfloat fDensity;\nif (fDeltaY != 0.) {\nfDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n} else {\nfDensity = 0.;\n}\nfloat f = exp(-fDensity);\nreturn f;\n}\nout float v_fog_factor;\nout highp vec4 v_shadowPos;\nlayout(std140) uniform CCShadow {\nhighp mat4 cc_matLightPlaneProj;\nhighp mat4 cc_matLightView;\nhighp mat4 cc_matLightViewProj;\nlowp  vec4 cc_shadowNFLSInfo;\nlowp  vec4 cc_shadowWHPBInfo;\nlowp  vec4 cc_shadowLPNNInfo;\nlowp  vec4 cc_shadowColor;\n};\n#if CC_RECEIVE_SHADOW\nuniform sampler2D cc_shadowMap;\nuniform sampler2D cc_spotLightingMap;\n#endif\nin vec3 a_position;\nin vec3 a_normal;\nin vec2 a_texCoord;\nout highp vec3 v_position;\nout mediump vec3 v_normal;\n#if USE_NORMALMAP\nout mediump vec3 v_tangent;\nout mediump vec3 v_binormal;\n#endif\nout mediump vec2 uvw;\nout mediump vec2 uv0;\nout mediump vec2 uv1;\nout mediump vec2 uv2;\nout mediump vec2 uv3;\nout mediump vec3 luv;\nout mediump vec3 diffuse;\nlayout(std140) uniform TexCoords {\nvec4 UVScale;\nvec4 lightMapUVParam;\n};\nvoid main () {\nvec3 worldPos;\nworldPos.x = cc_matWorld[3][0] + a_position.x;\nworldPos.y = cc_matWorld[3][1] + a_position.y;\nworldPos.z = cc_matWorld[3][2] + a_position.z;\nvec4 pos = vec4(worldPos, 1.0);\npos = cc_matViewProj * pos;\nuvw = a_texCoord;\nuv0 = a_position.xz * UVScale.x;\nuv1 = a_position.xz * UVScale.y;\nuv2 = a_position.xz * UVScale.z;\nuv3 = a_position.xz * UVScale.w;\n#if USE_LIGHTMAP\nluv.xy = lightMapUVParam.xy + a_texCoord * lightMapUVParam.zw;\nluv.z = lightMapUVParam.z;\n#endif\nv_position = worldPos;\nv_normal = a_normal;\n#if CC_USE_FOG == 0\nv_fog_factor = LinearFog(vec4(worldPos, 1.0));\n#elif CC_USE_FOG == 1\nv_fog_factor = ExpFog(vec4(worldPos, 1.0));\n#elif CC_USE_FOG == 2\nv_fog_factor = ExpSquaredFog(vec4(worldPos, 1.0));\n#elif CC_USE_FOG == 3\nv_fog_factor = LayeredFog(vec4(worldPos, 1.0));\n#else\nv_fog_factor = 1.0;\n#endif\n#if USE_NORMALMAP\nv_tangent = vec3(1.0, 0.0, 0.0);\nv_binormal = vec3(0.0, 0.0, 1.0);\nv_binormal = cross(v_tangent, a_normal);\nv_tangent = cross(a_normal, v_binormal);\n#endif\nv_shadowPos = cc_matLightViewProj * vec4(worldPos, 1.0);\ngl_Position = pos;\n}",
              "frag": "\nprecision highp float;\nlayout(std140) uniform CCGlobal {\nhighp   vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp   mat4 cc_matView;\nhighp   mat4 cc_matViewInv;\nhighp   mat4 cc_matProj;\nhighp   mat4 cc_matProjInv;\nhighp   mat4 cc_matViewProj;\nhighp   mat4 cc_matViewProjInv;\nhighp   vec4 cc_cameraPos;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\n};\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nlayout(std140) uniform CCShadow {\nhighp mat4 cc_matLightPlaneProj;\nhighp mat4 cc_matLightView;\nhighp mat4 cc_matLightViewProj;\nlowp  vec4 cc_shadowNFLSInfo;\nlowp  vec4 cc_shadowWHPBInfo;\nlowp  vec4 cc_shadowLPNNInfo;\nlowp  vec4 cc_shadowColor;\n};\n#if CC_RECEIVE_SHADOW\nuniform sampler2D cc_shadowMap;\nuniform sampler2D cc_spotLightingMap;\nfloat CCGetLinearDepth (vec3 worldPos) {\nvec4 viewStartPos = cc_matLightView * vec4(worldPos.xyz, 1.0);\nfloat dist = length(viewStartPos.xyz);\nreturn cc_shadowNFLSInfo.x + (-dist / (cc_shadowNFLSInfo.y - cc_shadowNFLSInfo.x));\n}\nfloat CCGetShadowFactorHard (vec4 shadowPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nfloat shadow = 0.0;\nfloat closestDepth = 0.0;\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nclosestDepth = dot(texture(cc_shadowMap, clipPos.xy), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\n} else {\nclosestDepth = texture(cc_shadowMap, clipPos.xy).x;\n}\nshadow = step(closestDepth, clipPos.z- cc_shadowWHPBInfo.w);\nreturn shadow;\n}\nfloat CCGetShadowFactorSoft (vec4 shadowPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat offsetDepth = clipPos.z - cc_shadowWHPBInfo.w;\nvec2 oneTap = 1.0 / cc_shadowWHPBInfo.xy;\nvec2 clipPos_offset = clipPos.xy + oneTap;\nfloat block0, block1, block2, block3;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock1 = step(dot(texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock2 = step(dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock3 = step(dot(texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\n} else {\nblock0 = step(texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)).x, offsetDepth);\nblock1 = step(texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos.y)).x, offsetDepth);\nblock2 = step(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset.y)).x, offsetDepth);\nblock3 = step(texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos_offset.y)).x, offsetDepth);\n}\nfloat coefX   = mod(clipPos.x, oneTap.x) * cc_shadowWHPBInfo.x;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block2, block3, coefX);\nfloat coefY   = mod(clipPos.y, oneTap.y) * cc_shadowWHPBInfo.y;;\nreturn mix(resultX, resultY, coefY);\n}\nfloat CCGetShadowFactorSoft2X (vec4 shadowPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat bias = cc_shadowWHPBInfo.w;\nfloat offsetDepth = clipPos.z - bias;\nvec2 mapSize = cc_shadowWHPBInfo.xy;\nvec2 oneTap = 1.0 / mapSize;\nfloat clipPos_offset_L = clipPos.x - oneTap.x;\nfloat clipPos_offset_R = clipPos.x + oneTap.x;\nfloat clipPos_offset_U = clipPos.y - oneTap.y;\nfloat clipPos_offset_D = clipPos.y + oneTap.y;\nfloat block0, block1, block2, block3, block4, block5, block6, block7, block8;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(dot(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock1 = step(dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock2 = step(dot(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock3 = step(dot(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock4 = step(dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock5 = step(dot(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock6 = step(dot(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock7 = step(dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock8 = step(dot(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\n} else {\nblock0 = step(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_U)).x, offsetDepth);\nblock1 = step(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_U)).x, offsetDepth);\nblock2 = step(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_U)).x, offsetDepth);\nblock3 = step(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos.y)).x, offsetDepth);\nblock4 = step(texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)).x, offsetDepth);\nblock5 = step(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos.y)).x, offsetDepth);\nblock6 = step(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_D)).x, offsetDepth);\nblock7 = step(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_D)).x, offsetDepth);\nblock8 = step(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_D)).x, offsetDepth);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * mapSize.x;\nfloat coefY = mod(clipPos.y, oneTap.y) * mapSize.y;\nfloat shadow = 0.0;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block3, block4, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block1, block2, coefX);\nresultY = mix(block4, block5, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block3, block4, coefX);\nresultY = mix(block6, block7, coefX);\nshadow += mix(resultX, resultY, coefY);\nresultX = mix(block4, block5, coefX);\nresultY = mix(block7, block8, coefX);\nshadow += mix(resultX, resultY, coefY);\nreturn shadow * 0.25;\n}\nfloat CCGetSpotLightShadowFactorHard (vec4 shadowPos, vec3 worldPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nfloat shadow = 0.0;\nfloat closestDepth = 0.0;\nfloat depth = 0.0;\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nif (cc_shadowLPNNInfo.y > 0.000001) {\nclosestDepth = dot(texture(cc_spotLightingMap, clipPos.xy), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\n} else {\nclosestDepth = texture(cc_spotLightingMap, clipPos.xy).x;\n}\nshadow = step(closestDepth, depth - cc_shadowWHPBInfo.w);\nreturn shadow;\n}\nfloat CCGetSpotLightShadowFactorSoft (vec4 shadowPos, vec3 worldPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nfloat offsetx = 1.0 / cc_shadowWHPBInfo.x;\nfloat offsety = 1.0 / cc_shadowWHPBInfo.y;\nfloat shadow = 0.0;\nfloat depth = 0.0;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nfloat closestDepth = dot(texture(cc_spotLightingMap, vec2(clipPos.x - offsetx, clipPos.y - offsety)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = dot(texture(cc_spotLightingMap, vec2(clipPos.x - offsetx, clipPos.y + offsety)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = dot(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = dot(texture(cc_spotLightingMap, vec2(clipPos.x + offsetx, clipPos.y - offsety)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = dot(texture(cc_spotLightingMap, vec2(clipPos.x + offsetx, clipPos.y + offsety)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\n} else {\nfloat closestDepth = texture(cc_spotLightingMap, vec2(clipPos.x - offsetx, clipPos.y - offsety)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = texture(cc_spotLightingMap, vec2(clipPos.x - offsetx, clipPos.y + offsety)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = texture(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = texture(cc_spotLightingMap, vec2(clipPos.x + offsetx, clipPos.y - offsety)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = texture(cc_spotLightingMap, vec2(clipPos.x + offsetx, clipPos.y + offsety)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\n}\nreturn shadow / 5.0;\n}\nfloat CCGetSpotLightShadowFactorSoft2X (vec4 shadowPos, vec3 worldPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nfloat offsetx = 1.0 / cc_shadowWHPBInfo.x;\nfloat offsety = 1.0 / cc_shadowWHPBInfo.y;\nfloat shadow = 0.0;\nfloat depth = 0.0;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nfor (int i = -1; i <= 1; i++) {\nfor (int j = -1; j <= 1; j++) {\nfloat closestDepth = dot(texture(cc_spotLightingMap, clipPos.xy + vec2(i, j) * vec2(offsetx, offsety)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\n}\n}\n} else {\nfor (int i = -1; i <= 1; i++) {\nfor (int j = -1; j <= 1; j++) {\nfloat closestDepth = texture(cc_spotLightingMap, clipPos.xy + vec2(i, j) * vec2(offsetx, offsety)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\n}\n}\n}\nreturn shadow / 9.0;\n}\n#endif\n#if CC_USE_IBL\nuniform samplerCube cc_environment;\nvec3 unpackRGBE (vec4 rgbe) {\nreturn rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\nvec4 fragTextureLod (sampler2D tex, vec2 coord, float lod) {\nreturn textureLod(tex, coord, lod);\n}\nvec4 fragTextureLod (samplerCube tex, vec3 coord, float lod) {\nreturn textureLod(tex, coord, lod);\n}\n#endif\nfloat GGXMobile (float roughness, float NoH, vec3 H, vec3 N) {\nvec3 NxH = cross(N, H);\nfloat OneMinusNoHSqr = dot(NxH, NxH);\nfloat a = roughness * roughness;\nfloat n = NoH * a;\nfloat p = a / (OneMinusNoHSqr + n * n);\nreturn p * p;\n}\nfloat CalcSpecular (float roughness, float NoH, vec3 H, vec3 N) {\nreturn (roughness * 0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox (vec3 specular, float roughness, float NoV) {\nconst vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\nconst vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\nvec4 r = roughness * c0 + c1;\nfloat a004 = min(r.x * r.x, exp2(-9.28 * NoV)) * r.x + r.y;\nvec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;\nAB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\nreturn specular * AB.x + AB.y;\n}\nstruct StandardSurface {\nvec4 albedo;\nvec3 position;\nvec3 normal;\nvec3 emissive;\nvec3 lightmap;\nfloat lightmap_test;\nfloat roughness;\nfloat metallic;\nfloat occlusion;\n};\nvec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) {\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - s.position);\nfloat NV = max(abs(dot(N, V)), 0.001);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 L = normalize(-cc_mainLitDir.xyz);\nvec3 H = normalize(L + V);\nfloat NH = max(dot(N, H), 0.0);\nfloat NL = max(dot(N, L), 0.001);\nvec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w;\nvec3 diffuseContrib = diffuse;\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nif (s.lightmap_test > 0.0001) {\nfinalColor = s.lightmap.rgb;\n}\n#else\ndiffuseContrib /= 3.14159265359;\n#endif\nvec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\nvec3 dirlightContrib = (diffuseContrib + specularContrib);\n#if CC_RECEIVE_SHADOW\n{\nfloat pcf = cc_shadowWHPBInfo.z + 0.001;\nfloat shadowAttenuation = 0.0;\nfloat cosAngle = clamp(1.0 - dot(N, L.xyz), 0.0, 1.0);\nvec3 projWorldPos = shadowPos.xyz + cosAngle * cc_shadowLPNNInfo.z * N;\nvec4 pos = vec4(projWorldPos.xyz, shadowPos.w);\nif (pcf > 2.0) shadowAttenuation = CCGetShadowFactorSoft2X(pos);\nelse if (pcf > 1.0) shadowAttenuation = CCGetShadowFactorSoft(pos);\nelse shadowAttenuation = CCGetShadowFactorHard(pos);\nvec3 shadowColor = cc_shadowColor.rgb * cc_shadowColor.a + dirlightContrib.rgb * (1.0 - cc_shadowColor.a);\nif (cc_shadowNFLSInfo.w > 0.000001) {\ndirlightContrib.rgb = shadowColor.rgb * shadowAttenuation + dirlightContrib.rgb * (1.0 - shadowAttenuation);\n} else {\ndirlightContrib.rgb = shadowColor.rgb * shadowAttenuation * NL + dirlightContrib.rgb * (1.0 - shadowAttenuation * NL);\n}\n}\n#endif\nfinalColor *= dirlightContrib;\nfloat fAmb = 0.5 - N.y * 0.5;\nvec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\nfinalColor += (ambDiff.rgb * diffuse);\n#if CC_USE_IBL\nvec3 R = normalize(reflect(-V, N));\nvec4 envmap = fragTextureLod(cc_environment, R, s.roughness * cc_ambientGround.w);\n#if CC_USE_IBL == 2\nvec3 env = unpackRGBE(envmap);\n#else\nvec3 env = SRGBToLinear(envmap.rgb);\n#endif\nfinalColor += env * cc_ambientSky.w * specular;\n#endif\nfinalColor = finalColor * s.occlusion;\n#if CC_USE_HDR\ns.emissive *= cc_exposure.w;\n#endif\nfinalColor += s.emissive;\nreturn vec4(finalColor, s.albedo.a);\n}\nvec3 ACESToneMap (vec3 color) {\ncolor = min(color, vec3(8.0));\nconst float A = 2.51;\nconst float B = 0.03;\nconst float C = 2.43;\nconst float D = 0.59;\nconst float E = 0.14;\nreturn (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n#if !CC_USE_HDR\ncolor.rgb = sqrt(ACESToneMap(color.rgb));\n#endif\nreturn color;\n}\nin float v_fog_factor;\nin highp vec4 v_shadowPos;\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nin vec3 v_luv;\nuniform sampler2D cc_lightingMap;\nvec3 UnpackLightingmap(vec4 color) {\nvec3 c;\nfloat e = 1.0 + color.a * (8.0 - 1.0);\nc.r = color.r * e;\nc.g = color.g * e;\nc.b = color.b * e;\nreturn c;\n}\n#endif\nin highp vec3 v_position;\nin mediump vec3 v_normal;\n#if USE_NORMALMAP\nin mediump vec3 v_tangent;\nin mediump vec3 v_binormal;\n#endif\nin mediump vec2 uvw;\nin mediump vec2 uv0;\nin mediump vec2 uv1;\nin mediump vec2 uv2;\nin mediump vec2 uv3;\nin mediump vec3 diffuse;\nin mediump vec3 luv;\nlayout(std140) uniform PbrParams {\nvec4 metallic;\nvec4 roughness;\n};\nuniform sampler2D weightMap;\nuniform sampler2D detailMap0;\nuniform sampler2D detailMap1;\nuniform sampler2D detailMap2;\nuniform sampler2D detailMap3;\nuniform sampler2D normalMap0;\nuniform sampler2D normalMap1;\nuniform sampler2D normalMap2;\nuniform sampler2D normalMap3;\nuniform sampler2D lightMap;\nvoid surf (out StandardSurface s) {\n#if LAYERS > 1\nvec4 w = texture(weightMap, uvw);\n#endif\nvec4 baseColor = vec4(0, 0, 0, 0);\n#if LAYERS == 1\nbaseColor = texture(detailMap0, uv0);\n#elif LAYERS == 2\nbaseColor += texture(detailMap0, uv0) * w.r;\nbaseColor += texture(detailMap1, uv1) * w.g;\n#elif LAYERS == 3\nbaseColor += texture(detailMap0, uv0) * w.r;\nbaseColor += texture(detailMap1, uv1) * w.g;\nbaseColor += texture(detailMap2, uv2) * w.b;\n#elif LAYERS == 4\nbaseColor += texture(detailMap0, uv0) * w.r;\nbaseColor += texture(detailMap1, uv1) * w.g;\nbaseColor += texture(detailMap2, uv2) * w.b;\nbaseColor += texture(detailMap3, uv3) * w.a;\n#else\nbaseColor = texture(detailMap0, uv0);\n#endif\ns.position = v_position;\n#if USE_NORMALMAP\nvec4 baseNormal = vec4(0, 0, 0, 0);\n#if LAYERS == 1\nbaseNormal = texture(normalMap0, uv0);\n#elif LAYERS == 2\nbaseNormal += texture(normalMap0, uv0) * w.r;\nbaseNormal += texture(normalMap1, uv1) * w.g;\n#elif LAYERS == 3\nbaseNormal += texture(normalMap0, uv0) * w.r;\nbaseNormal += texture(normalMap1, uv1) * w.g;\nbaseNormal += texture(normalMap2, uv2) * w.b;\n#elif LAYERS == 4\nbaseNormal += texture(normalMap0, uv0) * w.r;\nbaseNormal += texture(normalMap1, uv1) * w.g;\nbaseNormal += texture(normalMap2, uv2) * w.b;\nbaseNormal += texture(normalMap3, uv3) * w.a;\n#else\nbaseNormal = texture(normalMap0, uv0);\n#endif\nvec3 nmmp = baseNormal.xyz - vec3(0.5);\ns.normal =\nnmmp.x * normalize(v_tangent) +\nnmmp.y * normalize(v_binormal) +\nnmmp.z * normalize(v_normal);\n#else\ns.normal = v_normal;\n#endif\ns.albedo = vec4(SRGBToLinear(baseColor.rgb), 1.0);\ns.occlusion = 1.0;\n#if USE_PBR\ns.roughness = 0.0;\n#if LAYERS == 1\ns.roughness = roughness.x;\n#elif LAYERS == 2\ns.roughness += roughness.x * w.r;\ns.roughness += roughness.y * w.g;\n#elif LAYERS == 3\ns.roughness += roughness.x * w.r;\ns.roughness += roughness.y * w.g;\ns.roughness += roughness.z * w.b;\n#elif LAYERS == 4\ns.roughness += roughness.x * w.r;\ns.roughness += roughness.y * w.g;\ns.roughness += roughness.z * w.b;\ns.roughness += roughness.w * w.a;\n#else\ns.roughness = 1.0;\n#endif\ns.metallic = 0.0;\n#if LAYERS == 1\ns.metallic = metallic.x;\n#elif LAYERS == 2\ns.metallic += metallic.x * w.r;\ns.metallic += metallic.y * w.g;\n#elif LAYERS == 3\ns.metallic += metallic.x * w.r;\ns.metallic += metallic.y * w.g;\ns.metallic += metallic.z * w.b;\n#elif LAYERS == 4\ns.metallic += metallic.x * w.r;\ns.metallic += metallic.y * w.g;\ns.metallic += metallic.z * w.b;\ns.metallic += metallic.w * w.a;\n#else\ns.metallic = 0.0;\n#endif\n#else\ns.roughness = 1.0;\ns.metallic = 0.0;\n#endif\ns.emissive = vec3(0.0, 0.0, 0.0);\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nvec4 lightColor = texture(lightMap, luv.xy);\ns.lightmap = UnpackLightingmap(lightColor);\ns.lightmap_test = luv.z;\n#endif\n}\n#if CC_FORWARD_ADD\n#if CC_PIPELINE_TYPE == 0\n# define LIGHTS_PER_PASS 1\n#else\n# define LIGHTS_PER_PASS 10\n#endif\nlayout(std140) uniform CCForwardLight {\nhighp vec4 cc_lightPos[LIGHTS_PER_PASS];\nvec4 cc_lightColor[LIGHTS_PER_PASS];\nvec4 cc_lightSizeRangeAngle[LIGHTS_PER_PASS];\nvec4 cc_lightDir[LIGHTS_PER_PASS];\n};\nfloat SmoothDistAtt (float distSqr, float invSqrAttRadius) {\nfloat factor = distSqr * invSqrAttRadius;\nfloat smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\nreturn smoothFactor * smoothFactor;\n}\nfloat GetDistAtt (float distSqr, float invSqrAttRadius) {\nfloat attenuation = 1.0 / max(distSqr, 0.01*0.01);\nattenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\nreturn attenuation;\n}\nfloat GetAngleAtt (vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\nfloat cd = dot(litDir, L);\nfloat attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\nreturn (attenuation * attenuation);\n}\nvec4 CCStandardShadingAdditive (StandardSurface s, vec4 shadowPos) {\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 diffuseContrib = diffuse / 3.14159265359;\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - s.position);\nfloat NV = max(abs(dot(N, V)), 0.001);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 finalColor = vec3(0.0);\nint numLights = CC_PIPELINE_TYPE == 0 ? LIGHTS_PER_PASS : int(cc_lightDir[0].w);\nfor (int i = 0; i < LIGHTS_PER_PASS; i++) {\nif (i >= numLights) break;\nvec3 SLU = cc_lightPos[i].xyz - s.position;\nvec3 SL = normalize(SLU);\nvec3 SH = normalize(SL + V);\nfloat SNL = max(dot(N, SL), 0.001);\nfloat SNH = max(dot(N, SH), 0.0);\nfloat distSqr = dot(SLU, SLU);\nfloat litRadius = cc_lightSizeRangeAngle[i].x;\nfloat litRadiusSqr = litRadius * litRadius;\nfloat illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\nfloat attRadiusSqrInv = 1.0 / max(cc_lightSizeRangeAngle[i].y, 0.01);\nattRadiusSqrInv *= attRadiusSqrInv;\nfloat att = GetDistAtt(distSqr, attRadiusSqrInv);\nvec3 lspec = specular * CalcSpecular(s.roughness, SNH, SH, N);\nif (cc_lightPos[i].w > 0.0) {\nfloat cosInner = max(dot(-cc_lightDir[i].xyz, SL), 0.01);\nfloat cosOuter = cc_lightSizeRangeAngle[i].z;\nfloat litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\nfloat litAngleOffset = -cosOuter * litAngleScale;\natt *= GetAngleAtt(SL, -cc_lightDir[i].xyz, litAngleScale, litAngleOffset);\n}\nvec3 lightColor = cc_lightColor[i].rgb;\n#if CC_RECEIVE_SHADOW\nif (cc_lightPos[i].w > 0.0) {\n{\nfloat pcf = cc_shadowWHPBInfo.z + 0.001;\nfloat shadowAttenuation = 0.0;\nfloat cosAngle = clamp(1.0 - dot(N, normalize(cc_lightPos[i].xyz - s.position.xyz)), 0.0, 1.0);\nvec3 projWorldPos = shadowPos.xyz + cosAngle * cc_shadowLPNNInfo.z * N;\nvec4 pos = vec4(projWorldPos.xyz, shadowPos.w);\nif (pcf > 2.0) shadowAttenuation = CCGetSpotLightShadowFactorSoft2X(pos, s.position);\nelse if (pcf > 1.0) shadowAttenuation = CCGetSpotLightShadowFactorSoft(pos, s.position);\nelse shadowAttenuation = CCGetSpotLightShadowFactorHard(pos, s.position);\nlightColor *= 1.0 - shadowAttenuation;\n}\n}\n#endif\nfinalColor += SNL * lightColor * cc_lightColor[i].w * illum * att * (diffuseContrib + lspec);\n}\nfinalColor = finalColor * s.occlusion;\nreturn vec4(finalColor, 0.0);\n}\nlayout(location = 0) out vec4 fragColorX;\nvoid main () {\nStandardSurface s; surf(s);\nvec4 color = CCStandardShadingAdditive(s, v_shadowPos);\ncolor = vec4(mix(CC_FORWARD_ADD > 0 ? vec3(0.0) : cc_fogColor.rgb, color.rgb, v_fog_factor), color.a);\nfragColorX = CCFragOutput(color);\n}\n#elif CC_PIPELINE_TYPE == 0\nlayout(location = 0) out vec4 fragColorX;\nvoid main () {\nStandardSurface s; surf(s);\nvec4 color = CCStandardShadingBase(s, v_shadowPos);\ncolor = vec4(mix(CC_FORWARD_ADD > 0 ? vec3(0.0) : cc_fogColor.rgb, color.rgb, v_fog_factor), color.a);\nfragColorX = CCFragOutput(color);\n}\n#elif CC_PIPELINE_TYPE == 1\nlayout(location = 0) out vec4 fragColor0;\nlayout(location = 1) out vec4 fragColor1;\nlayout(location = 2) out vec4 fragColor2;\nlayout(location = 3) out vec4 fragColor3;\nvoid main () {\nStandardSurface s; surf(s);\nfragColor0 = s.albedo;\nfragColor1 = vec4(s.position, s.roughness);\nfragColor2 = vec4(s.normal, s.metallic);\nfragColor3 = vec4(s.emissive, s.occlusion);\n}\n#endif"
            }, {
              "vert": "\nprecision highp float;\nlayout(std140) uniform CCGlobal {\nhighp   vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp   mat4 cc_matView;\nhighp   mat4 cc_matViewInv;\nhighp   mat4 cc_matProj;\nhighp   mat4 cc_matProjInv;\nhighp   mat4 cc_matViewProj;\nhighp   mat4 cc_matViewProjInv;\nhighp   vec4 cc_cameraPos;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\n};\nlayout(std140) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\n};\nlayout(std140) uniform CCShadow {\nhighp mat4 cc_matLightPlaneProj;\nhighp mat4 cc_matLightView;\nhighp mat4 cc_matLightViewProj;\nlowp  vec4 cc_shadowNFLSInfo;\nlowp  vec4 cc_shadowWHPBInfo;\nlowp  vec4 cc_shadowLPNNInfo;\nlowp  vec4 cc_shadowColor;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec2 a_texCoord;\nout vec2 v_clip_depth;\nvec4 vert () {\nvec4 worldPos;\nworldPos.x = cc_matWorld[3][0] + a_position.x;\nworldPos.y = cc_matWorld[3][1] + a_position.y;\nworldPos.z = cc_matWorld[3][2] + a_position.z;\nworldPos.w = 1.0;\nvec4 clipPos = cc_matLightViewProj * worldPos;\nv_clip_depth = clipPos.zw;\nreturn clipPos;\n}\nvoid main() { gl_Position = vert(); }",
              "frag": "\nprecision highp float;\nvec4 packDepthToRGBA (float depth) {\nvec4 ret = vec4(1.0, 255.0, 65025.0, 160581375.0) * depth;\nret = fract(ret);\nret -= ret.yzww * vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);\nreturn ret;\n}\nin vec2 v_clip_depth;\nvec4 frag () {\nreturn packDepthToRGBA(v_clip_depth.x / v_clip_depth.y * 0.5 + 0.5);\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }"
            }], [{
              "vert": "\nprecision highp float;\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec2 a_texCoord;\nin vec4 a_tangent;\n#if CC_USE_MORPH\nin float a_vertexId;\nint getVertexId() {\nreturn int(a_vertexId);\n}\nlayout(std140) uniform CCMorph {\nvec4 cc_displacementWeights[15];\nvec4 cc_displacementTextureInfo;\n};\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int pixelIndex) {\nivec2 texSize = textureSize(tex, 0);\nreturn texelFetch(tex, ivec2(pixelIndex % texSize.x, pixelIndex / texSize.x), 0);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture(tex, x)),\ndecode32(texture(tex, y)),\ndecode32(texture(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nuniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nuniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nuniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nattr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nattr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nattr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_joints;\nin vec4 a_weights;\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nin highp vec4 a_jointAnimInfo;\n#endif\nlayout(std140) uniform CCSkinningTexture {\nhighp vec4 cc_jointTextureInfo;\n};\nlayout(std140) uniform CCSkinningAnimation {\nhighp vec4 cc_jointAnimInfo;\n};\nuniform highp sampler2D cc_jointTexture;\n#else\nlayout(std140) uniform CCSkinning {\nhighp vec4 cc_joints[30 * 3];\n};\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\n#if USE_INSTANCING\nhighp float j = 3.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n#else\nhighp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n#endif\nhighp float invSize = cc_jointTextureInfo.w;\nhighp float y = floor(j * invSize);\nhighp float x = floor(j - y * cc_jointTextureInfo.x);\ny = (y + 0.5) * invSize;\nvec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\n#if USE_INSTANCING\nhighp float j = 12.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n#else\nhighp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n#endif\nhighp float invSize = cc_jointTextureInfo.w;\nhighp float y = floor(j * invSize);\nhighp float x = floor(j - y * cc_jointTextureInfo.x);\ny = (y + 0.5) * invSize;\nvec4 v1 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\nmat4 m = skinMatrix();\nattr.position = m * attr.position;\nattr.normal = (m * vec4(attr.normal, 0.0)).xyz;\nattr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nlayout(std140) uniform CCGlobal {\nhighp   vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp   mat4 cc_matView;\nhighp   mat4 cc_matViewInv;\nhighp   mat4 cc_matProj;\nhighp   mat4 cc_matProjInv;\nhighp   mat4 cc_matViewProj;\nhighp   mat4 cc_matViewProjInv;\nhighp   vec4 cc_cameraPos;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\n};\n#if USE_INSTANCING\nin vec4 a_matWorld0;\nin vec4 a_matWorld1;\nin vec4 a_matWorld2;\n#if USE_LIGHTMAP\nin vec4 a_lightingMapUVParam;\n#endif\n#elif USE_BATCHING\nin float a_dyn_batch_id;\nlayout(std140) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#else\nlayout(std140) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\n};\n#endif\nfloat LinearFog(vec4 pos) {\nvec4 wPos = pos;\nfloat cam_dis = distance(cc_cameraPos, wPos);\nfloat fogStart = cc_fogBase.x;\nfloat fogEnd = cc_fogBase.y;\nreturn clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = distance(cc_cameraPos, wPos) / fogAtten * 4.;\nfloat f = exp(-cam_dis * fogDensity);\nreturn f;\n}\nfloat ExpSquaredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = distance(cc_cameraPos, wPos) / fogAtten * 4.;\nfloat f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\nreturn f;\n}\nfloat LayeredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat _FogTop = cc_fogAdd.x;\nfloat _FogRange = cc_fogAdd.y;\nvec3 camWorldProj = cc_cameraPos.xyz;\ncamWorldProj.y = 0.;\nvec3 worldPosProj = wPos.xyz;\nworldPosProj.y = 0.;\nfloat fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\nfloat fDeltaY, fDensityIntegral;\nif (cc_cameraPos.y > _FogTop) {\nif (wPos.y < _FogTop) {\nfDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\nfDensityIntegral = fDeltaY * fDeltaY * 0.5;\n} else {\nfDeltaY = 0.;\nfDensityIntegral = 0.;\n}\n} else {\nif (wPos.y < _FogTop) {\nfloat fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfloat fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\nfDeltaY = abs(fDeltaA - fDeltaB);\nfDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n} else {\nfDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n}\n}\nfloat fDensity;\nif (fDeltaY != 0.) {\nfDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n} else {\nfDensity = 0.;\n}\nfloat f = exp(-fDensity);\nreturn f;\n}\nout float v_fog_factor;\n#if USE_VERTEX_COLOR\nin lowp vec4 a_color;\nout lowp vec4 v_color;\n#endif\n#if USE_TEXTURE\nout vec2 v_uv;\nlayout(std140) uniform TexCoords {\nvec4 tilingOffset;\n};\n#endif\nvec4 vert () {\nvec4 position;\nposition = vec4(a_position, 1.0);\n#if CC_USE_MORPH\napplyMorph(position);\n#endif\n#if CC_USE_SKINNING\nCCSkin(position);\n#endif\nmat4 matWorld;\n#if USE_INSTANCING\nmatWorld = mat4(\nvec4(a_matWorld0.xyz, 0.0),\nvec4(a_matWorld1.xyz, 0.0),\nvec4(a_matWorld2.xyz, 0.0),\nvec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n);\n#elif USE_BATCHING\nmatWorld = cc_matWorlds[int(a_dyn_batch_id)];\n#else\nmatWorld = cc_matWorld;\n#endif\n#if USE_TEXTURE\nv_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n#if SAMPLE_FROM_RT\nv_uv = cc_cameraPos.w > 1.0 ? vec2(v_uv.x, 1.0 - v_uv.y) : v_uv;\n#endif\n#endif\n#if USE_VERTEX_COLOR\nv_color = a_color;\n#endif\n#if CC_USE_FOG == 0\nv_fog_factor = LinearFog(matWorld * position);\n#elif CC_USE_FOG == 1\nv_fog_factor = ExpFog(matWorld * position);\n#elif CC_USE_FOG == 2\nv_fog_factor = ExpSquaredFog(matWorld * position);\n#elif CC_USE_FOG == 3\nv_fog_factor = LayeredFog(matWorld * position);\n#else\nv_fog_factor = 1.0;\n#endif\nreturn cc_matProj * (cc_matView * matWorld) * position;\n}\nvoid main() { gl_Position = vert(); }",
              "frag": "\nprecision highp float;\nlayout(std140) uniform CCGlobal {\nhighp   vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp   mat4 cc_matView;\nhighp   mat4 cc_matViewInv;\nhighp   mat4 cc_matProj;\nhighp   mat4 cc_matProjInv;\nhighp   mat4 cc_matViewProj;\nhighp   mat4 cc_matViewProjInv;\nhighp   vec4 cc_cameraPos;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\n};\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n#if CC_USE_HDR\ncolor.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n#endif\nreturn color;\n}\nin float v_fog_factor;\n#if USE_ALPHA_TEST\n#endif\n#if USE_TEXTURE\nin vec2 v_uv;\nuniform sampler2D mainTexture;\n#endif\nlayout(std140) uniform Constant {\nvec4 mainColor;\nvec4 colorScaleAndCutoff;\n};\n#if USE_VERTEX_COLOR\nin lowp vec4 v_color;\n#endif\nvec4 frag () {\nvec4 o = mainColor;\no.rgb *= colorScaleAndCutoff.xyz;\n#if USE_VERTEX_COLOR\no *= v_color;\n#endif\n#if USE_TEXTURE\no *= texture(mainTexture, v_uv);\n#endif\n#if USE_ALPHA_TEST\nif (o.ALPHA_TEST_CHANNEL < colorScaleAndCutoff.w) discard;\n#endif\no = vec4(mix(CC_FORWARD_ADD > 0 ? vec3(0.0) : cc_fogColor.rgb, o.rgb, v_fog_factor), o.a);\nreturn CCFragOutput(o);\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }"
            }], [{
              "vert": "\nprecision highp float;\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec2 a_texCoord;\nin vec4 a_tangent;\nlayout(std140) uniform CCGlobal {\nhighp   vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp   mat4 cc_matView;\nhighp   mat4 cc_matViewInv;\nhighp   mat4 cc_matProj;\nhighp   mat4 cc_matProjInv;\nhighp   mat4 cc_matViewProj;\nhighp   mat4 cc_matViewProjInv;\nhighp   vec4 cc_cameraPos;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\n};\nout vec2 v_uv;\nvoid main () {\nvec4 position;\nposition = vec4(a_position, 1.0);\nposition.xy = cc_cameraPos.w == 0.0 ? vec2(position.xy.x, -position.xy.y) : position.xy;\ngl_Position = vec4(position.x, position.y, 1.0, 1.0);\nv_uv = a_texCoord;\n}",
              "frag": "\nprecision highp float;\nlayout(std140) uniform CCGlobal {\nhighp   vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp   mat4 cc_matView;\nhighp   mat4 cc_matViewInv;\nhighp   mat4 cc_matProj;\nhighp   mat4 cc_matProjInv;\nhighp   mat4 cc_matViewProj;\nhighp   mat4 cc_matViewProjInv;\nhighp   vec4 cc_cameraPos;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\n};\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nlayout(std140) uniform CCShadow {\nhighp mat4 cc_matLightPlaneProj;\nhighp mat4 cc_matLightView;\nhighp mat4 cc_matLightViewProj;\nlowp  vec4 cc_shadowNFLSInfo;\nlowp  vec4 cc_shadowWHPBInfo;\nlowp  vec4 cc_shadowLPNNInfo;\nlowp  vec4 cc_shadowColor;\n};\n#if CC_RECEIVE_SHADOW\nuniform sampler2D cc_shadowMap;\nuniform sampler2D cc_spotLightingMap;\nfloat CCGetLinearDepth (vec3 worldPos) {\nvec4 viewStartPos = cc_matLightView * vec4(worldPos.xyz, 1.0);\nfloat dist = length(viewStartPos.xyz);\nreturn cc_shadowNFLSInfo.x + (-dist / (cc_shadowNFLSInfo.y - cc_shadowNFLSInfo.x));\n}\nfloat CCGetShadowFactorHard (vec4 shadowPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nfloat shadow = 0.0;\nfloat closestDepth = 0.0;\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nclosestDepth = dot(texture(cc_shadowMap, clipPos.xy), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\n} else {\nclosestDepth = texture(cc_shadowMap, clipPos.xy).x;\n}\nshadow = step(closestDepth, clipPos.z- cc_shadowWHPBInfo.w);\nreturn shadow;\n}\nfloat CCGetShadowFactorSoft (vec4 shadowPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat offsetDepth = clipPos.z - cc_shadowWHPBInfo.w;\nvec2 oneTap = 1.0 / cc_shadowWHPBInfo.xy;\nvec2 clipPos_offset = clipPos.xy + oneTap;\nfloat block0, block1, block2, block3;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock1 = step(dot(texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock2 = step(dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock3 = step(dot(texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\n} else {\nblock0 = step(texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)).x, offsetDepth);\nblock1 = step(texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos.y)).x, offsetDepth);\nblock2 = step(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset.y)).x, offsetDepth);\nblock3 = step(texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos_offset.y)).x, offsetDepth);\n}\nfloat coefX   = mod(clipPos.x, oneTap.x) * cc_shadowWHPBInfo.x;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block2, block3, coefX);\nfloat coefY   = mod(clipPos.y, oneTap.y) * cc_shadowWHPBInfo.y;;\nreturn mix(resultX, resultY, coefY);\n}\nfloat CCGetShadowFactorSoft2X (vec4 shadowPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat bias = cc_shadowWHPBInfo.w;\nfloat offsetDepth = clipPos.z - bias;\nvec2 mapSize = cc_shadowWHPBInfo.xy;\nvec2 oneTap = 1.0 / mapSize;\nfloat clipPos_offset_L = clipPos.x - oneTap.x;\nfloat clipPos_offset_R = clipPos.x + oneTap.x;\nfloat clipPos_offset_U = clipPos.y - oneTap.y;\nfloat clipPos_offset_D = clipPos.y + oneTap.y;\nfloat block0, block1, block2, block3, block4, block5, block6, block7, block8;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(dot(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock1 = step(dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock2 = step(dot(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock3 = step(dot(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock4 = step(dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock5 = step(dot(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock6 = step(dot(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock7 = step(dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\nblock8 = step(dot(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)), offsetDepth);\n} else {\nblock0 = step(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_U)).x, offsetDepth);\nblock1 = step(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_U)).x, offsetDepth);\nblock2 = step(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_U)).x, offsetDepth);\nblock3 = step(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos.y)).x, offsetDepth);\nblock4 = step(texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)).x, offsetDepth);\nblock5 = step(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos.y)).x, offsetDepth);\nblock6 = step(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_D)).x, offsetDepth);\nblock7 = step(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_D)).x, offsetDepth);\nblock8 = step(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_D)).x, offsetDepth);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * mapSize.x;\nfloat coefY = mod(clipPos.y, oneTap.y) * mapSize.y;\nfloat shadow = 0.0;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block3, block4, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block1, block2, coefX);\nresultY = mix(block4, block5, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block3, block4, coefX);\nresultY = mix(block6, block7, coefX);\nshadow += mix(resultX, resultY, coefY);\nresultX = mix(block4, block5, coefX);\nresultY = mix(block7, block8, coefX);\nshadow += mix(resultX, resultY, coefY);\nreturn shadow * 0.25;\n}\nfloat CCGetSpotLightShadowFactorHard (vec4 shadowPos, vec3 worldPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nfloat shadow = 0.0;\nfloat closestDepth = 0.0;\nfloat depth = 0.0;\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nif (cc_shadowLPNNInfo.y > 0.000001) {\nclosestDepth = dot(texture(cc_spotLightingMap, clipPos.xy), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\n} else {\nclosestDepth = texture(cc_spotLightingMap, clipPos.xy).x;\n}\nshadow = step(closestDepth, depth - cc_shadowWHPBInfo.w);\nreturn shadow;\n}\nfloat CCGetSpotLightShadowFactorSoft (vec4 shadowPos, vec3 worldPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nfloat offsetx = 1.0 / cc_shadowWHPBInfo.x;\nfloat offsety = 1.0 / cc_shadowWHPBInfo.y;\nfloat shadow = 0.0;\nfloat depth = 0.0;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nfloat closestDepth = dot(texture(cc_spotLightingMap, vec2(clipPos.x - offsetx, clipPos.y - offsety)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = dot(texture(cc_spotLightingMap, vec2(clipPos.x - offsetx, clipPos.y + offsety)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = dot(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = dot(texture(cc_spotLightingMap, vec2(clipPos.x + offsetx, clipPos.y - offsety)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = dot(texture(cc_spotLightingMap, vec2(clipPos.x + offsetx, clipPos.y + offsety)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\n} else {\nfloat closestDepth = texture(cc_spotLightingMap, vec2(clipPos.x - offsetx, clipPos.y - offsety)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = texture(cc_spotLightingMap, vec2(clipPos.x - offsetx, clipPos.y + offsety)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = texture(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = texture(cc_spotLightingMap, vec2(clipPos.x + offsetx, clipPos.y - offsety)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\nclosestDepth = texture(cc_spotLightingMap, vec2(clipPos.x + offsetx, clipPos.y + offsety)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\n}\nreturn shadow / 5.0;\n}\nfloat CCGetSpotLightShadowFactorSoft2X (vec4 shadowPos, vec3 worldPos) {\nvec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z <-1.0 || clipPos.z > 1.0) { return 0.0; }\nfloat offsetx = 1.0 / cc_shadowWHPBInfo.x;\nfloat offsety = 1.0 / cc_shadowWHPBInfo.y;\nfloat shadow = 0.0;\nfloat depth = 0.0;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nfor (int i = -1; i <= 1; i++) {\nfor (int j = -1; j <= 1; j++) {\nfloat closestDepth = dot(texture(cc_spotLightingMap, clipPos.xy + vec2(i, j) * vec2(offsetx, offsety)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\n}\n}\n} else {\nfor (int i = -1; i <= 1; i++) {\nfor (int j = -1; j <= 1; j++) {\nfloat closestDepth = texture(cc_spotLightingMap, clipPos.xy + vec2(i, j) * vec2(offsetx, offsety)).x;\nshadow += step(closestDepth, depth - cc_shadowWHPBInfo.w);\n}\n}\n}\nreturn shadow / 9.0;\n}\n#endif\n#if CC_USE_IBL\nuniform samplerCube cc_environment;\nvec3 unpackRGBE (vec4 rgbe) {\nreturn rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\nvec4 fragTextureLod (sampler2D tex, vec2 coord, float lod) {\nreturn textureLod(tex, coord, lod);\n}\nvec4 fragTextureLod (samplerCube tex, vec3 coord, float lod) {\nreturn textureLod(tex, coord, lod);\n}\n#endif\nfloat GGXMobile (float roughness, float NoH, vec3 H, vec3 N) {\nvec3 NxH = cross(N, H);\nfloat OneMinusNoHSqr = dot(NxH, NxH);\nfloat a = roughness * roughness;\nfloat n = NoH * a;\nfloat p = a / (OneMinusNoHSqr + n * n);\nreturn p * p;\n}\nfloat CalcSpecular (float roughness, float NoH, vec3 H, vec3 N) {\nreturn (roughness * 0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox (vec3 specular, float roughness, float NoV) {\nconst vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\nconst vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\nvec4 r = roughness * c0 + c1;\nfloat a004 = min(r.x * r.x, exp2(-9.28 * NoV)) * r.x + r.y;\nvec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;\nAB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\nreturn specular * AB.x + AB.y;\n}\nstruct StandardSurface {\nvec4 albedo;\nvec3 position;\nvec3 normal;\nvec3 emissive;\nvec3 lightmap;\nfloat lightmap_test;\nfloat roughness;\nfloat metallic;\nfloat occlusion;\n};\nvec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) {\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - s.position);\nfloat NV = max(abs(dot(N, V)), 0.001);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 L = normalize(-cc_mainLitDir.xyz);\nvec3 H = normalize(L + V);\nfloat NH = max(dot(N, H), 0.0);\nfloat NL = max(dot(N, L), 0.001);\nvec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w;\nvec3 diffuseContrib = diffuse;\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nif (s.lightmap_test > 0.0001) {\nfinalColor = s.lightmap.rgb;\n}\n#else\ndiffuseContrib /= 3.14159265359;\n#endif\nvec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\nvec3 dirlightContrib = (diffuseContrib + specularContrib);\n#if CC_RECEIVE_SHADOW\n{\nfloat pcf = cc_shadowWHPBInfo.z + 0.001;\nfloat shadowAttenuation = 0.0;\nfloat cosAngle = clamp(1.0 - dot(N, L.xyz), 0.0, 1.0);\nvec3 projWorldPos = shadowPos.xyz + cosAngle * cc_shadowLPNNInfo.z * N;\nvec4 pos = vec4(projWorldPos.xyz, shadowPos.w);\nif (pcf > 2.0) shadowAttenuation = CCGetShadowFactorSoft2X(pos);\nelse if (pcf > 1.0) shadowAttenuation = CCGetShadowFactorSoft(pos);\nelse shadowAttenuation = CCGetShadowFactorHard(pos);\nvec3 shadowColor = cc_shadowColor.rgb * cc_shadowColor.a + dirlightContrib.rgb * (1.0 - cc_shadowColor.a);\nif (cc_shadowNFLSInfo.w > 0.000001) {\ndirlightContrib.rgb = shadowColor.rgb * shadowAttenuation + dirlightContrib.rgb * (1.0 - shadowAttenuation);\n} else {\ndirlightContrib.rgb = shadowColor.rgb * shadowAttenuation * NL + dirlightContrib.rgb * (1.0 - shadowAttenuation * NL);\n}\n}\n#endif\nfinalColor *= dirlightContrib;\nfloat fAmb = 0.5 - N.y * 0.5;\nvec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\nfinalColor += (ambDiff.rgb * diffuse);\n#if CC_USE_IBL\nvec3 R = normalize(reflect(-V, N));\nvec4 envmap = fragTextureLod(cc_environment, R, s.roughness * cc_ambientGround.w);\n#if CC_USE_IBL == 2\nvec3 env = unpackRGBE(envmap);\n#else\nvec3 env = SRGBToLinear(envmap.rgb);\n#endif\nfinalColor += env * cc_ambientSky.w * specular;\n#endif\nfinalColor = finalColor * s.occlusion;\n#if CC_USE_HDR\ns.emissive *= cc_exposure.w;\n#endif\nfinalColor += s.emissive;\nreturn vec4(finalColor, s.albedo.a);\n}\n#if CC_PIPELINE_TYPE == 0\n# define LIGHTS_PER_PASS 1\n#else\n# define LIGHTS_PER_PASS 10\n#endif\nlayout(std140) uniform CCForwardLight {\nhighp vec4 cc_lightPos[LIGHTS_PER_PASS];\nvec4 cc_lightColor[LIGHTS_PER_PASS];\nvec4 cc_lightSizeRangeAngle[LIGHTS_PER_PASS];\nvec4 cc_lightDir[LIGHTS_PER_PASS];\n};\nfloat SmoothDistAtt (float distSqr, float invSqrAttRadius) {\nfloat factor = distSqr * invSqrAttRadius;\nfloat smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\nreturn smoothFactor * smoothFactor;\n}\nfloat GetDistAtt (float distSqr, float invSqrAttRadius) {\nfloat attenuation = 1.0 / max(distSqr, 0.01*0.01);\nattenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\nreturn attenuation;\n}\nfloat GetAngleAtt (vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\nfloat cd = dot(litDir, L);\nfloat attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\nreturn (attenuation * attenuation);\n}\nvec4 CCStandardShadingAdditive (StandardSurface s, vec4 shadowPos) {\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 diffuseContrib = diffuse / 3.14159265359;\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - s.position);\nfloat NV = max(abs(dot(N, V)), 0.001);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 finalColor = vec3(0.0);\nint numLights = CC_PIPELINE_TYPE == 0 ? LIGHTS_PER_PASS : int(cc_lightDir[0].w);\nfor (int i = 0; i < LIGHTS_PER_PASS; i++) {\nif (i >= numLights) break;\nvec3 SLU = cc_lightPos[i].xyz - s.position;\nvec3 SL = normalize(SLU);\nvec3 SH = normalize(SL + V);\nfloat SNL = max(dot(N, SL), 0.001);\nfloat SNH = max(dot(N, SH), 0.0);\nfloat distSqr = dot(SLU, SLU);\nfloat litRadius = cc_lightSizeRangeAngle[i].x;\nfloat litRadiusSqr = litRadius * litRadius;\nfloat illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\nfloat attRadiusSqrInv = 1.0 / max(cc_lightSizeRangeAngle[i].y, 0.01);\nattRadiusSqrInv *= attRadiusSqrInv;\nfloat att = GetDistAtt(distSqr, attRadiusSqrInv);\nvec3 lspec = specular * CalcSpecular(s.roughness, SNH, SH, N);\nif (cc_lightPos[i].w > 0.0) {\nfloat cosInner = max(dot(-cc_lightDir[i].xyz, SL), 0.01);\nfloat cosOuter = cc_lightSizeRangeAngle[i].z;\nfloat litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\nfloat litAngleOffset = -cosOuter * litAngleScale;\natt *= GetAngleAtt(SL, -cc_lightDir[i].xyz, litAngleScale, litAngleOffset);\n}\nvec3 lightColor = cc_lightColor[i].rgb;\n#if CC_RECEIVE_SHADOW\nif (cc_lightPos[i].w > 0.0) {\n{\nfloat pcf = cc_shadowWHPBInfo.z + 0.001;\nfloat shadowAttenuation = 0.0;\nfloat cosAngle = clamp(1.0 - dot(N, normalize(cc_lightPos[i].xyz - s.position.xyz)), 0.0, 1.0);\nvec3 projWorldPos = shadowPos.xyz + cosAngle * cc_shadowLPNNInfo.z * N;\nvec4 pos = vec4(projWorldPos.xyz, shadowPos.w);\nif (pcf > 2.0) shadowAttenuation = CCGetSpotLightShadowFactorSoft2X(pos, s.position);\nelse if (pcf > 1.0) shadowAttenuation = CCGetSpotLightShadowFactorSoft(pos, s.position);\nelse shadowAttenuation = CCGetSpotLightShadowFactorHard(pos, s.position);\nlightColor *= 1.0 - shadowAttenuation;\n}\n}\n#endif\nfinalColor += SNL * lightColor * cc_lightColor[i].w * illum * att * (diffuseContrib + lspec);\n}\nfinalColor = finalColor * s.occlusion;\nreturn vec4(finalColor, 0.0);\n}\nvec3 ACESToneMap (vec3 color) {\ncolor = min(color, vec3(8.0));\nconst float A = 2.51;\nconst float B = 0.03;\nconst float C = 2.43;\nconst float D = 0.59;\nconst float E = 0.14;\nreturn (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n#if !CC_USE_HDR\ncolor.rgb = sqrt(ACESToneMap(color.rgb));\n#endif\nreturn color;\n}\nfloat LinearFog(vec4 pos) {\nvec4 wPos = pos;\nfloat cam_dis = distance(cc_cameraPos, wPos);\nfloat fogStart = cc_fogBase.x;\nfloat fogEnd = cc_fogBase.y;\nreturn clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = distance(cc_cameraPos, wPos) / fogAtten * 4.;\nfloat f = exp(-cam_dis * fogDensity);\nreturn f;\n}\nfloat ExpSquaredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = distance(cc_cameraPos, wPos) / fogAtten * 4.;\nfloat f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\nreturn f;\n}\nfloat LayeredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat _FogTop = cc_fogAdd.x;\nfloat _FogRange = cc_fogAdd.y;\nvec3 camWorldProj = cc_cameraPos.xyz;\ncamWorldProj.y = 0.;\nvec3 worldPosProj = wPos.xyz;\nworldPosProj.y = 0.;\nfloat fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\nfloat fDeltaY, fDensityIntegral;\nif (cc_cameraPos.y > _FogTop) {\nif (wPos.y < _FogTop) {\nfDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\nfDensityIntegral = fDeltaY * fDeltaY * 0.5;\n} else {\nfDeltaY = 0.;\nfDensityIntegral = 0.;\n}\n} else {\nif (wPos.y < _FogTop) {\nfloat fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfloat fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\nfDeltaY = abs(fDeltaA - fDeltaB);\nfDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n} else {\nfDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n}\n}\nfloat fDensity;\nif (fDeltaY != 0.) {\nfDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n} else {\nfDensity = 0.;\n}\nfloat f = exp(-fDensity);\nreturn f;\n}\nin vec2 v_uv;\nuniform sampler2D cc_gbuffer_albedoMap;\nuniform sampler2D cc_gbuffer_positionMap;\nuniform sampler2D cc_gbuffer_normalMap;\nuniform sampler2D cc_gbuffer_emissiveMap;\nlayout(location = 0) out vec4 fragColor;\nvoid main () {\nStandardSurface s;\nvec4 albedoMap = texture(cc_gbuffer_albedoMap,v_uv);\nvec4 positionMap = texture(cc_gbuffer_positionMap,v_uv);\nvec4 normalMap = texture(cc_gbuffer_normalMap,v_uv);\nvec4 emissiveMap = texture(cc_gbuffer_emissiveMap,v_uv);\ns.albedo = albedoMap;\ns.position = positionMap.xyz;\ns.roughness = positionMap.w;\ns.normal = normalMap.xyz;\ns.metallic = normalMap.w;\ns.emissive = emissiveMap.xyz;\ns.occlusion = emissiveMap.w;\nfloat fogFactor;\n#if CC_USE_FOG == 0\nfogFactor = LinearFog(vec4(s.position, 1));\n#elif CC_USE_FOG == 1\nfogFactor = ExpFog(vec4(s.position, 1));\n#elif CC_USE_FOG == 2\nfogFactor = ExpSquaredFog(vec4(s.position, 1));\n#elif CC_USE_FOG == 3\nfogFactor = LayeredFog(vec4(s.position, 1));\n#else\nfogFactor = 1.0;\n#endif\nvec4 shadowPos;\nshadowPos = cc_matLightViewProj * vec4(s.position, 1);\nvec4 color = CCStandardShadingBase(s, shadowPos) +\nCCStandardShadingAdditive(s, shadowPos);\ncolor = vec4(mix(CC_FORWARD_ADD > 0 ? vec3(0.0) : cc_fogColor.rgb, color.rgb, fogFactor), color.a);\nfragColor = CCFragOutput(color);\n}"
            }], [{
              "vert": "\nprecision highp float;\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec2 a_texCoord;\nin vec4 a_tangent;\n#if CC_USE_MORPH\nin float a_vertexId;\nint getVertexId() {\nreturn int(a_vertexId);\n}\nlayout(std140) uniform CCMorph {\nvec4 cc_displacementWeights[15];\nvec4 cc_displacementTextureInfo;\n};\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int pixelIndex) {\nivec2 texSize = textureSize(tex, 0);\nreturn texelFetch(tex, ivec2(pixelIndex % texSize.x, pixelIndex / texSize.x), 0);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture(tex, x)),\ndecode32(texture(tex, y)),\ndecode32(texture(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nuniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nuniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nuniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nattr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nattr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nattr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_joints;\nin vec4 a_weights;\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nin highp vec4 a_jointAnimInfo;\n#endif\nlayout(std140) uniform CCSkinningTexture {\nhighp vec4 cc_jointTextureInfo;\n};\nlayout(std140) uniform CCSkinningAnimation {\nhighp vec4 cc_jointAnimInfo;\n};\nuniform highp sampler2D cc_jointTexture;\n#else\nlayout(std140) uniform CCSkinning {\nhighp vec4 cc_joints[30 * 3];\n};\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\n#if USE_INSTANCING\nhighp float j = 3.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n#else\nhighp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n#endif\nhighp float invSize = cc_jointTextureInfo.w;\nhighp float y = floor(j * invSize);\nhighp float x = floor(j - y * cc_jointTextureInfo.x);\ny = (y + 0.5) * invSize;\nvec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\n#if USE_INSTANCING\nhighp float j = 12.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n#else\nhighp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n#endif\nhighp float invSize = cc_jointTextureInfo.w;\nhighp float y = floor(j * invSize);\nhighp float x = floor(j - y * cc_jointTextureInfo.x);\ny = (y + 0.5) * invSize;\nvec4 v1 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\nmat4 m = skinMatrix();\nattr.position = m * attr.position;\nattr.normal = (m * vec4(attr.normal, 0.0)).xyz;\nattr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nlayout(std140) uniform CCGlobal {\nhighp   vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp   mat4 cc_matView;\nhighp   mat4 cc_matViewInv;\nhighp   mat4 cc_matProj;\nhighp   mat4 cc_matProjInv;\nhighp   mat4 cc_matViewProj;\nhighp   mat4 cc_matViewProjInv;\nhighp   vec4 cc_cameraPos;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\n};\n#if USE_INSTANCING\nin vec4 a_matWorld0;\nin vec4 a_matWorld1;\nin vec4 a_matWorld2;\n#if USE_LIGHTMAP\nin vec4 a_lightingMapUVParam;\n#endif\n#elif USE_BATCHING\nin float a_dyn_batch_id;\nlayout(std140) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#else\nlayout(std140) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\n};\n#endif\nlayout(std140) uniform CCShadow {\nhighp mat4 cc_matLightPlaneProj;\nhighp mat4 cc_matLightView;\nhighp mat4 cc_matLightViewProj;\nlowp  vec4 cc_shadowNFLSInfo;\nlowp  vec4 cc_shadowWHPBInfo;\nlowp  vec4 cc_shadowLPNNInfo;\nlowp  vec4 cc_shadowColor;\n};\nvec4 vert () {\nvec4 position;\nposition = vec4(a_position, 1.0);\n#if CC_USE_MORPH\napplyMorph(position);\n#endif\n#if CC_USE_SKINNING\nCCSkin(position);\n#endif\nmat4 matWorld;\n#if USE_INSTANCING\nmatWorld = mat4(\nvec4(a_matWorld0.xyz, 0.0),\nvec4(a_matWorld1.xyz, 0.0),\nvec4(a_matWorld2.xyz, 0.0),\nvec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n);\n#elif USE_BATCHING\nmatWorld = cc_matWorlds[int(a_dyn_batch_id)];\n#else\nmatWorld = cc_matWorld;\n#endif\nposition = cc_matProj * (cc_matView * cc_matLightPlaneProj * matWorld) * position;\nposition.z -= 0.0001;\nreturn position;\n}\nvoid main() { gl_Position = vert(); }",
              "frag": "\nprecision mediump float;\nlayout(std140) uniform CCShadow {\nhighp mat4 cc_matLightPlaneProj;\nhighp mat4 cc_matLightView;\nhighp mat4 cc_matLightViewProj;\nlowp  vec4 cc_shadowNFLSInfo;\nlowp  vec4 cc_shadowWHPBInfo;\nlowp  vec4 cc_shadowLPNNInfo;\nlowp  vec4 cc_shadowColor;\n};\nlayout(std140) uniform CCGlobal {\nhighp   vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp   mat4 cc_matView;\nhighp   mat4 cc_matViewInv;\nhighp   mat4 cc_matProj;\nhighp   mat4 cc_matProjInv;\nhighp   mat4 cc_matViewProj;\nhighp   mat4 cc_matViewProjInv;\nhighp   vec4 cc_cameraPos;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\n};\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n#if CC_USE_HDR\ncolor.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n#endif\nreturn color;\n}\nvec4 frag () {\nreturn CCFragOutput(cc_shadowColor);\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }"
            }], [{
              "vert": "\nprecision highp float;\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec2 a_texCoord;\nin vec4 a_tangent;\n#if CC_USE_MORPH\nin float a_vertexId;\nint getVertexId() {\nreturn int(a_vertexId);\n}\nlayout(std140) uniform CCMorph {\nvec4 cc_displacementWeights[15];\nvec4 cc_displacementTextureInfo;\n};\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int pixelIndex) {\nivec2 texSize = textureSize(tex, 0);\nreturn texelFetch(tex, ivec2(pixelIndex % texSize.x, pixelIndex / texSize.x), 0);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture(tex, x)),\ndecode32(texture(tex, y)),\ndecode32(texture(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nuniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nuniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nuniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nattr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nattr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nattr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_joints;\nin vec4 a_weights;\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nin highp vec4 a_jointAnimInfo;\n#endif\nlayout(std140) uniform CCSkinningTexture {\nhighp vec4 cc_jointTextureInfo;\n};\nlayout(std140) uniform CCSkinningAnimation {\nhighp vec4 cc_jointAnimInfo;\n};\nuniform highp sampler2D cc_jointTexture;\n#else\nlayout(std140) uniform CCSkinning {\nhighp vec4 cc_joints[30 * 3];\n};\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\n#if USE_INSTANCING\nhighp float j = 3.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n#else\nhighp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n#endif\nhighp float invSize = cc_jointTextureInfo.w;\nhighp float y = floor(j * invSize);\nhighp float x = floor(j - y * cc_jointTextureInfo.x);\ny = (y + 0.5) * invSize;\nvec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\n#if USE_INSTANCING\nhighp float j = 12.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n#else\nhighp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n#endif\nhighp float invSize = cc_jointTextureInfo.w;\nhighp float y = floor(j * invSize);\nhighp float x = floor(j - y * cc_jointTextureInfo.x);\ny = (y + 0.5) * invSize;\nvec4 v1 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\nmat4 m = skinMatrix();\nattr.position = m * attr.position;\nattr.normal = (m * vec4(attr.normal, 0.0)).xyz;\nattr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nlayout(std140) uniform CCGlobal {\nhighp   vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp   mat4 cc_matView;\nhighp   mat4 cc_matViewInv;\nhighp   mat4 cc_matProj;\nhighp   mat4 cc_matProjInv;\nhighp   mat4 cc_matViewProj;\nhighp   mat4 cc_matViewProjInv;\nhighp   vec4 cc_cameraPos;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\n};\nout vec2 v_uv;\nvoid main () {\nStandardVertInput In;\nIn.position = vec4(a_position, 1.0);\nIn.normal = a_normal;\nIn.tangent = a_tangent;\n#if CC_USE_MORPH\napplyMorph(In);\n#endif\n#if CC_USE_SKINNING\nCCSkin(In);\n#endif\nIn.position.xy = cc_cameraPos.w == 0.0 ? vec2(In.position.xy.x, -In.position.xy.y) : In.position.xy;\ngl_Position = In.position;\ngl_Position.y = gl_Position.y;\nv_uv = a_texCoord;\n}",
              "frag": "\nprecision highp float;\nlayout(std140) uniform CCGlobal {\nhighp   vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp   mat4 cc_matView;\nhighp   mat4 cc_matViewInv;\nhighp   mat4 cc_matProj;\nhighp   mat4 cc_matProjInv;\nhighp   mat4 cc_matViewProj;\nhighp   mat4 cc_matViewProjInv;\nhighp   vec4 cc_cameraPos;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\n};\nin vec2 v_uv;\nuniform sampler2D cc_lighting_resultMap;\nlayout(location = 0) out vec4 fragColor;\nvoid texcoords(vec2 fragCoord, vec2 resolution,\nout vec2 v_rgbNW, out vec2 v_rgbNE,\nout vec2 v_rgbSW, out vec2 v_rgbSE,\nout vec2 v_rgbM) {\nvec2 inverseVP = 1.0 / resolution.xy;\nv_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\nv_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\nv_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\nv_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\nv_rgbM = vec2(fragCoord * inverseVP);\n}\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 resolution,\nvec2 v_rgbNW, vec2 v_rgbNE,\nvec2 v_rgbSW, vec2 v_rgbSE,\nvec2 v_rgbM) {\nvec4 color;\nmediump vec2 inverseVP = vec2(1.0 / resolution.x, 1.0 / resolution.y);\nvec3 rgbNW = texture(tex, v_rgbNW).xyz;\nvec3 rgbNE = texture(tex, v_rgbNE).xyz;\nvec3 rgbSW = texture(tex, v_rgbSW).xyz;\nvec3 rgbSE = texture(tex, v_rgbSE).xyz;\nvec4 texColor = texture(tex, v_rgbM);\nvec3 rgbM  = texColor.xyz;\nvec3 luma = vec3(0.299, 0.587, 0.114);\nfloat lumaNW = dot(rgbNW, luma);\nfloat lumaNE = dot(rgbNE, luma);\nfloat lumaSW = dot(rgbSW, luma);\nfloat lumaSE = dot(rgbSE, luma);\nfloat lumaM  = dot(rgbM,  luma);\nfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\nfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\nmediump vec2 dir;\ndir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\ndir.y =  ((lumaNW + lumaSW) - (lumaNE + lumaSE));\nfloat dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n(0.25 * (1.0 / 8.0)), (1.0/ 128.0));\nfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\ndir = min(vec2(8.0, 8.0),\nmax(vec2(-8.0, -8.0),\ndir * rcpDirMin)) * inverseVP;\nvec3 rgbA = 0.5 * (\ntexture(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\ntexture(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\nvec3 rgbB = rgbA * 0.5 + 0.25 * (\ntexture(tex, fragCoord * inverseVP + dir * -0.5).xyz +\ntexture(tex, fragCoord * inverseVP + dir * 0.5).xyz);\nfloat lumaB = dot(rgbB, luma);\nif ((lumaB < lumaMin) || (lumaB > lumaMax))\ncolor = vec4(rgbA, texColor.a);\nelse\ncolor = vec4(rgbB, texColor.a);\nreturn color;\n}\nvoid main () {\nmediump vec2 v_rgbNW;\nmediump vec2 v_rgbNE;\nmediump vec2 v_rgbSW;\nmediump vec2 v_rgbSE;\nmediump vec2 v_rgbM;\nvec2 resolution = cc_screenSize.xy;\nvec2 fragCoord = v_uv * resolution;\ntexcoords(fragCoord, resolution, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\nfragColor = fxaa(cc_lighting_resultMap, fragCoord, resolution, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}"
            }], [{
              "vert": "\nprecision highp float;\nlayout(std140) uniform CCGlobal {\nhighp   vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp   mat4 cc_matView;\nhighp   mat4 cc_matViewInv;\nhighp   mat4 cc_matProj;\nhighp   mat4 cc_matProjInv;\nhighp   mat4 cc_matViewProj;\nhighp   mat4 cc_matViewProjInv;\nhighp   vec4 cc_cameraPos;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\n};\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec2 a_texCoord;\nin vec4 a_tangent;\nout mediump vec4 viewDir;\nvec4 vert () {\nviewDir = vec4(a_position, 1.0);\nmat4 matViewRotOnly = mat4(mat3(cc_matView));\nmat4 matProj = cc_matProj;\nif (matProj[3].w > 0.0) {\nvec2 scale = vec2(48.0, 24.0);\nmatProj[0].xy *= scale;\nmatProj[1].xy *= scale;\nmatProj[2].zw = vec2(-1.0);\nmatProj[3].zw = vec2(0.0);\n}\nvec4 pos = matProj * matViewRotOnly * viewDir;\npos.z = 0.99999 * pos.w;\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }",
              "frag": "\nprecision mediump float;\nlayout(std140) uniform CCGlobal {\nhighp   vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp   mat4 cc_matView;\nhighp   mat4 cc_matViewInv;\nhighp   mat4 cc_matProj;\nhighp   mat4 cc_matProjInv;\nhighp   mat4 cc_matViewProj;\nhighp   mat4 cc_matViewProjInv;\nhighp   vec4 cc_cameraPos;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\n};\nuniform samplerCube cc_environment;\nvec3 unpackRGBE (vec4 rgbe) {\nreturn rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nvec3 ACESToneMap (vec3 color) {\ncolor = min(color, vec3(8.0));\nconst float A = 2.51;\nconst float B = 0.03;\nconst float C = 2.43;\nconst float D = 0.59;\nconst float E = 0.14;\nreturn (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n#if !CC_USE_HDR\ncolor.rgb = sqrt(ACESToneMap(color.rgb));\n#endif\nreturn color;\n}\nin mediump vec4 viewDir;\nvec4 frag () {\n#if USE_RGBE_CUBEMAP\nvec3 c = unpackRGBE(texture(cc_environment, viewDir.xyz));\n#else\nvec3 c = SRGBToLinear(texture(cc_environment, viewDir.xyz).rgb);\n#endif\nreturn CCFragOutput(vec4(c * cc_ambientSky.w, 1.0));\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }"
            }], [{
              "vert": "\nprecision mediump float;\nlayout(std140) uniform CCGlobal {\nhighp   vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp   mat4 cc_matView;\nhighp   mat4 cc_matViewInv;\nhighp   mat4 cc_matProj;\nhighp   mat4 cc_matProjInv;\nhighp   mat4 cc_matViewProj;\nhighp   mat4 cc_matViewProjInv;\nhighp   vec4 cc_cameraPos;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\n};\nin vec3 a_position;\nin vec4 a_color;\nout vec2 v_uv;\nlayout(std140) uniform Constants {\nvec4 offset;\n};\nlayout(std140) uniform PerFrameInfo {\nvec4 digits[8 * 10 / 4];\n};\nfloat getComponent(vec4 v, float i) {\nif (i < 1.0) { return v.x; }\nelse if (i < 2.0) { return v.y; }\nelse if (i < 3.0) { return v.z; }\nelse { return v.w; }\n}\nvec4 vert () {\nvec4 position = cc_matViewProj * vec4(a_position, 1.0);\nposition.xy += offset.xy;\nv_uv = a_color.xy;\nif (a_color.z >= 0.0) {\nfloat n = getComponent(digits[int(a_color.z)], a_color.w);\nv_uv += vec2(offset.z * n, 0.0);\n}\nreturn position;\n}\nvoid main() { gl_Position = vert(); }",
              "frag": "\nprecision mediump float;\nlayout(std140) uniform CCGlobal {\nhighp   vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp   mat4 cc_matView;\nhighp   mat4 cc_matViewInv;\nhighp   mat4 cc_matProj;\nhighp   mat4 cc_matProjInv;\nhighp   mat4 cc_matViewProj;\nhighp   mat4 cc_matViewProjInv;\nhighp   vec4 cc_cameraPos;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\n};\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n#if CC_USE_HDR\ncolor.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n#endif\nreturn color;\n}\nin vec2 v_uv;\nuniform sampler2D mainTexture;\nvec4 frag () {\nreturn CCFragOutput(texture(mainTexture, v_uv));\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }"
            }], [{
              "vert": "\nprecision mediump float;\nin vec2 a_position;\nin vec2 a_texCoord;\nout vec2 v_uv;\nout float v_percent;\nlayout(std140) uniform Constant {\nvec4 u_buffer0;\nvec4 u_buffer1;\nmat4 u_projection;\n};\nvec4 vert () {\nvec2 worldPos = a_position * u_buffer1.xy + u_buffer1.zw;\nvec2 clipSpace = worldPos / u_buffer0.xy * 2.0 - 1.0;\nvec4 screenPos = u_projection * vec4(clipSpace, 0.0, 1.0);\nv_uv = a_texCoord;\nv_percent = u_buffer0.z;\nreturn screenPos;\n}\nvoid main() { gl_Position = vert(); }",
              "frag": "\nprecision mediump float;\nin vec2 v_uv;\nin float v_percent;\nuniform sampler2D mainTexture;\nvec4 frag () {\nvec4 color = texture(mainTexture, v_uv);\nfloat precent = clamp(v_percent, 0.0, 1.0);\ncolor.xyz *= precent;\nreturn color;\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }"
            }]];

            var assembly = function () {
              {
                return {
                  glsl1: glsl1,
                  glsl3: glsl3
                };
              }
            }();

            var BuiltinResMgr = function () {
              function BuiltinResMgr() {
                this._device = null;
                this._resources = {};
              }

              var _proto = BuiltinResMgr.prototype;

              _proto.initBuiltinRes = function initBuiltinRes(device) {
                var _this = this;

                this._device = device;
                var resources = this._resources;
                var canvas = document.createElement('canvas');
                var context = canvas.getContext('2d');
                var imgAsset = new ImageAsset(canvas);
                var l = canvas.width = canvas.height = 2;
                context.fillStyle = '#000';
                context.fillRect(0, 0, l, l);
                var blackTexture = new Texture2D();
                blackTexture._uuid = 'black-texture';
                blackTexture.image = imgAsset;
                resources[blackTexture._uuid] = blackTexture;
                context.fillStyle = 'rgba(0,0,0,0)';
                context.fillRect(0, 0, l, l);
                var emptyTexture = new Texture2D();
                emptyTexture._uuid = 'empty-texture';
                emptyTexture.image = imgAsset;
                resources[emptyTexture._uuid] = emptyTexture;
                var blackCubeTexture = new TextureCube();
                blackCubeTexture._uuid = 'black-cube-texture';
                blackCubeTexture.setMipFilter(TextureCube.Filter.NEAREST);
                blackCubeTexture.image = {
                  front: new ImageAsset(canvas),
                  back: new ImageAsset(canvas),
                  left: new ImageAsset(canvas),
                  right: new ImageAsset(canvas),
                  top: new ImageAsset(canvas),
                  bottom: new ImageAsset(canvas)
                };
                resources[blackCubeTexture._uuid] = blackCubeTexture;
                context.fillStyle = '#777';
                context.fillRect(0, 0, l, l);
                var greyTexture = new Texture2D();
                greyTexture._uuid = 'grey-texture';
                greyTexture.image = imgAsset;
                resources[greyTexture._uuid] = greyTexture;
                context.fillStyle = '#fff';
                context.fillRect(0, 0, l, l);
                var whiteTexture = new Texture2D();
                whiteTexture._uuid = 'white-texture';
                whiteTexture.image = imgAsset;
                resources[whiteTexture._uuid] = whiteTexture;
                var whiteCubeTexture = new TextureCube();
                whiteCubeTexture._uuid = 'white-cube-texture';
                whiteCubeTexture.setMipFilter(TextureCube.Filter.NEAREST);
                whiteCubeTexture.image = {
                  front: new ImageAsset(canvas),
                  back: new ImageAsset(canvas),
                  left: new ImageAsset(canvas),
                  right: new ImageAsset(canvas),
                  top: new ImageAsset(canvas),
                  bottom: new ImageAsset(canvas)
                };
                resources[whiteCubeTexture._uuid] = whiteCubeTexture;
                context.fillStyle = '#7f7fff';
                context.fillRect(0, 0, l, l);
                var normalTexture = new Texture2D();
                normalTexture._uuid = 'normal-texture';
                normalTexture.image = imgAsset;
                resources[normalTexture._uuid] = normalTexture;
                canvas.width = canvas.height = 16;
                context.fillStyle = '#ddd';
                context.fillRect(0, 0, 16, 16);
                context.fillStyle = '#555';
                context.fillRect(0, 0, 8, 8);
                context.fillStyle = '#555';
                context.fillRect(8, 8, 8, 8);
                var defaultTexture = new Texture2D();
                defaultTexture._uuid = 'default-texture';
                defaultTexture.image = imgAsset;
                resources[defaultTexture._uuid] = defaultTexture;
                var defaultCubeTexture = new TextureCube();
                defaultCubeTexture.setMipFilter(TextureCube.Filter.NEAREST);
                defaultCubeTexture._uuid = 'default-cube-texture';
                defaultCubeTexture.image = {
                  front: new ImageAsset(canvas),
                  back: new ImageAsset(canvas),
                  left: new ImageAsset(canvas),
                  right: new ImageAsset(canvas),
                  top: new ImageAsset(canvas),
                  bottom: new ImageAsset(canvas)
                };
                resources[defaultCubeTexture._uuid] = defaultCubeTexture;

                if (legacyCC.SpriteFrame) {
                  var spriteFrame = new legacyCC.SpriteFrame();
                  var texture = imgAsset._texture;
                  spriteFrame.texture = texture;
                  spriteFrame._uuid = 'default-spriteframe';
                  resources[spriteFrame._uuid] = spriteFrame;
                }

                var shaderVersionKey = getDeviceShaderVersion(device);

                if (!shaderVersionKey) {
                  return Promise.reject(Error('Failed to initialize builtin shaders: unknown device.'));
                }

                var shaderSources = assembly[shaderVersionKey];

                if (!shaderSources) {
                  return Promise.reject(Error("Current device is requiring builtin shaders of version " + shaderVersionKey + " " + "but shaders of that version are not assembled in this build."));
                }

                return Promise.resolve().then(function () {
                  effects.forEach(function (e, effectIndex) {
                    var effect = Object.assign(new legacyCC.EffectAsset(), e);
                    effect.shaders.forEach(function (shaderInfo, shaderIndex) {
                      var shaderSource = shaderSources[effectIndex][shaderIndex];

                      if (shaderSource) {
                        shaderInfo[shaderVersionKey] = shaderSource;
                      }
                    });
                    effect.hideInEditor = true;
                    effect.onLoaded();
                  });

                  _this._initMaterials();
                });
              };

              _proto.get = function get(uuid) {
                return this._resources[uuid];
              };

              _proto._initMaterials = function _initMaterials() {
                var resources = this._resources;
                var materialsToBeCompiled = [];
                var standardMtl = new legacyCC.Material();
                standardMtl._uuid = 'standard-material';
                standardMtl.initialize({
                  effectName: 'standard'
                });
                resources[standardMtl._uuid] = standardMtl;
                materialsToBeCompiled.push(standardMtl);
                var missingEfxMtl = new legacyCC.Material();
                missingEfxMtl._uuid = 'missing-effect-material';
                missingEfxMtl.initialize({
                  effectName: 'unlit',
                  defines: {
                    USE_COLOR: true
                  }
                });
                missingEfxMtl.setProperty('mainColor', legacyCC.color('#ffff00'));
                resources[missingEfxMtl._uuid] = missingEfxMtl;
                materialsToBeCompiled.push(missingEfxMtl);
                var missingMtl = new legacyCC.Material();
                missingMtl._uuid = 'missing-material';
                missingMtl.initialize({
                  effectName: 'unlit',
                  defines: {
                    USE_COLOR: true
                  }
                });
                missingMtl.setProperty('mainColor', legacyCC.color('#ff00ff'));
                resources[missingMtl._uuid] = missingMtl;
                materialsToBeCompiled.push(missingMtl);
                var clearStencilMtl = new legacyCC.Material();
                clearStencilMtl._uuid = 'default-clear-stencil';
                clearStencilMtl.initialize({
                  defines: {
                    USE_TEXTURE: false
                  },
                  effectName: 'clear-stencil'
                });
                resources[clearStencilMtl._uuid] = clearStencilMtl;
                materialsToBeCompiled.push(clearStencilMtl);
                var spriteMtl = new legacyCC.Material();
                spriteMtl._uuid = 'ui-base-material';
                spriteMtl.initialize({
                  defines: {
                    USE_TEXTURE: false
                  },
                  effectName: 'sprite'
                });
                resources[spriteMtl._uuid] = spriteMtl;
                materialsToBeCompiled.push(spriteMtl);
                var spriteColorMtl = new legacyCC.Material();
                spriteColorMtl._uuid = 'ui-sprite-material';
                spriteColorMtl.initialize({
                  defines: {
                    USE_TEXTURE: true,
                    CC_USE_EMBEDDED_ALPHA: false,
                    IS_GRAY: false
                  },
                  effectName: 'sprite'
                });
                resources[spriteColorMtl._uuid] = spriteColorMtl;
                materialsToBeCompiled.push(spriteColorMtl);
                var alphaTestMaskMtl = new legacyCC.Material();
                alphaTestMaskMtl._uuid = 'ui-alpha-test-material';
                alphaTestMaskMtl.initialize({
                  defines: {
                    USE_TEXTURE: true,
                    USE_ALPHA_TEST: true,
                    CC_USE_EMBEDDED_ALPHA: false,
                    IS_GRAY: false
                  },
                  effectName: 'sprite'
                });
                resources[alphaTestMaskMtl._uuid] = alphaTestMaskMtl;
                materialsToBeCompiled.push(alphaTestMaskMtl);
                var spriteGrayMtl = new legacyCC.Material();
                spriteGrayMtl._uuid = 'ui-sprite-gray-material';
                spriteGrayMtl.initialize({
                  defines: {
                    USE_TEXTURE: true,
                    CC_USE_EMBEDDED_ALPHA: false,
                    IS_GRAY: true
                  },
                  effectName: 'sprite'
                });
                resources[spriteGrayMtl._uuid] = spriteGrayMtl;
                materialsToBeCompiled.push(spriteGrayMtl);
                var spriteAlphaMtl = new legacyCC.Material();
                spriteAlphaMtl._uuid = 'ui-sprite-alpha-sep-material';
                spriteAlphaMtl.initialize({
                  defines: {
                    USE_TEXTURE: true,
                    CC_USE_EMBEDDED_ALPHA: true,
                    IS_GRAY: false
                  },
                  effectName: 'sprite'
                });
                resources[spriteAlphaMtl._uuid] = spriteAlphaMtl;
                materialsToBeCompiled.push(spriteAlphaMtl);
                var spriteAlphaGrayMtl = new legacyCC.Material();
                spriteAlphaGrayMtl._uuid = 'ui-sprite-gray-alpha-sep-material';
                spriteAlphaGrayMtl.initialize({
                  defines: {
                    USE_TEXTURE: true,
                    CC_USE_EMBEDDED_ALPHA: true,
                    IS_GRAY: true
                  },
                  effectName: 'sprite'
                });
                resources[spriteAlphaGrayMtl._uuid] = spriteAlphaGrayMtl;
                materialsToBeCompiled.push(spriteAlphaGrayMtl);
                var defaultGraphicsMtl = new legacyCC.Material();
                defaultGraphicsMtl._uuid = 'ui-graphics-material';
                defaultGraphicsMtl.initialize({
                  effectName: 'graphics'
                });
                resources[defaultGraphicsMtl._uuid] = defaultGraphicsMtl;
                materialsToBeCompiled.push(defaultGraphicsMtl);
                var defaultParticleMtl = new legacyCC.Material();
                defaultParticleMtl._uuid = 'default-particle-material';
                defaultParticleMtl.initialize({
                  effectName: 'particle'
                });
                resources[defaultParticleMtl._uuid] = defaultParticleMtl;
                materialsToBeCompiled.push(defaultParticleMtl);
                var defaultParticleGPUMtl = new legacyCC.Material();
                defaultParticleGPUMtl._uuid = 'default-particle-gpu-material';
                defaultParticleGPUMtl.initialize({
                  effectName: 'particle-gpu'
                });
                resources[defaultParticleGPUMtl._uuid] = defaultParticleGPUMtl;
                materialsToBeCompiled.push(defaultParticleGPUMtl);
                var defaultTrailMtl = new legacyCC.Material();
                defaultTrailMtl._uuid = 'default-trail-material';
                defaultTrailMtl.initialize({
                  effectName: 'particle-trail'
                });
                resources[defaultTrailMtl._uuid] = defaultTrailMtl;
                materialsToBeCompiled.push(defaultTrailMtl);
                var defaultBillboardMtl = new legacyCC.Material();
                defaultBillboardMtl._uuid = 'default-billboard-material';
                defaultBillboardMtl.initialize({
                  effectName: 'billboard'
                });
                resources[defaultBillboardMtl._uuid] = defaultBillboardMtl;
                materialsToBeCompiled.push(defaultBillboardMtl);
                var spineTwoColorMtl = new legacyCC.Material();
                spineTwoColorMtl._uuid = 'default-spine-material';
                spineTwoColorMtl.initialize({
                  defines: {
                    USE_TEXTURE: true,
                    CC_USE_EMBEDDED_ALPHA: false,
                    IS_GRAY: false
                  },
                  effectName: 'spine'
                });
                resources[spineTwoColorMtl._uuid] = spineTwoColorMtl;
                materialsToBeCompiled.push(spineTwoColorMtl);
                var builtinDeferredMtl = new legacyCC.Material();
                builtinDeferredMtl._uuid = 'builtin-deferred-material';
                builtinDeferredMtl.initialize({
                  effectName: 'deferred-lighting'
                });
                resources[builtinDeferredMtl._uuid] = builtinDeferredMtl;
                materialsToBeCompiled.push(builtinDeferredMtl);
                var builtinPostProcessMtl = new legacyCC.Material();
                builtinPostProcessMtl._uuid = 'builtin-post-process-material';
                builtinPostProcessMtl.initialize({
                  effectName: 'post-process'
                });
                resources[builtinPostProcessMtl._uuid] = builtinPostProcessMtl;
                materialsToBeCompiled.push(builtinPostProcessMtl);
                legacyCC.game.on(legacyCC.Game.EVENT_GAME_INITED, function () {
                  for (var i = 0; i < materialsToBeCompiled.length; ++i) {
                    var mat = materialsToBeCompiled[i];

                    for (var j = 0; j < mat.passes.length; ++j) {
                      mat.passes[j].tryCompile();
                    }
                  }
                });
              };

              return BuiltinResMgr;
            }();

            var builtinResMgr = exports('builtinResMgr', legacyCC.builtinResMgr = new BuiltinResMgr());

            var getPhaseID = exports('getPhaseID', function () {
              var phases = new Map();
              var phaseNum = 0;
              return function (phaseName) {
                if (typeof phaseName === 'number') {
                  return phaseName;
                }

                if (!phases.has(phaseName)) {
                  phases.set(phaseName, 1 << phaseNum);
                  phaseNum++;
                }

                return phases.get(phaseName);
              };
            }());

            var _bufferInfo = new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE);

            var _bufferViewInfo = new BufferViewInfo(null);

            var _dsInfo = new DescriptorSetInfo(null);

            var BatchingSchemes;

            (function (BatchingSchemes) {
              BatchingSchemes[BatchingSchemes["INSTANCING"] = 1] = "INSTANCING";
              BatchingSchemes[BatchingSchemes["VB_MERGING"] = 2] = "VB_MERGING";
            })(BatchingSchemes || (BatchingSchemes = {}));

            var Pass = function () {
              Pass.fillPipelineInfo = function fillPipelineInfo(pass, info) {
                if (info.priority !== undefined) {
                  pass.priority = info.priority;
                }

                if (info.primitive !== undefined) {
                  pass.primitive = info.primitive;
                }

                if (info.stage !== undefined) {
                  pass.stage = info.stage;
                }

                if (info.dynamicStates !== undefined) {
                  pass.dynamicStates = info.dynamicStates;
                }

                if (info.phase !== undefined) {
                  pass.phase = getPhaseID(info.phase);
                }

                var bs = pass._bs;

                if (info.blendState) {
                  var bsInfo = info.blendState;
                  var targets = bsInfo.targets;

                  if (targets) {
                    targets.forEach(function (t, i) {
                      bs.setTarget(i, t);
                    });
                  }

                  if (bsInfo.isA2C !== undefined) {
                    bs.isA2C = bsInfo.isA2C;
                  }

                  if (bsInfo.isIndepend !== undefined) {
                    bs.isIndepend = bsInfo.isIndepend;
                  }

                  if (bsInfo.blendColor !== undefined) {
                    bs.blendColor = bsInfo.blendColor;
                  }
                }

                pass._rs.assign(info.rasterizerState);

                pass._dss.assign(info.depthStencilState);
              };

              Pass.getPassHash = function getPassHash(pass, hShader) {
                var res = hShader + "," + pass.primitive + "," + pass.dynamicStates;
                res += serializeBlendState(pass._bs);
                res += serializeDepthStencilState(pass._dss);
                res += serializeRasterizerState(pass._rs);
                return murmurhash2_32_gc(res, 666);
              };

              function Pass(root) {
                this._rootBuffer = null;
                this._rootBufferDirty = false;
                this._buffers = [];
                this._descriptorSet = null;
                this._priority = RenderPriority.DEFAULT;
                this._hash = 0;
                this._pipelineLayout = null;
                this._primitiveMode = PrimitiveMode.TRIANGLE_LIST;
                this._dynamicStates = DynamicStateFlagBit.NONE;
                this._stage = RenderPassStage.DEFAULT;
                this._phase = getPhaseID('default');
                this._batchingSchemes = 0;
                this._passIndex = 0;
                this._propertyIndex = 0;
                this._programName = '';
                this._dynamics = {};
                this._propertyHandleMap = {};
                this._rootBlock = null;
                this._blocks = [];
                this._shaderInfo = null;
                this._defines = {};
                this._properties = {};
                this._root = void 0;
                this._device = void 0;
                this._hShaderDefault = NULL_HANDLE;
                this._handle = NULL_HANDLE;
                this._bs = new BlendState();
                this._dss = new DepthStencilState();
                this._rs = new RasterizerState();
                this._root = root;
                this._device = root.device;
              }

              var _proto = Pass.prototype;

              _proto.initialize = function initialize(info) {
                this._doInit(info);

                this.resetUBOs();
                this.resetTextures();
                this.tryCompile();
              };

              _proto.getHandle = function getHandle(name, offset, targetType) {
                if (offset === void 0) {
                  offset = 0;
                }

                if (targetType === void 0) {
                  targetType = Type.UNKNOWN;
                }

                var handle = this._propertyHandleMap[name];

                if (!handle) {
                  return 0;
                }

                if (targetType) {
                  handle = customizeType(handle, targetType);
                } else if (offset) {
                  handle = customizeType(handle, getTypeFromHandle(handle) - offset);
                }

                return handle + offset;
              };

              _proto.getBinding = function getBinding(name) {
                var handle = this.getHandle(name);

                if (!handle) {
                  return -1;
                }

                return Pass.getBindingFromHandle(handle);
              };

              _proto.setUniform = function setUniform(handle, value) {
                var binding = Pass.getBindingFromHandle(handle);
                var type = Pass.getTypeFromHandle(handle);
                var ofs = Pass.getOffsetFromHandle(handle);
                var block = this._blocks[binding];
                type2writer[type](block, value, ofs);
                this._rootBufferDirty = true;
              };

              _proto.getUniform = function getUniform(handle, out) {
                var binding = Pass.getBindingFromHandle(handle);
                var type = Pass.getTypeFromHandle(handle);
                var ofs = Pass.getOffsetFromHandle(handle);
                var block = this._blocks[binding];
                return type2reader[type](block, out, ofs);
              };

              _proto.setUniformArray = function setUniformArray(handle, value) {
                var binding = Pass.getBindingFromHandle(handle);
                var type = Pass.getTypeFromHandle(handle);
                var stride = GetTypeSize(type) >> 2;
                var block = this._blocks[binding];
                var ofs = Pass.getOffsetFromHandle(handle);

                for (var i = 0; i < value.length; i++, ofs += stride) {
                  if (value[i] === null) {
                    continue;
                  }

                  type2writer[type](block, value[i], ofs);
                }

                this._rootBufferDirty = true;
              };

              _proto.bindTexture = function bindTexture(binding, value, index) {
                this._descriptorSet.bindTexture(binding, value, index || 0);
              };

              _proto.bindSampler = function bindSampler(binding, value, index) {
                this._descriptorSet.bindSampler(binding, value, index || 0);
              };

              _proto.setDynamicState = function setDynamicState(state, value) {
                var ds = this._dynamics[state];

                if (ds && ds.value === value) {
                  return;
                }

                ds.value = value;
                ds.dirty = true;
              };

              _proto.overridePipelineStates = function overridePipelineStates(original, overrides) {
                console.warn('base pass cannot override states, please use pass instance instead.');
              };

              _proto.update = function update() {
                if (!this._descriptorSet) {
                  errorID(12006);
                  return;
                }

                if (this._rootBuffer && this._rootBufferDirty) {
                  this._rootBuffer.update(this._rootBlock);

                  this._rootBufferDirty = false;
                }

                this._descriptorSet.update();
              };

              _proto.destroy = function destroy() {
                for (var i = 0; i < this._shaderInfo.blocks.length; i++) {
                  var u = this._shaderInfo.blocks[i];

                  this._buffers[u.binding].destroy();
                }

                this._buffers = [];

                if (this._rootBuffer) {
                  this._rootBuffer.destroy();

                  this._rootBuffer = null;
                }

                this._descriptorSet = null;

                this._rs.destroy();

                this._dss.destroy();

                this._bs.destroy();

                if (this._handle) {
                  DSPool.free(PassPool.get(this._handle, PassView.DESCRIPTOR_SET));
                  PassPool.free(this._handle);
                  this._handle = NULL_HANDLE;
                }
              };

              _proto.resetUniform = function resetUniform(name) {
                var handle = this.getHandle(name);

                if (!handle) {
                  return;
                }

                var type = Pass.getTypeFromHandle(handle);
                var binding = Pass.getBindingFromHandle(handle);
                var ofs = Pass.getOffsetFromHandle(handle);
                var block = this._blocks[binding];
                var info = this._properties[name];
                var value = info && info.value || getDefaultFromType(type);
                type2writer[type](block, value, ofs);
                this._rootBufferDirty = true;
              };

              _proto.resetTexture = function resetTexture(name, index) {
                var handle = this.getHandle(name);

                if (!handle) {
                  return;
                }

                var type = Pass.getTypeFromHandle(handle);
                var binding = Pass.getBindingFromHandle(handle);
                var info = this._properties[name];
                var value = info && info.value;
                var texName = value ? value + "-texture" : getDefaultFromType(type);
                var textureBase = builtinResMgr.get(texName);
                var texture = textureBase && textureBase.getGFXTexture();
                var samplerHash = info && info.samplerHash !== undefined ? info.samplerHash : textureBase && textureBase.getSamplerHash();
                var sampler = samplerLib.getSampler(this._device, samplerHash);

                this._descriptorSet.bindSampler(binding, sampler, index);

                this._descriptorSet.bindTexture(binding, texture, index);
              };

              _proto.resetUBOs = function resetUBOs() {
                for (var i = 0; i < this._shaderInfo.blocks.length; i++) {
                  var u = this._shaderInfo.blocks[i];
                  var block = this._blocks[u.binding];
                  var ofs = 0;

                  for (var j = 0; j < u.members.length; j++) {
                    var cur = u.members[j];
                    var info = this._properties[cur.name];
                    var givenDefault = info && info.value;
                    var value = givenDefault || getDefaultFromType(cur.type);
                    var size = (GetTypeSize(cur.type) >> 2) * cur.count;

                    for (var k = 0; k + value.length <= size; k += value.length) {
                      block.set(value, ofs + k);
                    }

                    ofs += size;
                  }
                }

                this._rootBufferDirty = true;
              };

              _proto.resetTextures = function resetTextures() {
                for (var i = 0; i < this._shaderInfo.samplerTextures.length; i++) {
                  var u = this._shaderInfo.samplerTextures[i];

                  for (var j = 0; j < u.count; j++) {
                    this.resetTexture(u.name, j);
                  }
                }
              };

              _proto.tryCompile = function tryCompile() {
                var pipeline = this._root.pipeline;

                if (!pipeline) {
                  return false;
                }

                this._syncBatchingScheme();

                this._hShaderDefault = programLib.getGFXShader(this._device, this._programName, this._defines, pipeline);

                if (!this._hShaderDefault) {
                  console.warn("create shader " + this._programName + " failed");
                  return false;
                }

                this.pipelineLayoutHandle = programLib.getTemplateInfo(this._programName).hPipelineLayout;
                this.hash = Pass.getPassHash(this, this._hShaderDefault);
                return true;
              };

              _proto.getShaderVariant = function getShaderVariant(patches) {
                if (patches === void 0) {
                  patches = null;
                }

                if (!this._hShaderDefault && !this.tryCompile()) {
                  console.warn('pass resources incomplete');
                  return NULL_HANDLE;
                }

                if (!patches) {
                  return this._hShaderDefault;
                }

                var pipeline = this._root.pipeline;

                for (var _i = 0; _i < patches.length; _i++) {
                  var patch = patches[_i];
                  this._defines[patch.name] = patch.value;
                }

                var hShader = programLib.getGFXShader(this._device, this._programName, this._defines, pipeline);

                for (var _i2 = 0; _i2 < patches.length; _i2++) {
                  var _patch = patches[_i2];
                  delete this._defines[_patch.name];
                }

                return hShader;
              };

              _proto.beginChangeStatesSilently = function beginChangeStatesSilently() {};

              _proto.endChangeStatesSilently = function endChangeStatesSilently() {};

              _proto._doInit = function _doInit(info, copyDefines) {
                if (copyDefines === void 0) {
                  copyDefines = false;
                }

                this._handle = PassPool.alloc();
                this.priority = RenderPriority.DEFAULT;
                this.stage = RenderPassStage.DEFAULT;
                this.phase = getPhaseID('default');
                this.primitive = PrimitiveMode.TRIANGLE_LIST;
                this.rasterizerState = this._rs;
                this.depthStencilState = this._dss;
                this.blendState = this._bs;
                this._passIndex = info.passIndex;
                this._propertyIndex = info.propertyIndex !== undefined ? info.propertyIndex : info.passIndex;
                this._programName = info.program;
                this._defines = copyDefines ? _extends({}, info.defines) : info.defines;
                this._shaderInfo = programLib.getTemplate(info.program);
                this._properties = info.properties || this._properties;
                var device = this._device;
                Pass.fillPipelineInfo(this, info);

                if (info.stateOverrides) {
                  Pass.fillPipelineInfo(this, info.stateOverrides);
                }

                _dsInfo.layout = programLib.getDescriptorSetLayout(this._device, info.program);
                this.descriptorSetHandle = DSPool.alloc(this._device, _dsInfo);
                var blocks = this._shaderInfo.blocks;
                var tmplInfo = programLib.getTemplateInfo(info.program);
                var blockSizes = tmplInfo.blockSizes,
                    handleMap = tmplInfo.handleMap;
                var alignment = device.capabilities.uboOffsetAlignment;
                var startOffsets = [];
                var lastSize = 0;
                var lastOffset = 0;

                for (var i = 0; i < blocks.length; i++) {
                  var size = blockSizes[i];
                  startOffsets.push(lastOffset);
                  lastOffset += Math.ceil(size / alignment) * alignment;
                  lastSize = size;
                }

                var totalSize = startOffsets[startOffsets.length - 1] + lastSize;

                if (totalSize) {
                  _bufferInfo.size = Math.ceil(totalSize / 16) * 16;
                  this._rootBuffer = device.createBuffer(_bufferInfo);
                  this._rootBlock = new ArrayBuffer(totalSize);
                }

                for (var _i3 = 0, count = 0; _i3 < blocks.length; _i3++) {
                  var binding = blocks[_i3].binding;
                  var _size = blockSizes[_i3];
                  _bufferViewInfo.buffer = this._rootBuffer;
                  _bufferViewInfo.offset = startOffsets[count++];
                  _bufferViewInfo.range = Math.ceil(_size / 16) * 16;
                  var bufferView = this._buffers[binding] = device.createBuffer(_bufferViewInfo);
                  this._blocks[binding] = new Float32Array(this._rootBlock, _bufferViewInfo.offset, _size / Float32Array.BYTES_PER_ELEMENT);

                  this._descriptorSet.bindBuffer(binding, bufferView);
                }

                var directHandleMap = this._propertyHandleMap = handleMap;
                var indirectHandleMap = {};

                for (var name in this._properties) {
                  var prop = this._properties[name];

                  if (!prop.handleInfo) {
                    continue;
                  }

                  indirectHandleMap[name] = this.getHandle.apply(this, prop.handleInfo);
                }

                Object.assign(directHandleMap, indirectHandleMap);
              };

              _proto._syncBatchingScheme = function _syncBatchingScheme() {
                if (this._defines.USE_INSTANCING) {
                  if (this._device.hasFeature(Feature.INSTANCED_ARRAYS)) {
                    this.batchingScheme = BatchingSchemes.INSTANCING;
                  } else {
                    this._defines.USE_INSTANCING = false;
                    this.batchingScheme = 0;
                  }
                } else if (this._defines.USE_BATCHING) {
                  this.batchingScheme = BatchingSchemes.VB_MERGING;
                } else {
                  this.batchingScheme = 0;
                }
              };

              _proto._destroyHandle = function _destroyHandle() {
                if (this._handle) {
                  PassPool.free(this._handle);
                  this._handle = NULL_HANDLE;
                }
              };

              _proto._initPassFromTarget = function _initPassFromTarget(target, dss, bs, hashFactor) {
                this._passIndex = target.passIndex;
                this._propertyIndex = target.propertyIndex;
                this._programName = target.program;
                this._defines = target.defines;
                this._shaderInfo = target._shaderInfo;
                this._properties = target._properties;
                this._hShaderDefault = target._hShaderDefault;
                this._blocks = target._blocks;
                this._dynamics = target._dynamics;
                this.priority = target.priority;
                this.stage = target.stage;
                this.phase = target.phase;
                this.batchingScheme = target.batchingScheme;
                this.primitive = target.primitive;
                this.dynamicStates = target.dynamicStates;
                this.hash = target.hash ^ hashFactor;
                this.rasterizerState = target.rasterizerState;
                this.blendState = bs;
                this.depthStencilState = dss;
                this.pipelineLayoutHandle = programLib.getTemplateInfo(this._programName).hPipelineLayout;
                this.descriptorSetHandle = PassPool.get(target.handle, PassView.DESCRIPTOR_SET);
              };

              _createClass(Pass, [{
                key: "root",
                get: function get() {
                  return this._root;
                }
              }, {
                key: "device",
                get: function get() {
                  return this._device;
                }
              }, {
                key: "shaderInfo",
                get: function get() {
                  return this._shaderInfo;
                }
              }, {
                key: "localSetLayout",
                get: function get() {
                  return programLib.getDescriptorSetLayout(this._device, this._programName, true);
                }
              }, {
                key: "program",
                get: function get() {
                  return this._programName;
                }
              }, {
                key: "properties",
                get: function get() {
                  return this._properties;
                }
              }, {
                key: "defines",
                get: function get() {
                  return this._defines;
                }
              }, {
                key: "passIndex",
                get: function get() {
                  return this._passIndex;
                }
              }, {
                key: "propertyIndex",
                get: function get() {
                  return this._propertyIndex;
                }
              }, {
                key: "dynamics",
                get: function get() {
                  return this._dynamics;
                }
              }, {
                key: "blocks",
                get: function get() {
                  return this._blocks;
                }
              }, {
                key: "rootBufferDirty",
                get: function get() {
                  return this._rootBufferDirty;
                }
              }, {
                key: "handle",
                get: function get() {
                  return this._handle;
                }
              }, {
                key: "priority",
                get: function get() {
                  return this._priority;
                },
                set: function set(val) {
                  this._priority = val;
                  PassPool.set(this._handle, PassView.PRIORITY, val);
                }
              }, {
                key: "primitive",
                get: function get() {
                  return this._primitiveMode;
                },
                set: function set(val) {
                  this._primitiveMode = val;
                  PassPool.set(this._handle, PassView.PRIMITIVE, val);
                }
              }, {
                key: "stage",
                get: function get() {
                  return this._stage;
                },
                set: function set(val) {
                  this._stage = val;
                  PassPool.set(this._handle, PassView.STAGE, val);
                }
              }, {
                key: "phase",
                get: function get() {
                  return this._phase;
                },
                set: function set(val) {
                  this._phase = val;
                  PassPool.set(this._handle, PassView.PHASE, val);
                }
              }, {
                key: "dynamicStates",
                get: function get() {
                  return this._dynamicStates;
                },
                set: function set(val) {
                  this._dynamicStates = val;
                  PassPool.set(this._handle, PassView.DYNAMIC_STATES, val);
                }
              }, {
                key: "batchingScheme",
                get: function get() {
                  return this._batchingSchemes;
                },
                set: function set(val) {
                  this._batchingSchemes = val;
                  PassPool.set(this._handle, PassView.BATCHING_SCHEME, val);
                }
              }, {
                key: "hash",
                get: function get() {
                  return this._hash;
                },
                set: function set(val) {
                  this._hash = val;
                  PassPool.set(this._handle, PassView.HASH, val);
                }
              }, {
                key: "pipelineLayoutHandle",
                set: function set(val) {
                  this._pipelineLayout = PipelineLayoutPool.get(val);
                  PassPool.set(this._handle, PassView.PIPELINE_LAYOUT, val);
                }
              }, {
                key: "pipelineLayout",
                get: function get() {
                  return this._pipelineLayout;
                }
              }, {
                key: "descriptorSetHandle",
                set: function set(val) {
                  this._descriptorSet = DSPool.get(val);
                  PassPool.set(this._handle, PassView.DESCRIPTOR_SET, val);
                }
              }, {
                key: "descriptorSet",
                get: function get() {
                  return this._descriptorSet;
                }
              }, {
                key: "rasterizerState",
                get: function get() {
                  return this._rs;
                },
                set: function set(val) {
                  this._rs = val;
                  PassPool.set(this._handle, PassView.RASTERIZER_STATE, val.handle);
                }
              }, {
                key: "depthStencilState",
                get: function get() {
                  return this._dss;
                },
                set: function set(val) {
                  this._dss = val;
                  PassPool.set(this._handle, PassView.DEPTH_STENCIL_STATE, val.handle);
                }
              }, {
                key: "blendState",
                get: function get() {
                  return this._bs;
                },
                set: function set(val) {
                  this._bs = val;
                  PassPool.set(this._handle, PassView.BLEND_STATE, val.handle);
                }
              }]);

              return Pass;
            }();
            Pass.PropertyType = PropertyType;
            Pass.getPropertyTypeFromHandle = getPropertyTypeFromHandle;
            Pass.getTypeFromHandle = getTypeFromHandle;
            Pass.getBindingFromHandle = getBindingFromHandle;
            Pass.getOffsetFromHandle = getOffsetFromHandle;

            function serializeBlendState(bs) {
              var res = ",bs," + bs.isA2C;

              for (var _iterator = _createForOfIteratorHelperLoose(bs.targets), _step; !(_step = _iterator()).done;) {
                var t = _step.value;
                res += ",bt," + t.blend + "," + t.blendEq + "," + t.blendAlphaEq + "," + t.blendColorMask;
                res += "," + t.blendSrc + "," + t.blendDst + "," + t.blendSrcAlpha + "," + t.blendDstAlpha;
              }

              return res;
            }

            function serializeRasterizerState(rs) {
              return ",rs," + rs.cullMode + "," + rs.depthBias + "," + rs.isFrontFaceCCW;
            }

            function serializeDepthStencilState(dss) {
              var res = ",dss," + dss.depthTest + "," + dss.depthWrite + "," + dss.depthFunc;
              res += "," + dss.stencilTestFront + "," + dss.stencilFuncFront + "," + dss.stencilRefFront + "," + dss.stencilReadMaskFront;
              res += "," + dss.stencilFailOpFront + "," + dss.stencilZFailOpFront + "," + dss.stencilPassOpFront + "," + dss.stencilWriteMaskFront;
              res += "," + dss.stencilTestBack + "," + dss.stencilFuncBack + "," + dss.stencilRefBack + "," + dss.stencilReadMaskBack;
              res += "," + dss.stencilFailOpBack + "," + dss.stencilZFailOpBack + "," + dss.stencilPassOpBack + "," + dss.stencilWriteMaskBack;
              return res;
            }

            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'
            }]);
            var 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;
            var 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.prototype, 'Camera.prototype', [{
              name: 'getSplitFrustum'
            }]);

            function ColorTemperatureToRGB(rgb, kelvin) {
              if (kelvin < 1000.0) {
                kelvin = 1000.0;
              } else if (kelvin > 15000.0) {
                kelvin = 15000.0;
              }

              var kSqr = kelvin * kelvin;
              var u = (0.860117757 + 1.54118254e-4 * kelvin + 1.28641212e-7 * kSqr) / (1.0 + 8.42420235e-4 * kelvin + 7.08145163e-7 * kSqr);
              var v = (0.317398726 + 4.22806245e-5 * kelvin + 4.20481691e-8 * kSqr) / (1.0 - 2.89741816e-5 * kelvin + 1.61456053e-7 * kSqr);
              var d = 2.0 * u - 8.0 * v + 4.0;
              var x = 3.0 * u / d;
              var y = 2.0 * v / d;
              var z = 1.0 - x - y;
              var X = 1.0 / y * x;
              var Z = 1.0 / y * z;
              rgb.x = 3.2404542 * X + -1.5371385 + -0.4985314 * Z;
              rgb.y = -0.9692660 * X + 1.8760108 + 0.0415560 * Z;
              rgb.z = 0.0556434 * X + -0.2040259 + 1.0572252 * Z;
            }
            var LightType;

            (function (LightType) {
              LightType[LightType["DIRECTIONAL"] = 0] = "DIRECTIONAL";
              LightType[LightType["SPHERE"] = 1] = "SPHERE";
              LightType[LightType["SPOT"] = 2] = "SPOT";
              LightType[LightType["UNKNOWN"] = 3] = "UNKNOWN";
            })(LightType || (LightType = {}));

            var nt2lm = function nt2lm(size) {
              return 4 * Math.PI * Math.PI * size * size;
            };
            var Light = function () {
              function Light() {
                this._baked = false;
                this._color = new Vec3(1, 1, 1);
                this._colorTemp = 6550.0;
                this._colorTempRGB = new Vec3(1, 1, 1);
                this._scene = null;
                this._node = null;
                this._name = null;
                this._handle = NULL_HANDLE;
              }

              var _proto = Light.prototype;

              _proto.initialize = function initialize() {
                this._handle = LightPool.alloc();
                LightPool.setVec3(this._handle, LightView.COLOR, this._color);
                LightPool.setVec3(this._handle, LightView.COLOR_TEMPERATURE_RGB, this._colorTempRGB);
                LightPool.set(this._handle, LightView.TYPE, LightType.UNKNOWN);
              };

              _proto.attachToScene = function attachToScene(scene) {
                this._scene = scene;
              };

              _proto.detachFromScene = function detachFromScene() {
                this._scene = null;
              };

              _proto.destroy = function destroy() {
                this._name = null;
                this._node = null;

                if (this._handle) {
                  LightPool.free(this._handle);
                  this._handle = NULL_HANDLE;
                }
              };

              _proto.update = function update() {};

              _createClass(Light, [{
                key: "baked",
                get: function get() {
                  return this._baked;
                },
                set: function set(val) {
                  this._baked = val;
                }
              }, {
                key: "color",
                get: function get() {
                  return this._color;
                },
                set: function set(color) {
                  this._color.set(color);

                  LightPool.setVec3(this._handle, LightView.COLOR, color);
                }
              }, {
                key: "useColorTemperature",
                get: function get() {
                  return LightPool.get(this._handle, LightView.USE_COLOR_TEMPERATURE) === 1;
                },
                set: function set(enable) {
                  LightPool.set(this._handle, LightView.USE_COLOR_TEMPERATURE, enable ? 1 : 0);
                }
              }, {
                key: "colorTemperature",
                get: function get() {
                  return this._colorTemp;
                },
                set: function set(val) {
                  this._colorTemp = val;
                  ColorTemperatureToRGB(this._colorTempRGB, this._colorTemp);
                  LightPool.setVec3(this._handle, LightView.COLOR_TEMPERATURE_RGB, this._colorTempRGB);
                }
              }, {
                key: "colorTemperatureRGB",
                get: function get() {
                  return this._colorTempRGB;
                }
              }, {
                key: "node",
                get: function get() {
                  return this._node;
                },
                set: function set(n) {
                  this._node = n;

                  if (this._node) {
                    this._node.hasChangedFlags |= TransformBit.ROTATION;
                    LightPool.set(this._handle, LightView.NODE, this._node.handle);
                  }
                }
              }, {
                key: "type",
                get: function get() {
                  return LightPool.get(this._handle, LightView.TYPE);
                }
              }, {
                key: "name",
                get: function get() {
                  return this._name;
                },
                set: function set(n) {
                  this._name = n;
                }
              }, {
                key: "scene",
                get: function get() {
                  return this._scene;
                }
              }, {
                key: "handle",
                get: function get() {
                  return this._handle;
                }
              }]);

              return Light;
            }();

            var _forward = new Vec3(0, 0, -1);

            var _v3 = new Vec3();

            var DirectionalLight = function (_Light) {
              _inheritsLoose(DirectionalLight, _Light);

              function DirectionalLight() {
                var _this;

                _this = _Light.call(this) || this;
                _this._dir = new Vec3(1.0, -1.0, -1.0);
                return _this;
              }

              var _proto = DirectionalLight.prototype;

              _proto.initialize = function initialize() {
                _Light.prototype.initialize.call(this);

                LightPool.set(this._handle, LightView.ILLUMINANCE, Ambient.SUN_ILLUM);
                LightPool.setVec3(this._handle, LightView.DIRECTION, this._dir);
                LightPool.set(this._handle, LightView.TYPE, LightType.DIRECTIONAL);
              };

              _proto.update = function update() {
                if (this._node && this._node.hasChangedFlags) {
                  this.direction = Vec3.transformQuat(_v3, _forward, this._node.worldRotation);
                }
              };

              _createClass(DirectionalLight, [{
                key: "direction",
                get: function get() {
                  return this._dir;
                },
                set: function set(dir) {
                  Vec3.normalize(this._dir, dir);
                  LightPool.setVec3(this._handle, LightView.DIRECTION, this._dir);
                }
              }, {
                key: "illuminance",
                get: function get() {
                  return LightPool.get(this._handle, LightView.ILLUMINANCE);
                },
                set: function set(illum) {
                  LightPool.set(this._handle, LightView.ILLUMINANCE, illum);
                }
              }]);

              return DirectionalLight;
            }(Light);

            function deepFlatten(strList, array) {
              for (var _iterator = _createForOfIteratorHelperLoose(array), _step; !(_step = _iterator()).done;) {
                var item = _step.value;

                if (Array.isArray(item)) {
                  deepFlatten(strList, item);
                } else {
                    strList.push(item);
                  }
              }
            }

            function flattenCodeArray(array) {
              var separator =  '';
              var strList = [];
              deepFlatten(strList, array);
              return strList.join(separator);
            }

            var Destroyed$1 = CCObject.Flags.Destroyed;
            var PersistentMask$1 = CCObject.Flags.PersistentMask;
            var DEFAULT = DELIMETER + "default";
            var IDENTIFIER_RE$1 = CCClass.IDENTIFIER_RE;
            var VAR = 'var ';
            var LOCAL_OBJ = 'o';
            var LOCAL_TEMP_OBJ = 't';
            var LOCAL_ARRAY = 'a';
            var LINE_INDEX_OF_NEW_OBJ = 0;
            var DEFAULT_MODULE_CACHE = {
              'cc.ClickEvent': false,
              'cc.PrefabInfo': false
            };
            var escapeForJS$1 = CCClass.escapeForJS;

            var Declaration = function () {
              function Declaration(varName, expression) {
                this.varName = void 0;
                this.expression = void 0;
                this.varName = varName;
                this.expression = expression;
              }

              var _proto = Declaration.prototype;

              _proto.toString = function toString() {
                return VAR + this.varName + "=" + this.expression + ";";
              };

              return Declaration;
            }();

            function mergeDeclaration(statement, expression) {
              if (expression instanceof Declaration) {
                return new Declaration(expression.varName, statement + expression.expression);
              } else {
                return statement + expression;
              }
            }

            function writeAssignment(codeArray, statement, expression) {
              if (Array.isArray(expression)) {
                expression[0] = mergeDeclaration(statement, expression[0]);
                codeArray.push(expression);
              } else {
                codeArray.push(mergeDeclaration(statement, expression) + ";");
              }
            }

            var Assignments = function () {
              function Assignments(targetExpression) {
                this._exps = void 0;
                this._targetExp = void 0;
                this._exps = [];
                this._targetExp = targetExpression;
              }

              var _proto2 = Assignments.prototype;

              _proto2.append = function append(key, expression) {
                this._exps.push([key, expression]);
              };

              _proto2.writeCode = function writeCode(codeArray) {
                var targetVar;

                if (this._exps.length > 1) {
                  codeArray.push(LOCAL_TEMP_OBJ + "=" + this._targetExp + ";");
                  targetVar = LOCAL_TEMP_OBJ;
                } else if (this._exps.length === 1) {
                  targetVar = this._targetExp;
                } else {
                  return;
                }

                for (var i = 0; i < this._exps.length; i++) {
                  var pair = this._exps[i];
                  writeAssignment(codeArray, targetVar + getPropAccessor(pair[0]) + "=", pair[1]);
                }
              };

              return Assignments;
            }();

            Assignments.pool = void 0;
            Assignments.pool = new Pool(function (obj) {
              obj._exps.length = 0;
              obj._targetExp = null;
            }, 1);

            Assignments.pool.get = function (targetExpression) {
              var cache = this._get() || new Assignments();
              cache._targetExp = targetExpression;
              return cache;
            };

            function getPropAccessor(key) {
              return IDENTIFIER_RE$1.test(key) ? "." + key : "[" + escapeForJS$1(key) + "]";
            }

            var Parser = function () {
              function Parser(obj, parent) {
                this.parent = void 0;
                this.objsToClear_iN$t = void 0;
                this.codeArray = void 0;
                this.objs = void 0;
                this.funcs = void 0;
                this.funcModuleCache = void 0;
                this.globalVariables = void 0;
                this.globalVariableId = void 0;
                this.localVariableId = void 0;
                this.result = void 0;
                this.parent = parent;
                this.objsToClear_iN$t = [];
                this.codeArray = [];
                this.objs = [];
                this.funcs = [];
                this.funcModuleCache = createMap();
                mixin(this.funcModuleCache, DEFAULT_MODULE_CACHE);
                this.globalVariables = [];
                this.globalVariableId = 0;
                this.localVariableId = 0;
                this.codeArray.push(VAR + LOCAL_OBJ + "," + LOCAL_TEMP_OBJ + ";", 'if(R){', LOCAL_OBJ + "=R;", '}else{', LOCAL_OBJ + "=R=new " + this.getFuncModule(obj.constructor, true) + "();", '}');
                obj._iN$t = {
                  globalVar: 'R'
                };
                this.objsToClear_iN$t.push(obj);
                this.enumerateObject(this.codeArray, obj);
                var globalVariablesDeclaration;

                if (this.globalVariables.length > 0) {
                  globalVariablesDeclaration = VAR + this.globalVariables.join(',') + ";";
                }

                var code = flattenCodeArray(['return (function(R){', globalVariablesDeclaration || [], this.codeArray, 'return o;', '})']);
                this.result = Function('O', 'F', code)(this.objs, this.funcs);

                for (var i = 0, len = this.objsToClear_iN$t.length; i < len; ++i) {
                  this.objsToClear_iN$t[i]._iN$t = null;
                }

                this.objsToClear_iN$t.length = 0;
              }

              var _proto3 = Parser.prototype;

              _proto3.getFuncModule = function getFuncModule(func, usedInNew) {
                var clsName = getClassName(func);

                if (clsName) {
                  var cache = this.funcModuleCache[clsName];

                  if (cache) {
                    return cache;
                  } else if (cache === undefined) {
                    var clsNameIsModule = clsName.indexOf('.') !== -1;

                    if (clsNameIsModule) {
                      try {
                        clsNameIsModule = func === Function("return " + clsName)();

                        if (clsNameIsModule) {
                          this.funcModuleCache[clsName] = clsName;
                          return clsName;
                        }
                      } catch (e) {}
                    }
                  }
                }

                var index = this.funcs.indexOf(func);

                if (index < 0) {
                  index = this.funcs.length;
                  this.funcs.push(func);
                }

                var res = "F[" + index + "]";

                if (usedInNew) {
                  res = "(" + res + ")";
                }

                this.funcModuleCache[clsName] = res;
                return res;
              };

              _proto3.getObjRef = function getObjRef(obj) {
                var index = this.objs.indexOf(obj);

                if (index < 0) {
                  index = this.objs.length;
                  this.objs.push(obj);
                }

                return "O[" + index + "]";
              };

              _proto3.setValueType = function setValueType(codeArray, defaultValue, srcValue, targetExpression) {
                var assignments = Assignments.pool.get(targetExpression);
                var fastDefinedProps = defaultValue.constructor.__props__;

                if (!fastDefinedProps) {
                  fastDefinedProps = Object.keys(defaultValue);
                }

                for (var i = 0; i < fastDefinedProps.length; i++) {
                  var propName = fastDefinedProps[i];
                  var prop = srcValue[propName];

                  if (defaultValue[propName] === prop) {
                    continue;
                  }

                  var expression = this.enumerateField(srcValue, propName, prop);
                  assignments.append(propName, expression);
                }

                assignments.writeCode(codeArray);
                Assignments.pool.put(assignments);
              };

              _proto3.enumerateCCClass = function enumerateCCClass(codeArray, obj, klass) {
                var props = klass.__values__;
                var attrs = getClassAttrs(klass);

                for (var p = 0; p < props.length; p++) {
                  var key = props[p];
                  var val = obj[key];
                  var defaultValue = attrs[key + DEFAULT];

                  if (equalsToDefault(defaultValue, val)) {
                    continue;
                  }

                  if (typeof val === 'object' && val instanceof legacyCC.ValueType) {
                    defaultValue = CCClass.getDefault(defaultValue);

                    if (defaultValue && defaultValue.constructor === val.constructor) {
                      var targetExpression = LOCAL_OBJ + getPropAccessor(key);
                      this.setValueType(codeArray, defaultValue, val, targetExpression);
                      continue;
                    }
                  }

                  this.setObjProp(codeArray, obj, key, val);
                }
              };

              _proto3.instantiateArray = function instantiateArray(value) {
                if (value.length === 0) {
                  return '[]';
                }

                var arrayVar = LOCAL_ARRAY + ++this.localVariableId;
                var declaration = new Declaration(arrayVar, "new Array(" + value.length + ")");
                var codeArray = [declaration];
                value._iN$t = {
                  globalVar: '',
                  source: codeArray
                };
                this.objsToClear_iN$t.push(value);

                for (var i = 0; i < value.length; ++i) {
                  var statement = arrayVar + "[" + i + "]=";
                  var expression = this.enumerateField(value, i, value[i]);
                  writeAssignment(codeArray, statement, expression);
                }

                return codeArray;
              };

              _proto3.instantiateTypedArray = function instantiateTypedArray(value) {
                var type = value.constructor.name;

                if (value.length === 0) {
                  return "new " + type;
                }

                var arrayVar = LOCAL_ARRAY + ++this.localVariableId;
                var declaration = new Declaration(arrayVar, "new " + type + "(" + value.length + ")");
                var codeArray = [declaration];
                value._iN$t = {
                  globalVar: '',
                  source: codeArray
                };
                this.objsToClear_iN$t.push(value);

                for (var i = 0; i < value.length; ++i) {
                  if (value[i] !== 0) {
                    var statement = arrayVar + "[" + i + "]=";
                    writeAssignment(codeArray, statement, value[i]);
                  }
                }

                return codeArray;
              };

              _proto3.enumerateField = function enumerateField(obj, key, value) {
                if (typeof value === 'object' && value) {
                  var _iN$t = value._iN$t;

                  if (_iN$t) {
                    var globalVar = _iN$t.globalVar;

                    if (!globalVar) {
                      globalVar = _iN$t.globalVar = "v" + ++this.globalVariableId;
                      this.globalVariables.push(globalVar);
                      var line = _iN$t.source[LINE_INDEX_OF_NEW_OBJ];
                      _iN$t.source[LINE_INDEX_OF_NEW_OBJ] = mergeDeclaration(globalVar + "=", line);
                    }

                    return globalVar;
                  } else if (ArrayBuffer.isView(value)) {
                    return this.instantiateTypedArray(value);
                  } else if (Array.isArray(value)) {
                    return this.instantiateArray(value);
                  } else {
                    return this.instantiateObj(value);
                  }
                } else if (typeof value === 'function') {
                  return this.getFuncModule(value);
                } else if (typeof value === 'string') {
                  return escapeForJS$1(value);
                } else {
                  if (key === '_objFlags' && obj instanceof CCObject) {
                    value &= PersistentMask$1;
                  }

                  return value;
                }
              };

              _proto3.setObjProp = function setObjProp(codeArray, obj, key, value) {
                var statement = LOCAL_OBJ + getPropAccessor(key) + "=";
                var expression = this.enumerateField(obj, key, value);
                writeAssignment(codeArray, statement, expression);
              };

              _proto3.enumerateObject = function enumerateObject(codeArray, obj) {
                var klass = obj.constructor;

                if (legacyCC.Class._isCCClass(klass)) {
                  this.enumerateCCClass(codeArray, obj, klass);
                } else {
                  for (var key in obj) {
                    if (!obj.hasOwnProperty(key) || key.charCodeAt(0) === 95 && key.charCodeAt(1) === 95 && key !== '__type__') {
                      continue;
                    }

                    var value = obj[key];

                    if (typeof value === 'object' && value && value === obj._iN$t) {
                      continue;
                    }

                    this.setObjProp(codeArray, obj, key, value);
                  }
                }
              };

              _proto3.instantiateObj = function instantiateObj(obj) {
                if (obj instanceof legacyCC.ValueType) {
                  return CCClass.getNewValueTypeCode(obj);
                }

                if (obj instanceof legacyCC.Asset) {
                  return this.getObjRef(obj);
                }

                if (obj._objFlags & Destroyed$1) {
                  return null;
                }

                var createCode;
                var ctor = obj.constructor;

                if (legacyCC.Class._isCCClass(ctor)) {
                  if (this.parent) {
                    if (this.parent instanceof legacyCC.Component) {
                      if (obj instanceof legacyCC._BaseNode || obj instanceof legacyCC.Component) {
                        return this.getObjRef(obj);
                      }
                    } else if (this.parent instanceof legacyCC._BaseNode) {
                      if (obj instanceof legacyCC._BaseNode) {
                        if (!obj.isChildOf(this.parent)) {
                          return this.getObjRef(obj);
                        }
                      } else if (obj instanceof legacyCC.Component) {
                        if (!obj.node.isChildOf(this.parent)) {
                          return this.getObjRef(obj);
                        }
                      }
                    }
                  }

                  createCode = new Declaration(LOCAL_OBJ, "new " + this.getFuncModule(ctor, true) + "()");
                } else if (ctor === Object) {
                  createCode = new Declaration(LOCAL_OBJ, '{}');
                } else if (!ctor) {
                  createCode = new Declaration(LOCAL_OBJ, 'Object.create(null)');
                } else {
                  return this.getObjRef(obj);
                }

                var codeArray = [createCode];
                obj._iN$t = {
                  globalVar: '',
                  source: codeArray
                };
                this.objsToClear_iN$t.push(obj);
                this.enumerateObject(codeArray, obj);
                return ['(function(){', codeArray, 'return o;})();'];
              };

              return Parser;
            }();

            function equalsToDefault(def, value) {
              if (typeof def === 'function') {
                try {
                  def = def();
                } catch (e) {
                  return false;
                }
              }

              if (def === value) {
                return true;
              }

              if (def && value && typeof def === 'object' && typeof value === 'object' && def.constructor === value.constructor) {
                if (def instanceof legacyCC.ValueType) {
                  if (def.equals(value)) {
                    return true;
                  }
                } else if (Array.isArray(def)) {
                  return def.length === 0 && value.length === 0;
                } else if (def.constructor === Object) {
                  return isEmptyObject(def) && isEmptyObject(value);
                }
              }

              return false;
            }
            function compile(node) {
              var root = node instanceof legacyCC._BaseNode && node;
              var parser = new Parser(node, root);
              return parser.result;
            }

            var NodeUIProperties = function () {
              function NodeUIProperties(node) {
                this._uiComp = null;
                this.opacity = 1;
                this.localOpacity = 1;
                this._uiTransformComp = null;
                this._node = void 0;
                this.uiTransformDirty = true;
                this._node = node;
              }

              _createClass(NodeUIProperties, [{
                key: "uiTransformComp",
                get: function get() {
                  if (!this._uiTransformComp) {
                    this._uiTransformComp = this._node.getComponent('cc.UITransform');
                  }

                  return this._uiTransformComp;
                },
                set: function set(value) {
                  this._uiTransformComp = value;
                }
              }, {
                key: "uiComp",
                get: function get() {
                  return this._uiComp;
                },
                set: function set(comp) {
                  if (this._uiComp && comp) {
                    warnID(12002);
                    return;
                  }

                  this._uiComp = comp;
                }
              }]);

              return NodeUIProperties;
            }();

            var SystemEventType;

            (function (SystemEventType) {
              SystemEventType["TOUCH_START"] = "touch-start";
              SystemEventType["TOUCH_MOVE"] = "touch-move";
              SystemEventType["TOUCH_END"] = "touch-end";
              SystemEventType["TOUCH_CANCEL"] = "touch-cancel";
              SystemEventType["MOUSE_DOWN"] = "mouse-down";
              SystemEventType["MOUSE_MOVE"] = "mouse-move";
              SystemEventType["MOUSE_UP"] = "mouse-up";
              SystemEventType["MOUSE_WHEEL"] = "mouse-wheel";
              SystemEventType["MOUSE_ENTER"] = "mouse-enter";
              SystemEventType["MOUSE_LEAVE"] = "mouse-leave";
              SystemEventType["KEY_DOWN"] = "keydown";
              SystemEventType["KEY_UP"] = "keyup";
              SystemEventType["DEVICEMOTION"] = "devicemotion";
              SystemEventType["TRANSFORM_CHANGED"] = "transform-changed";
              SystemEventType["SCENE_CHANGED_FOR_PERSISTS"] = "scene-changed-for-persists";
              SystemEventType["SIZE_CHANGED"] = "size-changed";
              SystemEventType["ANCHOR_CHANGED"] = "anchor-changed";
              SystemEventType["COLOR_CHANGED"] = "color-changed";
              SystemEventType["CHILD_ADDED"] = "child-added";
              SystemEventType["CHILD_REMOVED"] = "child-removed";
              SystemEventType["PARENT_CHANGED"] = "parent-changed";
              SystemEventType["NODE_DESTROYED"] = "node-destroyed";
              SystemEventType["LAYER_CHANGED"] = "layer-changed";
              SystemEventType["SIBLING_ORDER_CHANGED"] = "sibling-order-changed";
            })(SystemEventType || (SystemEventType = exports('SystemEventType', {})));

            ccenum(SystemEventType);
            legacyCC.SystemEventType = SystemEventType;

            var EventListener = function () {
              EventListener.create = function create(argObj) {
                assertID(argObj && argObj.event, 1900);
                var listenerType = argObj.event;
                delete argObj.event;
                var listener = null;

                if (listenerType === legacyCC.EventListener.TOUCH_ONE_BY_ONE) {
                  listener = new TouchOneByOneEventListener();
                } else if (listenerType === legacyCC.EventListener.TOUCH_ALL_AT_ONCE) {
                  listener = new TouchAllAtOnceEventListener();
                } else if (listenerType === legacyCC.EventListener.MOUSE) {
                  listener = new MouseEventListener();
                } else if (listenerType === legacyCC.EventListener.KEYBOARD) {
                  listener = new KeyboardEventListener();
                } else if (listenerType === legacyCC.EventListener.ACCELERATION) {
                  listener = new AccelerationEventListener(argObj.callback);
                  delete argObj.callback;
                }

                if (listener) {
                  for (var _i = 0, _Object$keys = Object.keys(argObj); _i < _Object$keys.length; _i++) {
                    var key = _Object$keys[_i];
                    listener[key] = argObj[key];
                  }
                }

                return listener;
              };

              function EventListener(type, listenerID, callback) {
                this._cameraPriority = 0;
                this.owner = null;
                this.mask = null;
                this._previousIn = false;
                this._target = null;
                this._onEvent = void 0;
                this._type = void 0;
                this._listenerID = void 0;
                this._registered = false;
                this._fixedPriority = 0;
                this._node = null;
                this._paused = true;
                this._isEnabled = true;
                this._onEvent = callback;
                this._type = type || 0;
                this._listenerID = listenerID || '';
              }

              var _proto = EventListener.prototype;

              _proto._setPaused = function _setPaused(paused) {
                this._paused = paused;
              };

              _proto._isPaused = function _isPaused() {
                return this._paused;
              };

              _proto._setRegistered = function _setRegistered(registered) {
                this._registered = registered;
              };

              _proto._isRegistered = function _isRegistered() {
                return this._registered;
              };

              _proto._getType = function _getType() {
                return this._type;
              };

              _proto._getListenerID = function _getListenerID() {
                return this._listenerID;
              };

              _proto._setFixedPriority = function _setFixedPriority(fixedPriority) {
                this._fixedPriority = fixedPriority;
              };

              _proto._getFixedPriority = function _getFixedPriority() {
                return this._fixedPriority;
              };

              _proto._setSceneGraphPriority = function _setSceneGraphPriority(node) {
                this._target = node;
                this._node = node;
              };

              _proto._getSceneGraphPriority = function _getSceneGraphPriority() {
                return this._node;
              };

              _proto.checkAvailable = function checkAvailable() {
                return this._onEvent !== null;
              };

              _proto.clone = function clone() {
                return null;
              };

              _proto.setEnabled = function setEnabled(enabled) {
                this._isEnabled = enabled;
              };

              _proto.isEnabled = function isEnabled() {
                return this._isEnabled;
              };

              _createClass(EventListener, [{
                key: "onEvent",
                get: function get() {
                  return this._onEvent;
                }
              }]);

              return EventListener;
            }();
            EventListener.UNKNOWN = 0;
            EventListener.TOUCH_ONE_BY_ONE = 1;
            EventListener.TOUCH_ALL_AT_ONCE = 2;
            EventListener.KEYBOARD = 3;
            EventListener.MOUSE = 4;
            EventListener.ACCELERATION = 6;
            EventListener.CUSTOM = 8;
            EventListener.ListenerID = {
              MOUSE: '__cc_mouse',
              TOUCH_ONE_BY_ONE: '__cc_touch_one_by_one',
              TOUCH_ALL_AT_ONCE: '__cc_touch_all_at_once',
              KEYBOARD: '__cc_keyboard',
              ACCELERATION: '__cc_acceleration'
            };
            var ListenerID = EventListener.ListenerID;
            var MouseEventListener = function (_EventListener) {
              _inheritsLoose(MouseEventListener, _EventListener);

              function MouseEventListener() {
                var _this;

                _this = _EventListener.call(this, EventListener.MOUSE, ListenerID.MOUSE, null) || this;
                _this.onMouseDown = null;
                _this.onMouseUp = null;
                _this.onMouseMove = null;
                _this.onMouseScroll = null;

                _this._onEvent = function (event) {
                  return _this._callback(event);
                };

                return _this;
              }

              var _proto2 = MouseEventListener.prototype;

              _proto2._callback = function _callback(event) {
                switch (event.eventType) {
                  case SystemEventType.MOUSE_DOWN:
                    if (this.onMouseDown) {
                      this.onMouseDown(event);
                    }

                    break;

                  case SystemEventType.MOUSE_UP:
                    if (this.onMouseUp) {
                      this.onMouseUp(event);
                    }

                    break;

                  case SystemEventType.MOUSE_MOVE:
                    if (this.onMouseMove) {
                      this.onMouseMove(event);
                    }

                    break;

                  case SystemEventType.MOUSE_WHEEL:
                    if (this.onMouseScroll) {
                      this.onMouseScroll(event);
                    }

                    break;
                }
              };

              _proto2.clone = function clone() {
                var eventListener = new MouseEventListener();
                eventListener.onMouseDown = this.onMouseDown;
                eventListener.onMouseUp = this.onMouseUp;
                eventListener.onMouseMove = this.onMouseMove;
                eventListener.onMouseScroll = this.onMouseScroll;
                return eventListener;
              };

              _proto2.checkAvailable = function checkAvailable() {
                return true;
              };

              return MouseEventListener;
            }(EventListener);
            var TouchOneByOneEventListener = function (_EventListener2) {
              _inheritsLoose(TouchOneByOneEventListener, _EventListener2);

              function TouchOneByOneEventListener() {
                var _this2;

                _this2 = _EventListener2.call(this, EventListener.TOUCH_ONE_BY_ONE, ListenerID.TOUCH_ONE_BY_ONE, null) || this;
                _this2.swallowTouches = false;
                _this2.onTouchBegan = null;
                _this2.onTouchMoved = null;
                _this2.onTouchEnded = null;
                _this2.onTouchCancelled = null;
                _this2._claimedTouches = [];
                return _this2;
              }

              var _proto3 = TouchOneByOneEventListener.prototype;

              _proto3.setSwallowTouches = function setSwallowTouches(needSwallow) {
                this.swallowTouches = needSwallow;
              };

              _proto3.isSwallowTouches = function isSwallowTouches() {
                return this.swallowTouches;
              };

              _proto3.clone = function clone() {
                var eventListener = new TouchOneByOneEventListener();
                eventListener.onTouchBegan = this.onTouchBegan;
                eventListener.onTouchMoved = this.onTouchMoved;
                eventListener.onTouchEnded = this.onTouchEnded;
                eventListener.onTouchCancelled = this.onTouchCancelled;
                eventListener.swallowTouches = this.swallowTouches;
                return eventListener;
              };

              _proto3.checkAvailable = function checkAvailable() {
                if (!this.onTouchBegan) {
                  logID(1801);
                  return false;
                }

                return true;
              };

              return TouchOneByOneEventListener;
            }(EventListener);
            var TouchAllAtOnceEventListener = function (_EventListener3) {
              _inheritsLoose(TouchAllAtOnceEventListener, _EventListener3);

              function TouchAllAtOnceEventListener() {
                var _this3;

                _this3 = _EventListener3.call(this, EventListener.TOUCH_ALL_AT_ONCE, ListenerID.TOUCH_ALL_AT_ONCE, null) || this;
                _this3.onTouchesBegan = null;
                _this3.onTouchesMoved = null;
                _this3.onTouchesEnded = null;
                _this3.onTouchesCancelled = null;
                return _this3;
              }

              var _proto4 = TouchAllAtOnceEventListener.prototype;

              _proto4.clone = function clone() {
                var eventListener = new TouchAllAtOnceEventListener();
                eventListener.onTouchesBegan = this.onTouchesBegan;
                eventListener.onTouchesMoved = this.onTouchesMoved;
                eventListener.onTouchesEnded = this.onTouchesEnded;
                eventListener.onTouchesCancelled = this.onTouchesCancelled;
                return eventListener;
              };

              _proto4.checkAvailable = function checkAvailable() {
                if (this.onTouchesBegan === null && this.onTouchesMoved === null && this.onTouchesEnded === null && this.onTouchesCancelled === null) {
                  logID(1802);
                  return false;
                }

                return true;
              };

              return TouchAllAtOnceEventListener;
            }(EventListener);
            var AccelerationEventListener = function (_EventListener4) {
              _inheritsLoose(AccelerationEventListener, _EventListener4);

              function AccelerationEventListener(callback) {
                var _this4;

                _this4 = _EventListener4.call(this, EventListener.ACCELERATION, ListenerID.ACCELERATION, null) || this;
                _this4._onAccelerationEvent = null;

                _this4._onEvent = function (event) {
                  return _this4._callback(event);
                };

                _this4._onAccelerationEvent = callback;
                return _this4;
              }

              var _proto5 = AccelerationEventListener.prototype;

              _proto5._callback = function _callback(event) {
                if (this._onAccelerationEvent) {
                  this._onAccelerationEvent(event.acc, event);
                }
              };

              _proto5.checkAvailable = function checkAvailable() {
                assertID(this._onAccelerationEvent, 1803);
                return true;
              };

              _proto5.clone = function clone() {
                return new AccelerationEventListener(this._onAccelerationEvent);
              };

              return AccelerationEventListener;
            }(EventListener);
            var KeyboardEventListener = function (_EventListener5) {
              _inheritsLoose(KeyboardEventListener, _EventListener5);

              function KeyboardEventListener() {
                var _this5;

                _this5 = _EventListener5.call(this, EventListener.KEYBOARD, ListenerID.KEYBOARD, null) || this;
                _this5.onKeyPressed = null;
                _this5.onKeyReleased = null;

                _this5._onEvent = function (event) {
                  return _this5._callback(event);
                };

                return _this5;
              }

              var _proto6 = KeyboardEventListener.prototype;

              _proto6._callback = function _callback(event) {
                if (event.isPressed) {
                  if (this.onKeyPressed) {
                    this.onKeyPressed(event.keyCode, event);
                  }
                } else if (this.onKeyReleased) {
                  this.onKeyReleased(event.keyCode, event);
                }
              };

              _proto6.clone = function clone() {
                var eventListener = new KeyboardEventListener();
                eventListener.onKeyPressed = this.onKeyPressed;
                eventListener.onKeyReleased = this.onKeyReleased;
                return eventListener;
              };

              _proto6.checkAvailable = function checkAvailable() {
                if (this.onKeyPressed === null && this.onKeyReleased === null) {
                  logID(1800);
                  return false;
                }

                return true;
              };

              return KeyboardEventListener;
            }(EventListener);
            legacyCC.EventListener = EventListener;

            var ListenerID$1 = EventListener.ListenerID;

            function checkUINode(node) {
              if (node && node.getComponent('cc.UITransform')) {
                return true;
              }

              return false;
            }

            var _EventListenerVector = function () {
              function _EventListenerVector() {
                this.gt0Index = 0;
                this._fixedListeners = [];
                this._sceneGraphListeners = [];
              }

              var _proto = _EventListenerVector.prototype;

              _proto.size = function size() {
                return this._fixedListeners.length + this._sceneGraphListeners.length;
              };

              _proto.empty = function empty() {
                return this._fixedListeners.length === 0 && this._sceneGraphListeners.length === 0;
              };

              _proto.push = function push(listener) {
                if (listener._getFixedPriority() === 0) {
                  this._sceneGraphListeners.push(listener);
                } else {
                  this._fixedListeners.push(listener);
                }
              };

              _proto.clearSceneGraphListeners = function clearSceneGraphListeners() {
                this._sceneGraphListeners.length = 0;
              };

              _proto.clearFixedListeners = function clearFixedListeners() {
                this._fixedListeners.length = 0;
              };

              _proto.clear = function clear() {
                this._sceneGraphListeners.length = 0;
                this._fixedListeners.length = 0;
              };

              _proto.getFixedPriorityListeners = function getFixedPriorityListeners() {
                return this._fixedListeners;
              };

              _proto.getSceneGraphPriorityListeners = function getSceneGraphPriorityListeners() {
                return this._sceneGraphListeners;
              };

              return _EventListenerVector;
            }();

            function __getListenerID(event) {
              var eventType = Event;
              var type = event.type;

              if (type === eventType.ACCELERATION) {
                return ListenerID$1.ACCELERATION;
              }

              if (type === eventType.KEYBOARD) {
                return ListenerID$1.KEYBOARD;
              }

              if (type.startsWith(eventType.MOUSE)) {
                return ListenerID$1.MOUSE;
              }

              if (type.startsWith(eventType.TOUCH)) {
                logID(2000);
              }

              return '';
            }

            var DIRTY_NONE = 0;
            var DIRTY_FIXED_PRIORITY = 1 << 0;
            var DIRTY_SCENE_GRAPH_PRIORITY = 1 << 1;

            var EventManager = function () {
              function EventManager() {
                this._listenersMap = {};
                this._priorityDirtyFlagMap = {};
                this._nodeListenersMap = {};
                this._toAddedListeners = [];
                this._toRemovedListeners = [];
                this._dirtyListeners = {};
                this._inDispatch = 0;
                this._isEnabled = false;
                this._internalCustomListenerIDs = [];
                this._currentTouch = null;
                this._currentTouchListener = null;
              }

              var _proto2 = EventManager.prototype;

              _proto2.pauseTarget = function pauseTarget(node, recursive) {
                if (recursive === void 0) {
                  recursive = false;
                }

                if (!(node instanceof legacyCC._BaseNode)) {
                  warnID(3506);
                  return;
                }

                var listeners = this._nodeListenersMap[node.uuid];

                if (listeners) {
                  for (var i = 0; i < listeners.length; ++i) {
                    var _listener = listeners[i];

                    _listener._setPaused(true);
                  }
                }

                if (recursive === true) {
                  var locChildren = node.children;

                  if (locChildren) {
                    for (var _i = 0; _i < locChildren.length; ++_i) {
                      var locChild = locChildren[_i];
                      this.pauseTarget(locChild, true);
                    }
                  }
                }
              };

              _proto2.resumeTarget = function resumeTarget(node, recursive) {
                if (recursive === void 0) {
                  recursive = false;
                }

                if (!(node instanceof legacyCC._BaseNode)) {
                  warnID(3506);
                  return;
                }

                var listeners = this._nodeListenersMap[node.uuid];

                if (listeners) {
                  for (var i = 0; i < listeners.length; ++i) {
                    var _listener2 = listeners[i];

                    _listener2._setPaused(false);
                  }
                }

                this._setDirtyForNode(node);

                if (recursive === true && node.children.length > 0) {
                  var locChildren = node.children;

                  if (locChildren) {
                    for (var _i2 = 0; _i2 < locChildren.length; ++_i2) {
                      var locChild = locChildren[_i2];
                      this.resumeTarget(locChild, true);
                    }
                  }
                }
              };

              _proto2.frameUpdateListeners = function frameUpdateListeners() {
                var locListenersMap = this._listenersMap;
                var locPriorityDirtyFlagMap = this._priorityDirtyFlagMap;

                for (var selKey in locListenersMap) {
                  if (locListenersMap[selKey].empty()) {
                    delete locPriorityDirtyFlagMap[selKey];
                    delete locListenersMap[selKey];
                  }
                }

                var locToAddedListeners = this._toAddedListeners;

                if (locToAddedListeners.length !== 0) {
                  for (var i = 0, len = locToAddedListeners.length; i < len; i++) {
                    this._forceAddEventListener(locToAddedListeners[i]);
                  }

                  locToAddedListeners.length = 0;
                }

                if (this._toRemovedListeners.length !== 0) {
                  this._cleanToRemovedListeners();
                }
              };

              _proto2.hasEventListener = function hasEventListener(listenerID) {
                return !!this._getListeners(listenerID);
              };

              _proto2.addListener = function addListener(listener, nodeOrPriority) {
                assertID(listener && nodeOrPriority, 3503);

                if (!(legacyCC.js.isNumber(nodeOrPriority) || nodeOrPriority instanceof legacyCC._BaseNode)) {
                  warnID(3506);
                  return null;
                }

                if (!(listener instanceof legacyCC.EventListener)) {
                  assertID(!legacyCC.js.isNumber(nodeOrPriority), 3504);
                  listener = legacyCC.EventListener.create(listener);
                } else if (listener._isRegistered()) {
                  logID(3505);
                  return null;
                }

                if (!listener.checkAvailable()) {
                  return null;
                }

                if (legacyCC.js.isNumber(nodeOrPriority)) {
                  if (nodeOrPriority === 0) {
                    logID(3500);
                    return null;
                  }

                  listener._setSceneGraphPriority(null);

                  listener._setFixedPriority(nodeOrPriority);

                  listener._setRegistered(true);

                  listener._setPaused(false);

                  this._addListener(listener);
                } else {
                  if (!checkUINode(nodeOrPriority)) {
                    logID(3512);
                    return null;
                  }

                  listener._setSceneGraphPriority(nodeOrPriority);

                  listener._setFixedPriority(0);

                  listener._setRegistered(true);

                  this._addListener(listener);
                }

                return listener;
              };

              _proto2.addCustomListener = function addCustomListener(eventName, callback) {
                var listener = EventListener.create({
                  event: legacyCC.EventListener.CUSTOM,
                  eventName: eventName,
                  callback: callback
                });
                this.addListener(listener, 1);
                return listener;
              };

              _proto2.removeListener = function removeListener(listener) {
                if (listener == null) {
                  return;
                }

                var isFound = false;
                var locListener = this._listenersMap;

                if (listener === this._currentTouchListener) {
                  this._currentTouchListener = this._currentTouch = null;
                }

                for (var selKey in locListener) {
                  var listeners = locListener[selKey];
                  var fixedPriorityListeners = listeners.getFixedPriorityListeners();
                  var sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners();
                  isFound = this._removeListenerInVector(sceneGraphPriorityListeners, listener);

                  if (isFound) {
                    this._setDirty(listener._getListenerID(), DIRTY_SCENE_GRAPH_PRIORITY);
                  } else {
                    isFound = this._removeListenerInVector(fixedPriorityListeners, listener);

                    if (isFound) {
                      this._setDirty(listener._getListenerID(), DIRTY_FIXED_PRIORITY);
                    }
                  }

                  if (listeners.empty()) {
                    delete this._priorityDirtyFlagMap[listener._getListenerID()];
                    delete locListener[selKey];
                  }

                  if (isFound) {
                    break;
                  }
                }

                if (!isFound) {
                  var locToAddedListeners = this._toAddedListeners;

                  for (var i = locToAddedListeners.length - 1; i >= 0; i--) {
                    var selListener = locToAddedListeners[i];

                    if (selListener === listener) {
                      legacyCC.js.array.removeAt(locToAddedListeners, i);

                      selListener._setRegistered(false);

                      break;
                    }
                  }
                }
              };

              _proto2.removeListeners = function removeListeners(listenerType, recursive) {
                if (recursive === void 0) {
                  recursive = false;
                }

                if (!(legacyCC.js.isNumber(listenerType) || listenerType instanceof legacyCC._BaseNode)) {
                  warnID(3506);
                  return;
                }

                if (listenerType._id !== undefined) {
                  var listeners = this._nodeListenersMap[listenerType._id];

                  if (listeners) {
                    var listenersCopy = legacyCC.js.array.copy(listeners);

                    for (var i = 0; i < listenersCopy.length; ++i) {
                      var listenerCopy = listenersCopy[i];
                      this.removeListener(listenerCopy);
                    }

                    delete this._nodeListenersMap[listenerType._id];
                  }

                  var locToAddedListeners = this._toAddedListeners;

                  for (var _i3 = 0; _i3 < locToAddedListeners.length;) {
                    var _listener3 = locToAddedListeners[_i3];

                    if (_listener3._getSceneGraphPriority() === listenerType) {
                      _listener3._setSceneGraphPriority(null);

                      _listener3._setRegistered(false);

                      locToAddedListeners.splice(_i3, 1);
                    } else {
                      ++_i3;
                    }
                  }

                  if (recursive === true) {
                    var locChildren = listenerType.getChildren();

                    for (var _i4 = 0; _i4 < locChildren.length; ++_i4) {
                      var locChild = locChildren[_i4];
                      this.removeListeners(locChild, true);
                    }
                  }
                } else if (listenerType === legacyCC.EventListener.TOUCH_ONE_BY_ONE) {
                  this._removeListenersForListenerID(ListenerID$1.TOUCH_ONE_BY_ONE);
                } else if (listenerType === legacyCC.EventListener.TOUCH_ALL_AT_ONCE) {
                  this._removeListenersForListenerID(ListenerID$1.TOUCH_ALL_AT_ONCE);
                } else if (listenerType === legacyCC.EventListener.MOUSE) {
                  this._removeListenersForListenerID(ListenerID$1.MOUSE);
                } else if (listenerType === legacyCC.EventListener.ACCELERATION) {
                  this._removeListenersForListenerID(ListenerID$1.ACCELERATION);
                } else if (listenerType === legacyCC.EventListener.KEYBOARD) {
                  this._removeListenersForListenerID(ListenerID$1.KEYBOARD);
                } else {
                  logID(3501);
                }
              };

              _proto2.removeCustomListeners = function removeCustomListeners(customEventName) {
                this._removeListenersForListenerID(customEventName);
              };

              _proto2.removeAllListeners = function removeAllListeners() {
                var locListeners = this._listenersMap;
                var locInternalCustomEventIDs = this._internalCustomListenerIDs;

                for (var selKey in locListeners) {
                  if (locInternalCustomEventIDs.indexOf(selKey) === -1) {
                    this._removeListenersForListenerID(selKey);
                  }
                }
              };

              _proto2.setPriority = function setPriority(listener, fixedPriority) {
                if (listener == null) {
                  return;
                }

                var locListeners = this._listenersMap;

                for (var selKey in locListeners) {
                  var selListeners = locListeners[selKey];
                  var fixedPriorityListeners = selListeners.getFixedPriorityListeners();

                  if (fixedPriorityListeners) {
                    var found = fixedPriorityListeners.indexOf(listener);

                    if (found !== -1) {
                      if (listener._getSceneGraphPriority() != null) {
                        logID(3502);
                      }

                      if (listener._getFixedPriority() !== fixedPriority) {
                        listener._setFixedPriority(fixedPriority);

                        this._setDirty(listener._getListenerID(), DIRTY_FIXED_PRIORITY);
                      }

                      return;
                    }
                  }
                }
              };

              _proto2.setEnabled = function setEnabled(enabled) {
                this._isEnabled = enabled;
              };

              _proto2.isEnabled = function isEnabled() {
                return this._isEnabled;
              };

              _proto2.dispatchEvent = function dispatchEvent(event) {
                if (!this._isEnabled) {
                  return;
                }

                this._updateDirtyFlagForSceneGraph();

                this._inDispatch++;

                if (!event || !event.getType) {
                  errorID(3511);
                  return;
                }

                if (event.getType().startsWith(legacyCC.Event.TOUCH)) {
                  this._dispatchTouchEvent(event);

                  this._inDispatch--;
                  return;
                }

                var listenerID = __getListenerID(event);

                this._sortEventListeners(listenerID);

                var selListeners = this._listenersMap[listenerID];

                if (selListeners != null) {
                  this._dispatchEventToListeners(selListeners, this._onListenerCallback, event);

                  this._onUpdateListeners(selListeners);
                }

                this._inDispatch--;
              };

              _proto2._onListenerCallback = function _onListenerCallback(listener, event) {
                event.currentTarget = listener._target;
                var onEvent = listener.onEvent;

                if (onEvent) {
                  onEvent(event);
                }

                return event.isStopped();
              };

              _proto2.dispatchCustomEvent = function dispatchCustomEvent(eventName, optionalUserData) {
                var ev = new legacyCC.Event.EventCustom(eventName);
                ev.setUserData(optionalUserData);
                this.dispatchEvent(ev);
              };

              _proto2._setDirtyForNode = function _setDirtyForNode(node) {
                var selListeners = this._nodeListenersMap[node._id];

                if (selListeners !== undefined) {
                  for (var j = 0, len = selListeners.length; j < len; j++) {
                    var selListener = selListeners[j];

                    var listenerID = selListener._getListenerID();

                    if (!this._dirtyListeners[listenerID]) {
                      this._dirtyListeners[listenerID] = true;
                    }
                  }
                }

                if (node.children.length > 0) {
                  var _children = node.children;

                  for (var i = 0, _len = _children ? _children.length : 0; i < _len; i++) {
                    this._setDirtyForNode(_children[i]);
                  }
                }
              };

              _proto2._addListener = function _addListener(listener) {
                if (this._inDispatch === 0) {
                  this._forceAddEventListener(listener);
                } else {
                  this._toAddedListeners.push(listener);
                }
              };

              _proto2._forceAddEventListener = function _forceAddEventListener(listener) {
                var listenerID = listener._getListenerID();

                var listeners = this._listenersMap[listenerID];

                if (!listeners) {
                  listeners = new _EventListenerVector();
                  this._listenersMap[listenerID] = listeners;
                }

                listeners.push(listener);

                if (listener._getFixedPriority() === 0) {
                  this._setDirty(listenerID, DIRTY_SCENE_GRAPH_PRIORITY);

                  var node = listener._getSceneGraphPriority();

                  if (node === null) {
                    logID(3507);
                  }

                  this._associateNodeAndEventListener(node, listener);

                  if (node.activeInHierarchy) {
                    this.resumeTarget(node);
                  }
                } else {
                  this._setDirty(listenerID, DIRTY_FIXED_PRIORITY);
                }
              };

              _proto2._getListeners = function _getListeners(listenerID) {
                return this._listenersMap[listenerID];
              };

              _proto2._updateDirtyFlagForSceneGraph = function _updateDirtyFlagForSceneGraph() {
                var locDirtyListeners = this._dirtyListeners;

                for (var selKey in locDirtyListeners) {
                  this._setDirty(selKey, DIRTY_SCENE_GRAPH_PRIORITY);

                  locDirtyListeners[selKey] = false;
                }
              };

              _proto2._removeAllListenersInVector = function _removeAllListenersInVector(listenerVector) {
                if (!listenerVector) {
                  return;
                }

                var selListener;

                for (var i = listenerVector.length - 1; i >= 0; i--) {
                  selListener = listenerVector[i];

                  selListener._setRegistered(false);

                  if (selListener._getSceneGraphPriority() != null) {
                    this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener);

                    selListener._setSceneGraphPriority(null);
                  }

                  if (this._inDispatch === 0) {
                    legacyCC.js.array.removeAt(listenerVector, i);
                  }
                }
              };

              _proto2._removeListenersForListenerID = function _removeListenersForListenerID(listenerID) {
                var listeners = this._listenersMap[listenerID];

                if (listeners) {
                  var fixedPriorityListeners = listeners.getFixedPriorityListeners();
                  var sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners();

                  this._removeAllListenersInVector(sceneGraphPriorityListeners);

                  this._removeAllListenersInVector(fixedPriorityListeners);

                  delete this._priorityDirtyFlagMap[listenerID];

                  if (!this._inDispatch) {
                    listeners.clear();
                    delete this._listenersMap[listenerID];
                  }
                }

                var locToAddedListeners = this._toAddedListeners;

                for (var i = locToAddedListeners.length - 1; i >= 0; i--) {
                  var _listener4 = locToAddedListeners[i];

                  if (_listener4 && _listener4._getListenerID() === listenerID) {
                    legacyCC.js.array.removeAt(locToAddedListeners, i);
                  }
                }
              };

              _proto2._sortEventListeners = function _sortEventListeners(listenerID) {
                var dirtyFlag = DIRTY_NONE;
                var locFlagMap = this._priorityDirtyFlagMap;

                if (locFlagMap[listenerID]) {
                  dirtyFlag = locFlagMap[listenerID];
                }

                if (dirtyFlag !== DIRTY_NONE) {
                  locFlagMap[listenerID] = DIRTY_NONE;

                  if (dirtyFlag & DIRTY_FIXED_PRIORITY) {
                    this._sortListenersOfFixedPriority(listenerID);
                  }

                  if (dirtyFlag & DIRTY_SCENE_GRAPH_PRIORITY) {
                    var rootEntity = legacyCC.director.getScene();

                    if (rootEntity) {
                      this._sortListenersOfSceneGraphPriority(listenerID);
                    }
                  }
                }
              };

              _proto2._sortListenersOfSceneGraphPriority = function _sortListenersOfSceneGraphPriority(listenerID) {
                var listeners = this._getListeners(listenerID);

                if (!listeners) {
                  return;
                }

                var sceneGraphListener = listeners.getSceneGraphPriorityListeners();

                if (!sceneGraphListener || sceneGraphListener.length === 0) {
                  return;
                }

                var eventListeners = listeners.getSceneGraphPriorityListeners();
                eventListeners.forEach(function (listener) {
                  var node = listener._getSceneGraphPriority();

                  var trans = node === null || node === void 0 ? void 0 : node._uiProps.uiTransformComp;
                  listener._cameraPriority = trans ? trans.cameraPriority : 0;
                });
                eventListeners.sort(this._sortEventListenersOfSceneGraphPriorityDes);
              };

              _proto2._sortEventListenersOfSceneGraphPriorityDes = function _sortEventListenersOfSceneGraphPriorityDes(l1, l2) {
                var node1 = l1._getSceneGraphPriority();

                var node2 = l2._getSceneGraphPriority();

                if (!l2 || !node2 || !node2._activeInHierarchy || !node2._uiProps.uiTransformComp) {
                  return -1;
                } else if (!l1 || !node1 || !node1._activeInHierarchy || !node1._uiProps.uiTransformComp) {
                  return 1;
                }

                var p1 = node1;
                var p2 = node2;
                var ex = false;

                if (l1._cameraPriority !== l2._cameraPriority) {
                  return l2._cameraPriority - l1._cameraPriority;
                }

                while (p1.parent._id !== p2.parent._id) {
                  p1 = p1.parent.parent === null ? (ex = true) && node2 : p1.parent;
                  p2 = p2.parent.parent === null ? (ex = true) && node1 : p2.parent;
                }

                if (p1._id === p2._id) {
                  if (p1._id === node2._id) {
                    return -1;
                  }

                  if (p1._id === node1._id) {
                    return 1;
                  }
                }

                var priority1 = p1.getSiblingIndex();
                var priority2 = p2.getSiblingIndex();
                return ex ? priority1 - priority2 : priority2 - priority1;
              };

              _proto2._sortListenersOfFixedPriority = function _sortListenersOfFixedPriority(listenerID) {
                var listeners = this._listenersMap[listenerID];

                if (!listeners) {
                  return;
                }

                var fixedListeners = listeners.getFixedPriorityListeners();

                if (!fixedListeners || fixedListeners.length === 0) {
                  return;
                }

                fixedListeners.sort(this._sortListenersOfFixedPriorityAsc);
                var index = 0;

                for (var len = fixedListeners.length; index < len;) {
                  if (fixedListeners[index]._getFixedPriority() >= 0) {
                    break;
                  }

                  ++index;
                }

                listeners.gt0Index = index;
              };

              _proto2._sortListenersOfFixedPriorityAsc = function _sortListenersOfFixedPriorityAsc(l1, l2) {
                return l1._getFixedPriority() - l2._getFixedPriority();
              };

              _proto2._onUpdateListeners = function _onUpdateListeners(listeners) {
                var fixedPriorityListeners = listeners.getFixedPriorityListeners();
                var sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners();
                var toRemovedListeners = this._toRemovedListeners;

                if (sceneGraphPriorityListeners) {
                  for (var i = sceneGraphPriorityListeners.length - 1; i >= 0; i--) {
                    var selListener = sceneGraphPriorityListeners[i];

                    if (!selListener._isRegistered()) {
                      legacyCC.js.array.removeAt(sceneGraphPriorityListeners, i);
                      var idx = toRemovedListeners.indexOf(selListener);

                      if (idx !== -1) {
                        toRemovedListeners.splice(idx, 1);
                      }
                    }
                  }
                }

                if (fixedPriorityListeners) {
                  for (var _i5 = fixedPriorityListeners.length - 1; _i5 >= 0; _i5--) {
                    var _selListener = fixedPriorityListeners[_i5];

                    if (!_selListener._isRegistered()) {
                      legacyCC.js.array.removeAt(fixedPriorityListeners, _i5);

                      var _idx = toRemovedListeners.indexOf(_selListener);

                      if (_idx !== -1) {
                        toRemovedListeners.splice(_idx, 1);
                      }
                    }
                  }
                }

                if (sceneGraphPriorityListeners && sceneGraphPriorityListeners.length === 0) {
                  listeners.clearSceneGraphListeners();
                }

                if (fixedPriorityListeners && fixedPriorityListeners.length === 0) {
                  listeners.clearFixedListeners();
                }
              };

              _proto2._updateTouchListeners = function _updateTouchListeners(event) {
                var locInDispatch = this._inDispatch;
                assertID(locInDispatch > 0, 3508);

                if (locInDispatch > 1) {
                  return;
                }

                var listeners;
                listeners = this._listenersMap[ListenerID$1.TOUCH_ONE_BY_ONE];

                if (listeners) {
                  this._onUpdateListeners(listeners);
                }

                listeners = this._listenersMap[ListenerID$1.TOUCH_ALL_AT_ONCE];

                if (listeners) {
                  this._onUpdateListeners(listeners);
                }

                assertID(locInDispatch === 1, 3509);
                var locToAddedListeners = this._toAddedListeners;

                if (locToAddedListeners.length !== 0) {
                  for (var i = 0, len = locToAddedListeners.length; i < len; i++) {
                    this._forceAddEventListener(locToAddedListeners[i]);
                  }

                  this._toAddedListeners.length = 0;
                }

                if (this._toRemovedListeners.length !== 0) {
                  this._cleanToRemovedListeners();
                }
              };

              _proto2._cleanToRemovedListeners = function _cleanToRemovedListeners() {
                var toRemovedListeners = this._toRemovedListeners;

                for (var i = 0; i < toRemovedListeners.length; ++i) {
                  var selListener = toRemovedListeners[i];

                  var listeners = this._listenersMap[selListener._getListenerID()];

                  if (!listeners) {
                    continue;
                  }

                  var fixedPriorityListeners = listeners.getFixedPriorityListeners();
                  var sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners();

                  if (sceneGraphPriorityListeners) {
                    var idx = sceneGraphPriorityListeners.indexOf(selListener);

                    if (idx !== -1) {
                      sceneGraphPriorityListeners.splice(idx, 1);
                    }
                  }

                  if (fixedPriorityListeners) {
                    var _idx2 = fixedPriorityListeners.indexOf(selListener);

                    if (_idx2 !== -1) {
                      fixedPriorityListeners.splice(_idx2, 1);
                    }
                  }
                }

                toRemovedListeners.length = 0;
              };

              _proto2._onTouchEventCallback = function _onTouchEventCallback(listener, argsObj) {
                if (!listener._isRegistered()) {
                  return false;
                }

                var event = argsObj.event;
                var selTouch = event.touch;
                event.currentTarget = listener._getSceneGraphPriority();
                var isClaimed = false;
                var removedIdx = -1;
                var eventCode = event.getEventCode();

                if (eventCode === SystemEventType.TOUCH_START) {
                  if (!macro.ENABLE_MULTI_TOUCH && eventManager._currentTouch) {
                    var node = eventManager._currentTouchListener._node;

                    if (!node || node.activeInHierarchy) {
                      return false;
                    }
                  }

                  if (listener.onTouchBegan) {
                    isClaimed = listener.onTouchBegan(selTouch, event);

                    if (isClaimed && listener._isRegistered() && !listener._isPaused()) {
                      listener._claimedTouches.push(selTouch);

                      if (macro.ENABLE_MULTI_TOUCH || !eventManager._currentTouch) {
                        eventManager._currentTouch = selTouch;
                      }

                      eventManager._currentTouchListener = listener;
                    }
                  }
                } else if (listener._claimedTouches.length > 0) {
                  removedIdx = listener._claimedTouches.indexOf(selTouch);

                  if (removedIdx !== -1) {
                    isClaimed = true;

                    if (!macro.ENABLE_MULTI_TOUCH && eventManager._currentTouch && eventManager._currentTouch !== selTouch) {
                      return false;
                    }

                    if (eventCode === SystemEventType.TOUCH_MOVE && listener.onTouchMoved) {
                      listener.onTouchMoved(selTouch, event);
                    } else if (eventCode === SystemEventType.TOUCH_END) {
                      if (listener.onTouchEnded) {
                        listener.onTouchEnded(selTouch, event);
                      }

                      if (listener._isRegistered()) {
                        listener._claimedTouches.splice(removedIdx, 1);
                      }

                      if (macro.ENABLE_MULTI_TOUCH || eventManager._currentTouch === selTouch) {
                        eventManager._currentTouch = null;
                      }

                      eventManager._currentTouchListener = null;
                    } else if (eventCode === SystemEventType.TOUCH_CANCEL) {
                      if (listener.onTouchCancelled) {
                        listener.onTouchCancelled(selTouch, event);
                      }

                      if (listener._isRegistered()) {
                        listener._claimedTouches.splice(removedIdx, 1);
                      }

                      if (macro.ENABLE_MULTI_TOUCH || eventManager._currentTouch === selTouch) {
                        eventManager._currentTouch = null;
                      }

                      eventManager._currentTouchListener = null;
                    }
                  }
                }

                if (event.isStopped()) {
                  eventManager._updateTouchListeners(event);

                  return true;
                }

                if (isClaimed && listener._isRegistered() && listener.swallowTouches) {
                  if (argsObj.needsMutableSet) {
                    argsObj.touches.splice(selTouch, 1);
                  }

                  return true;
                }

                return false;
              };

              _proto2._dispatchTouchEvent = function _dispatchTouchEvent(event) {
                this._sortEventListeners(ListenerID$1.TOUCH_ONE_BY_ONE);

                this._sortEventListeners(ListenerID$1.TOUCH_ALL_AT_ONCE);

                var oneByOneListeners = this._getListeners(ListenerID$1.TOUCH_ONE_BY_ONE);

                var allAtOnceListeners = this._getListeners(ListenerID$1.TOUCH_ALL_AT_ONCE);

                if (oneByOneListeners === null && allAtOnceListeners === null) {
                  return;
                }

                var originalTouches = event.getTouches();
                var mutableTouches = legacyCC.js.array.copy(originalTouches);
                var oneByOneArgsObj = {
                  event: event,
                  needsMutableSet: oneByOneListeners && allAtOnceListeners,
                  touches: mutableTouches,
                  selTouch: null
                };

                if (oneByOneListeners) {
                  for (var i = 0; i < originalTouches.length; ++i) {
                    var originalTouch = originalTouches[i];
                    event.touch = originalTouch;
                    event.propagationStopped = event.propagationImmediateStopped = false;

                    this._dispatchEventToListeners(oneByOneListeners, this._onTouchEventCallback, oneByOneArgsObj);
                  }
                }

                if (allAtOnceListeners && mutableTouches.length > 0) {
                  this._dispatchEventToListeners(allAtOnceListeners, this._onTouchesEventCallback, {
                    event: event,
                    touches: mutableTouches
                  });

                  if (event.isStopped()) {
                    return;
                  }
                }

                this._updateTouchListeners(event);
              };

              _proto2._onTouchesEventCallback = function _onTouchesEventCallback(listener, callbackParams) {
                if (!listener._isRegistered()) {
                  return false;
                }

                var event = callbackParams.event;
                var touches = callbackParams.touches;
                var eventCode = event.getEventCode();
                event.currentTarget = listener._getSceneGraphPriority();

                if (eventCode === SystemEventType.TOUCH_START && listener.onTouchesBegan) {
                  listener.onTouchesBegan(touches, event);
                } else if (eventCode === SystemEventType.TOUCH_MOVE && listener.onTouchesMoved) {
                  listener.onTouchesMoved(touches, event);
                } else if (eventCode === SystemEventType.TOUCH_END && listener.onTouchesEnded) {
                  listener.onTouchesEnded(touches, event);
                } else if (eventCode === SystemEventType.TOUCH_CANCEL && listener.onTouchesCancelled) {
                  listener.onTouchesCancelled(touches, event);
                }

                if (event.isStopped()) {
                  eventManager._updateTouchListeners(event);

                  return true;
                }

                return false;
              };

              _proto2._associateNodeAndEventListener = function _associateNodeAndEventListener(node, listener) {
                var listeners = this._nodeListenersMap[node.uuid];

                if (!listeners) {
                  listeners = [];
                  this._nodeListenersMap[node.uuid] = listeners;
                }

                listeners.push(listener);
              };

              _proto2._dissociateNodeAndEventListener = function _dissociateNodeAndEventListener(node, listener) {
                var listeners = this._nodeListenersMap[node.uuid];

                if (listeners) {
                  legacyCC.js.array.remove(listeners, listener);

                  if (listeners.length === 0) {
                    delete this._nodeListenersMap[node.uuid];
                  }
                }
              };

              _proto2._dispatchEventToListeners = function _dispatchEventToListeners(listeners, onEvent, eventOrArgs) {
                var shouldStopPropagation = false;
                var fixedPriorityListeners = listeners.getFixedPriorityListeners();
                var sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners();
                var i = 0;

                if (fixedPriorityListeners) {
                  if (fixedPriorityListeners.length !== 0) {
                    for (; i < listeners.gt0Index; ++i) {
                      var selListener = fixedPriorityListeners[i];

                      if (selListener.isEnabled() && !selListener._isPaused() && selListener._isRegistered() && onEvent(selListener, eventOrArgs)) {
                        shouldStopPropagation = true;
                        break;
                      }
                    }
                  }
                }

                if (sceneGraphPriorityListeners && !shouldStopPropagation) {
                  for (var _i6 = 0; _i6 < sceneGraphPriorityListeners.length; ++_i6) {
                    var _selListener2 = sceneGraphPriorityListeners[_i6];

                    if (_selListener2.isEnabled() && !_selListener2._isPaused() && _selListener2._isRegistered() && onEvent(_selListener2, eventOrArgs)) {
                      shouldStopPropagation = true;
                      break;
                    }
                  }
                }

                if (fixedPriorityListeners && !shouldStopPropagation) {
                  for (; i < fixedPriorityListeners.length; ++i) {
                    var _selListener3 = fixedPriorityListeners[i];

                    if (_selListener3.isEnabled() && !_selListener3._isPaused() && _selListener3._isRegistered() && onEvent(_selListener3, eventOrArgs)) {
                      shouldStopPropagation = true;
                      break;
                    }
                  }
                }
              };

              _proto2._setDirty = function _setDirty(listenerID, flag) {
                var locDirtyFlagMap = this._priorityDirtyFlagMap;

                if (locDirtyFlagMap[listenerID] == null) {
                  locDirtyFlagMap[listenerID] = flag;
                } else {
                  locDirtyFlagMap[listenerID] |= flag;
                }
              };

              _proto2._sortNumberAsc = function _sortNumberAsc(a, b) {
                return a - b;
              };

              _proto2._removeListenerInCallback = function _removeListenerInCallback(listeners, callback) {
                if (listeners == null) {
                  return false;
                }

                for (var i = listeners.length - 1; i >= 0; i--) {
                  var selListener = listeners[i];

                  if (selListener._onCustomEvent === callback || selListener.onEvent === callback) {
                    selListener._setRegistered(false);

                    if (selListener._getSceneGraphPriority() != null) {
                      this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener);

                      selListener._setSceneGraphPriority(null);
                    }

                    if (this._inDispatch === 0) {
                      legacyCC.js.array.removeAt(listeners, i);
                    } else {
                      this._toRemovedListeners.push(selListener);
                    }

                    return true;
                  }
                }

                return false;
              };

              _proto2._removeListenerInVector = function _removeListenerInVector(listeners, listener) {
                if (listeners == null) {
                  return false;
                }

                for (var i = listeners.length - 1; i >= 0; i--) {
                  var selListener = listeners[i];

                  if (selListener === listener) {
                    selListener._setRegistered(false);

                    if (selListener._getSceneGraphPriority() != null) {
                      this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener);

                      selListener._setSceneGraphPriority(null);
                    }

                    if (this._inDispatch === 0) {
                      legacyCC.js.array.removeAt(listeners, i);
                    } else {
                      this._toRemovedListeners.push(selListener);
                    }

                    return true;
                  }
                }

                return false;
              };

              return EventManager;
            }();

            var eventManager = exports('eventManager', new EventManager());
            legacyCC.eventManager = eventManager;

            var Destroying$1 = CCObject.Flags.Destroying;

            var _dec$9, _class$9, _class2$8, _descriptor$6, _descriptor2$2, _descriptor3$2, _descriptor4$1, _descriptor5$1, _class3$5, _temp$8;
            var Destroying$2 = CCObject.Flags.Destroying;
            var DontDestroy$1 = CCObject.Flags.DontDestroy;
            var Deactivating$1 = CCObject.Flags.Deactivating;
            var TRANSFORM_ON = 1 << 0;
            var idGenerator$2 = new IDGenerator('Node');

            function getConstructor(typeOrClassName) {
              if (!typeOrClassName) {
                errorID(3804);
                return null;
              }

              if (typeof typeOrClassName === 'string') {
                return getClassByName(typeOrClassName);
              }

              return typeOrClassName;
            }

            var BaseNode = exports('BaseNode', (_dec$9 = ccclass('cc.BaseNode'), _dec$9(_class$9 = (_class2$8 = (_temp$8 = _class3$5 = function (_CCObject) {
              _inheritsLoose(BaseNode, _CCObject);

              BaseNode._setScene = function _setScene(node) {
                node._updateScene();
              };

              BaseNode._findComponent = function _findComponent(node, constructor) {
                var cls = constructor;
                var comps = node._components;

                if (cls._sealed) {
                  for (var i = 0; i < comps.length; ++i) {
                    var comp = comps[i];

                    if (comp.constructor === constructor) {
                      return comp;
                    }
                  }
                } else {
                  for (var _i = 0; _i < comps.length; ++_i) {
                    var _comp = comps[_i];

                    if (_comp instanceof constructor) {
                      return _comp;
                    }
                  }
                }

                return null;
              };

              BaseNode._findComponents = function _findComponents(node, constructor, components) {
                var cls = constructor;
                var comps = node._components;

                if (cls._sealed) {
                  for (var i = 0; i < comps.length; ++i) {
                    var comp = comps[i];

                    if (comp.constructor === constructor) {
                      components.push(comp);
                    }
                  }
                } else {
                  for (var _i2 = 0; _i2 < comps.length; ++_i2) {
                    var _comp2 = comps[_i2];

                    if (_comp2 instanceof constructor) {
                      components.push(_comp2);
                    }
                  }
                }
              };

              BaseNode._findChildComponent = function _findChildComponent(children, constructor) {
                for (var i = 0; i < children.length; ++i) {
                  var node = children[i];

                  var comp = BaseNode._findComponent(node, constructor);

                  if (comp) {
                    return comp;
                  }

                  if (node._children.length > 0) {
                    comp = BaseNode._findChildComponent(node._children, constructor);

                    if (comp) {
                      return comp;
                    }
                  }
                }

                return null;
              };

              BaseNode._findChildComponents = function _findChildComponents(children, constructor, components) {
                for (var i = 0; i < children.length; ++i) {
                  var node = children[i];

                  BaseNode._findComponents(node, constructor, components);

                  if (node._children.length > 0) {
                    BaseNode._findChildComponents(node._children, constructor, components);
                  }
                }
              };

              var _proto = BaseNode.prototype;

              _proto._updateScene = function _updateScene() {
                if (this._parent == null) {
                  error('Node %s(%s) has not attached to a scene.', this.name, this.uuid);
                } else {
                  this._scene = this._parent._scene;
                }
              };

              function BaseNode(name) {
                var _this;

                _this = _CCObject.call(this, name) || this;

                _initializerDefineProperty(_this, "_parent", _descriptor$6, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_children", _descriptor2$2, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_active", _descriptor3$2, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_components", _descriptor4$1, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_prefab", _descriptor5$1, _assertThisInitialized(_this));

                _this._scene = null;
                _this._activeInHierarchy = false;
                _this._id = idGenerator$2.getNewId();
                _this._name = void 0;
                _this._eventProcessor = new legacyCC.NodeEventProcessor(_assertThisInitialized(_this));
                _this._eventMask = 0;
                _this._siblingIndex = 0;
                _this._originalSceneId = '';
                _this._registerIfAttached =  undefined ;
                _this._name = name !== undefined ? name : 'New Node';
                return _this;
              }

              _proto.attr = function attr(attrs) {
                mixin(this, attrs);
              };

              _proto.getParent = function getParent() {
                return this._parent;
              };

              _proto.setParent = function setParent(value, keepWorldTransform) {
                if (keepWorldTransform === void 0) {
                  keepWorldTransform = false;
                }

                if (this._parent === value) {
                  return;
                }

                var oldParent = this._parent;
                var newParent = value;

                if ( oldParent && oldParent._objFlags & Deactivating$1) {
                  errorID(3821);
                }

                this._parent = newParent;
                this._siblingIndex = 0;

                this._onSetParent(oldParent, keepWorldTransform);

                if (this.emit) {
                  this.emit(SystemEventType.PARENT_CHANGED, oldParent);
                }

                if (oldParent) {
                  if (!(oldParent._objFlags & Destroying$2)) {
                    var removeAt = oldParent._children.indexOf(this);

                    oldParent._children.splice(removeAt, 1);

                    oldParent._updateSiblingIndex();

                    if (oldParent.emit) {
                      oldParent.emit(SystemEventType.CHILD_REMOVED, this);
                    }
                  }
                }

                if (newParent) {
                  if ( newParent._objFlags & Deactivating$1) {
                    errorID(3821);
                  }

                  newParent._children.push(this);

                  this._siblingIndex = newParent._children.length - 1;

                  if (newParent.emit) {
                    newParent.emit(SystemEventType.CHILD_ADDED, this);
                  }
                }

                this._onHierarchyChanged(oldParent);
              };

              _proto.getChildByUuid = function getChildByUuid(uuid) {
                if (!uuid) {
                  log('Invalid uuid');
                  return null;
                }

                var locChildren = this._children;

                for (var i = 0, len = locChildren.length; i < len; i++) {
                  if (locChildren[i]._id === uuid) {
                    return locChildren[i];
                  }
                }

                return null;
              };

              _proto.getChildByName = function getChildByName(name) {
                if (!name) {
                  log('Invalid name');
                  return null;
                }

                var locChildren = this._children;

                for (var i = 0, len = locChildren.length; i < len; i++) {
                  if (locChildren[i]._name === name) {
                    return locChildren[i];
                  }
                }

                return null;
              };

              _proto.getChildByPath = function getChildByPath(path) {
                var segments = path.split('/');
                var lastNode = this;

                var _loop = function _loop(i) {
                  var segment = segments[i];

                  if (segment.length === 0) {
                    return "continue";
                  }

                  var next = lastNode.children.find(function (childNode) {
                    return childNode.name === segment;
                  });

                  if (!next) {
                    return {
                      v: null
                    };
                  }

                  lastNode = next;
                };

                for (var i = 0; i < segments.length; ++i) {
                  var _ret = _loop(i);

                  if (_ret === "continue") continue;
                  if (typeof _ret === "object") return _ret.v;
                }

                return lastNode;
              };

              _proto.addChild = function addChild(child) {
                child.setParent(this);
              };

              _proto.insertChild = function insertChild(child, siblingIndex) {
                child.parent = this;
                child.setSiblingIndex(siblingIndex);
              };

              _proto.getSiblingIndex = function getSiblingIndex() {
                return this._siblingIndex;
              };

              _proto.setSiblingIndex = function setSiblingIndex(index) {
                if (!this._parent) {
                  return;
                }

                if (this._parent._objFlags & Deactivating$1) {
                  errorID(3821);
                  return;
                }

                var siblings = this._parent._children;
                index = index !== -1 ? index : siblings.length - 1;
                var oldIndex = siblings.indexOf(this);

                if (index !== oldIndex) {
                  siblings.splice(oldIndex, 1);

                  if (index < siblings.length) {
                    siblings.splice(index, 0, this);
                  } else {
                    siblings.push(this);
                  }

                  this._parent._updateSiblingIndex();

                  if (this._onSiblingIndexChanged) {
                    this._onSiblingIndexChanged(index);
                  }
                }
              };

              _proto.walk = function walk(preFunc, postFunc) {
                var index = 1;
                var children = null;
                var curr = null;
                var i = 0;
                var stack = BaseNode._stacks[BaseNode._stackId];

                if (!stack) {
                  stack = [];

                  BaseNode._stacks.push(stack);
                }

                BaseNode._stackId++;
                stack.length = 0;
                stack[0] = this;
                var parent = null;
                var afterChildren = false;

                while (index) {
                  index--;
                  curr = stack[index];

                  if (!curr) {
                    continue;
                  }

                  if (!afterChildren && preFunc) {
                    preFunc(curr);
                  } else if (afterChildren && postFunc) {
                    postFunc(curr);
                  }

                  stack[index] = null;

                  if (afterChildren) {
                    if (parent === this._parent) break;
                    afterChildren = false;
                  } else {
                    if (curr._children.length > 0) {
                      parent = curr;
                      children = curr._children;
                      i = 0;
                      stack[index] = children[i];
                      index++;
                    } else {
                      stack[index] = curr;
                      index++;
                      afterChildren = true;
                    }

                    continue;
                  }

                  if (children) {
                    i++;

                    if (children[i]) {
                      stack[index] = children[i];
                      index++;
                    } else if (parent) {
                      stack[index] = parent;
                      index++;
                      afterChildren = true;

                      if (parent._parent) {
                        children = parent._parent._children;
                        i = children.indexOf(parent);
                        parent = parent._parent;
                      } else {
                        parent = null;
                        children = null;
                      }

                      if (i < 0) {
                        break;
                      }
                    }
                  }
                }

                stack.length = 0;
                BaseNode._stackId--;
              };

              _proto.removeFromParent = function removeFromParent() {
                if (this._parent) {
                  this._parent.removeChild(this);
                }
              };

              _proto.removeChild = function removeChild(child) {
                if (this._children.indexOf(child) > -1) {
                  child.parent = null;
                }
              };

              _proto.removeAllChildren = function removeAllChildren() {
                var children = this._children;

                for (var i = children.length - 1; i >= 0; i--) {
                  var node = children[i];

                  if (node) {
                    node.parent = null;
                  }
                }

                this._children.length = 0;
              };

              _proto.isChildOf = function isChildOf(parent) {
                var child = this;

                do {
                  if (child === parent) {
                    return true;
                  }

                  child = child._parent;
                } while (child);

                return false;
              };

              _proto.getComponent = function getComponent(typeOrClassName) {
                var constructor = getConstructor(typeOrClassName);

                if (constructor) {
                  return BaseNode._findComponent(this, constructor);
                }

                return null;
              };

              _proto.getComponents = function getComponents(typeOrClassName) {
                var constructor = getConstructor(typeOrClassName);
                var components = [];

                if (constructor) {
                  BaseNode._findComponents(this, constructor, components);
                }

                return components;
              };

              _proto.getComponentInChildren = function getComponentInChildren(typeOrClassName) {
                var constructor = getConstructor(typeOrClassName);

                if (constructor) {
                  return BaseNode._findChildComponent(this._children, constructor);
                }

                return null;
              };

              _proto.getComponentsInChildren = function getComponentsInChildren(typeOrClassName) {
                var constructor = getConstructor(typeOrClassName);
                var components = [];

                if (constructor) {
                  BaseNode._findComponents(this, constructor, components);

                  BaseNode._findChildComponents(this._children, constructor, components);
                }

                return components;
              };

              _proto.addComponent = function addComponent(typeOrClassName) {

                var constructor;

                if (typeof typeOrClassName === 'string') {
                  constructor = getClassByName(typeOrClassName);

                  if (!constructor) {
                    if (legacyCC._RF.peek()) {
                      errorID(3808, typeOrClassName);
                    }

                    throw TypeError(getError(3807, typeOrClassName));
                  }
                } else {
                  if (!typeOrClassName) {
                    throw TypeError(getError(3804));
                  }

                  constructor = typeOrClassName;
                }

                if (typeof constructor !== 'function') {
                  throw TypeError(getError(3809));
                }

                if (!isChildClassOf(constructor, legacyCC.Component)) {
                  throw TypeError(getError(3810));
                }

                var ReqComp = constructor._requireComponent;

                if (ReqComp && !this.getComponent(ReqComp)) {
                  this.addComponent(ReqComp);
                }

                var component = new constructor();
                component.node = this;

                this._components.push(component);

                if (this._activeInHierarchy) {
                  legacyCC.director._nodeActivator.activateComp(component);
                }

                return component;
              };

              _proto.removeComponent = function removeComponent(component) {
                if (!component) {
                  errorID(3813);
                  return;
                }

                var componentInstance = null;

                if (component instanceof Component) {
                  componentInstance = component;
                } else {
                  componentInstance = this.getComponent(component);
                }

                if (componentInstance) {
                  componentInstance.destroy();
                }
              };

              _proto.on = function on(type, callback, target, useCapture) {
                if (useCapture === void 0) {
                  useCapture = false;
                }

                switch (type) {
                  case SystemEventType.TRANSFORM_CHANGED:
                    this._eventMask |= TRANSFORM_ON;
                    break;
                }

                this._eventProcessor.on(type, callback, target, useCapture);
              };

              _proto.off = function off(type, callback, target, useCapture) {
                if (useCapture === void 0) {
                  useCapture = false;
                }

                this._eventProcessor.off(type, callback, target, useCapture);

                var hasListeners = this._eventProcessor.hasEventListener(type);

                if (!hasListeners) {
                  switch (type) {
                    case SystemEventType.TRANSFORM_CHANGED:
                      this._eventMask &= ~TRANSFORM_ON;
                      break;
                  }
                }
              };

              _proto.once = function once(type, callback, target, useCapture) {
                this._eventProcessor.once(type, callback, target, useCapture);
              };

              _proto.emit = function emit(type, arg0, arg1, arg2, arg3, arg4) {
                this._eventProcessor.emit(type, arg0, arg1, arg2, arg3, arg4);
              };

              _proto.dispatchEvent = function dispatchEvent(event) {
                this._eventProcessor.dispatchEvent(event);
              };

              _proto.hasEventListener = function hasEventListener(type, callback, target) {
                return this._eventProcessor.hasEventListener(type, callback, target);
              };

              _proto.targetOff = function targetOff(target) {
                this._eventProcessor.targetOff(target);

                if (this._eventMask & TRANSFORM_ON && !this._eventProcessor.hasEventListener(SystemEventType.TRANSFORM_CHANGED)) {
                  this._eventMask &= ~TRANSFORM_ON;
                }
              };

              _proto.destroy = function destroy() {
                if (_CCObject.prototype.destroy.call(this)) {
                  this.active = false;
                  return true;
                }

                return false;
              };

              _proto.destroyAllChildren = function destroyAllChildren() {
                var children = this._children;

                for (var i = 0; i < children.length; ++i) {
                  children[i].destroy();
                }
              };

              _proto._removeComponent = function _removeComponent(component) {
                if (!component) {
                  errorID(3814);
                  return;
                }

                if (!(this._objFlags & Destroying$2)) {
                  var i = this._components.indexOf(component);

                  if (i !== -1) {
                    this._components.splice(i, 1);
                  } else if (component.node !== this) {
                    errorID(3815);
                  }
                }
              };

              _proto._updateSiblingIndex = function _updateSiblingIndex() {
                for (var i = 0; i < this._children.length; ++i) {
                  this._children[i]._siblingIndex = i;
                }

                this.emit(SystemEventType.SIBLING_ORDER_CHANGED);
              };

              _proto._onSetParent = function _onSetParent(oldParent, keepWorldTransform) {

                if (this._parent) {
                  if ((oldParent == null || oldParent._scene !== this._parent._scene) && this._parent._scene != null) {
                    this.walk(BaseNode._setScene);
                  }
                }
              };

              _proto._onPostActivated = function _onPostActivated(active) {};

              _proto._onBatchCreated = function _onBatchCreated(dontSyncChildPrefab) {
                if (this._parent) {
                  this._siblingIndex = this._parent.children.indexOf(this);
                }
              };

              _proto._onPreDestroy = function _onPreDestroy() {
                this._onPreDestroyBase();
              };

              _proto._onHierarchyChanged = function _onHierarchyChanged(oldParent) {
                return this._onHierarchyChangedBase(oldParent);
              };

              _proto._instantiate = function _instantiate(cloned, isSyncedNode) {
                if (!cloned) {
                  cloned = legacyCC.instantiate._clone(this, this);
                }

                var newPrefabInfo = cloned._prefab;

                cloned._parent = null;

                cloned._onBatchCreated(isSyncedNode);

                return cloned;
              };

              _proto._onHierarchyChangedBase = function _onHierarchyChangedBase(oldParent) {
                var newParent = this._parent;

                if (this._persistNode && !(newParent instanceof legacyCC.Scene)) {
                  legacyCC.game.removePersistRootNode(this);
                }

                var shouldActiveNow = this._active && !!(newParent && newParent._activeInHierarchy);

                if (this._activeInHierarchy !== shouldActiveNow) {
                  legacyCC.director._nodeActivator.activateNode(this, shouldActiveNow);
                }
              };

              _proto._onPreDestroyBase = function _onPreDestroyBase() {
                this._objFlags |= Destroying$2;
                var parent = this._parent;
                var destroyByParent = !!parent && (parent._objFlags & Destroying$2) !== 0;

                if (!destroyByParent && EDITOR) {
                  this._registerIfAttached(false);
                }

                if (this._persistNode) {
                  legacyCC.game.removePersistRootNode(this);
                }

                if (!destroyByParent) {
                  if (parent) {
                    this.emit(SystemEventType.PARENT_CHANGED, this);

                    var childIndex = parent._children.indexOf(this);

                    parent._children.splice(childIndex, 1);

                    this._siblingIndex = 0;

                    parent._updateSiblingIndex();

                    if (parent.emit) {
                      parent.emit(SystemEventType.CHILD_REMOVED, this);
                    }
                  }
                }

                this.emit(SystemEventType.NODE_DESTROYED, this);

                this._eventProcessor.destroy();

                var children = this._children;

                for (var i = 0; i < children.length; ++i) {
                  children[i]._destroyImmediate();
                }

                var comps = this._components;

                for (var _i5 = 0; _i5 < comps.length; ++_i5) {
                  comps[_i5]._destroyImmediate();
                }

                return destroyByParent;
              };

              _createClass(BaseNode, [{
                key: "components",
                get: function get() {
                  return this._components;
                }
              }, {
                key: "_persistNode",
                get: function get() {
                  return (this._objFlags & DontDestroy$1) > 0;
                },
                set: function set(value) {
                  if (value) {
                    this._objFlags |= DontDestroy$1;
                  } else {
                    this._objFlags &= ~DontDestroy$1;
                  }
                }
              }, {
                key: "name",
                get: function get() {
                  return this._name;
                },
                set: function set(value) {

                  this._name = value;
                }
              }, {
                key: "uuid",
                get: function get() {
                  return this._id;
                }
              }, {
                key: "children",
                get: function get() {
                  return this._children;
                }
              }, {
                key: "active",
                get: function get() {
                  return this._active;
                },
                set: function set(isActive) {
                  if (this._active !== isActive) {
                    this._active = isActive;
                    var parent = this._parent;

                    if (parent) {
                      var couldActiveInScene = parent._activeInHierarchy;

                      if (couldActiveInScene) {
                        legacyCC.director._nodeActivator.activateNode(this, isActive);
                      }
                    }
                  }
                }
              }, {
                key: "activeInHierarchy",
                get: function get() {
                  return this._activeInHierarchy;
                }
              }, {
                key: "parent",
                get: function get() {
                  return this._parent;
                },
                set: function set(value) {
                  this.setParent(value);
                }
              }, {
                key: "scene",
                get: function get() {
                  return this._scene;
                }
              }, {
                key: "eventProcessor",
                get: function get() {
                  return this._eventProcessor;
                }
              }]);

              return BaseNode;
            }(CCObject), _class3$5.idGenerator = idGenerator$2, _class3$5._stacks = [[]], _class3$5._stackId = 0, _temp$8), (_applyDecoratedDescriptor(_class2$8.prototype, "_persistNode", [property], Object.getOwnPropertyDescriptor(_class2$8.prototype, "_persistNode"), _class2$8.prototype), _applyDecoratedDescriptor(_class2$8.prototype, "name", [editable], Object.getOwnPropertyDescriptor(_class2$8.prototype, "name"), _class2$8.prototype), _applyDecoratedDescriptor(_class2$8.prototype, "children", [editable], Object.getOwnPropertyDescriptor(_class2$8.prototype, "children"), _class2$8.prototype), _applyDecoratedDescriptor(_class2$8.prototype, "active", [editable], Object.getOwnPropertyDescriptor(_class2$8.prototype, "active"), _class2$8.prototype), _applyDecoratedDescriptor(_class2$8.prototype, "activeInHierarchy", [editable], Object.getOwnPropertyDescriptor(_class2$8.prototype, "activeInHierarchy"), _class2$8.prototype), _applyDecoratedDescriptor(_class2$8.prototype, "parent", [editable], Object.getOwnPropertyDescriptor(_class2$8.prototype, "parent"), _class2$8.prototype), _descriptor$6 = _applyDecoratedDescriptor(_class2$8.prototype, "_parent", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor2$2 = _applyDecoratedDescriptor(_class2$8.prototype, "_children", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor3$2 = _applyDecoratedDescriptor(_class2$8.prototype, "_active", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _descriptor4$1 = _applyDecoratedDescriptor(_class2$8.prototype, "_components", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor5$1 = _applyDecoratedDescriptor(_class2$8.prototype, "_prefab", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            })), _class2$8)) || _class$9));
            legacyCC._BaseNode = BaseNode;

            var _decorator = /*#__PURE__*/Object.freeze({
                __proto__: null,
                ccclass: ccclass,
                property: property,
                requireComponent: requireComponent,
                executionOrder: executionOrder,
                disallowMultiple: disallowMultiple,
                executeInEditMode: executeInEditMode,
                menu: menu,
                playOnFocus: playOnFocus,
                inspector: inspector,
                icon: icon,
                help: help,
                type: type,
                integer: integer,
                float: _float,
                boolean: _boolean,
                string: string
            });
            exports('_decorator', _decorator);

            var Destroyed$2 = CCObject.Flags.Destroyed;
            var PersistentMask$2 = CCObject.Flags.PersistentMask;
            var objsToClearTmpVar = [];
            function instantiate(original, internalForce) {

              var clone;

              if (original instanceof CCObject) {
                if (original._instantiate) {
                  legacyCC.game._isCloning = true;
                  clone = original._instantiate(null, true);
                  legacyCC.game._isCloning = false;
                  return clone;
                } else if (original instanceof legacyCC.Asset) {
                  throw new TypeError(getError(6903));
                }
              }

              legacyCC.game._isCloning = true;
              clone = doInstantiate(original);
              legacyCC.game._isCloning = false;
              return clone;
            }

            function doInstantiate(obj, parent) {

              var clone;

              if (obj._iN$t) {
                clone = obj._iN$t;
              } else if (obj.constructor) {
                var klass = obj.constructor;
                clone = new klass();
              } else {
                clone = Object.create(null);
              }

              enumerateObject(obj, clone, parent);

              for (var i = 0, len = objsToClearTmpVar.length; i < len; ++i) {
                objsToClearTmpVar[i]._iN$t = null;
              }

              objsToClearTmpVar.length = 0;
              return clone;
            }

            function enumerateCCClass(klass, obj, clone, parent) {
              var props = klass.__values__;

              for (var p = 0; p < props.length; p++) {
                var key = props[p];
                var value = obj[key];

                if (typeof value === 'object' && value) {
                  var initValue = clone[key];

                  if (initValue instanceof ValueType && initValue.constructor === value.constructor) {
                    initValue.set(value);
                  } else {
                    clone[key] = value._iN$t || instantiateObj(value, parent);
                  }
                } else {
                  clone[key] = value;
                }
              }
            }

            function enumerateObject(obj, clone, parent) {
              js.value(obj, '_iN$t', clone, true);
              objsToClearTmpVar.push(obj);
              var klass = obj.constructor;

              if (legacyCC.Class._isCCClass(klass)) {
                enumerateCCClass(klass, obj, clone, parent);
              } else {
                for (var key in obj) {
                  if (!obj.hasOwnProperty(key) || key.charCodeAt(0) === 95 && key.charCodeAt(1) === 95 && key !== '__type__') {
                    continue;
                  }

                  var 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 (obj instanceof CCObject) {
                clone._objFlags &= PersistentMask$2;
              }
            }

            function instantiateObj(obj, parent) {
              if (obj instanceof ValueType) {
                return obj.clone();
              }

              if (obj instanceof legacyCC.Asset) {
                return obj;
              }

              var clone;

              if (ArrayBuffer.isView(obj)) {
                var len = obj.length;
                clone = new obj.constructor(len);
                obj._iN$t = clone;
                objsToClearTmpVar.push(obj);

                for (var i = 0; i < len; ++i) {
                  clone[i] = obj[i];
                }

                return clone;
              }

              if (Array.isArray(obj)) {
                var _len = obj.length;
                clone = new Array(_len);
                obj._iN$t = clone;
                objsToClearTmpVar.push(obj);

                for (var _i = 0; _i < _len; ++_i) {
                  var value = obj[_i];

                  if (typeof value === 'object' && value) {
                    clone[_i] = value._iN$t || instantiateObj(value, parent);
                  } else {
                    clone[_i] = value;
                  }
                }

                return clone;
              } else if (obj._objFlags & Destroyed$2) {
                return null;
              }

              var ctor = obj.constructor;

              if (legacyCC.Class._isCCClass(ctor)) {
                if (parent) {
                  if (parent instanceof legacyCC.Component) {
                    if (obj instanceof legacyCC._BaseNode || obj instanceof legacyCC.Component) {
                      return obj;
                    }
                  } else if (parent instanceof legacyCC._BaseNode) {
                    if (obj instanceof legacyCC._BaseNode) {
                      if (!obj.isChildOf(parent)) {
                        return obj;
                      }
                    } else if (obj instanceof legacyCC.Component) {
                      if (obj.node && !obj.node.isChildOf(parent)) {
                        return obj;
                      }
                    }
                  }
                }

                clone = new ctor();
              } else if (ctor === Object) {
                clone = {};
              } else if (!ctor) {
                clone = Object.create(null);
              } else {
                return obj;
              }

              enumerateObject(obj, clone, parent);
              return clone;
            }

            instantiate._clone = doInstantiate;
            legacyCC.instantiate = instantiate;

            var _dec$a, _class$a, _class2$9, _descriptor$7, _descriptor2$3, _descriptor3$3, _descriptor4$2, _class3$6, _temp$9, _BuiltinElementTypeTr;
            var StorageUnit;

            (function (StorageUnit) {
              StorageUnit[StorageUnit["Uint8"] = 0] = "Uint8";
              StorageUnit[StorageUnit["Uint16"] = 1] = "Uint16";
              StorageUnit[StorageUnit["Uint32"] = 2] = "Uint32";
              StorageUnit[StorageUnit["Int8"] = 3] = "Int8";
              StorageUnit[StorageUnit["Int16"] = 4] = "Int16";
              StorageUnit[StorageUnit["Int32"] = 5] = "Int32";
              StorageUnit[StorageUnit["Float32"] = 6] = "Float32";
              StorageUnit[StorageUnit["Float64"] = 7] = "Float64";
            })(StorageUnit || (StorageUnit = {}));

            var ElementType;

            (function (ElementType) {
              ElementType[ElementType["Scalar"] = 0] = "Scalar";
              ElementType[ElementType["Vec2"] = 1] = "Vec2";
              ElementType[ElementType["Vec3"] = 2] = "Vec3";
              ElementType[ElementType["Vec4"] = 3] = "Vec4";
              ElementType[ElementType["Quat"] = 4] = "Quat";
              ElementType[ElementType["Mat4"] = 5] = "Mat4";
            })(ElementType || (ElementType = {}));

            var elementTypeBits = 3;
            function combineStorageUnitElementType(unit, elementType) {
              return (elementType << elementTypeBits) + unit;
            }
            function extractStorageUnitElementType(combined) {
              return {
                storageUnit: ~(-1 << elementTypeBits) & combined,
                elementType: combined >> elementTypeBits
              };
            }
            var CompactValueTypeArray = exports('CompactValueTypeArray', (_dec$a = ccclass('cc.CompactValueTypeArray'), _dec$a(_class$a = (_class2$9 = (_temp$9 = _class3$6 = function () {
              function CompactValueTypeArray() {
                _initializerDefineProperty(this, "_byteOffset", _descriptor$7, this);

                _initializerDefineProperty(this, "_unitCount", _descriptor2$3, this);

                _initializerDefineProperty(this, "_unitElement", _descriptor3$3, this);

                _initializerDefineProperty(this, "_length", _descriptor4$2, this);
              }

              CompactValueTypeArray.lengthFor = function lengthFor(values, elementType, unit) {
                var elementTraits = getElementTraits(elementType);
                return elementTraits.requiredUnits * values.length * getStorageConstructor(unit).BYTES_PER_ELEMENT;
              };

              CompactValueTypeArray.compress = function compress(values, elementType, unit, arrayBuffer, byteOffset, presumedByteOffset) {
                var elementTraits = getElementTraits(elementType);
                var storageConstructor = getStorageConstructor(unit);
                var unitCount = elementTraits.requiredUnits * values.length;
                var storage = new storageConstructor(arrayBuffer, byteOffset, unitCount);

                for (var i = 0; i < values.length; ++i) {
                  elementTraits.compress(storage, i, values[i]);
                }

                var result = new CompactValueTypeArray();
                result._unitElement = combineStorageUnitElementType(unit, elementType);
                result._byteOffset = presumedByteOffset;
                result._unitCount = unitCount;
                result._length = values.length;
                return result;
              };

              var _proto = CompactValueTypeArray.prototype;

              _proto.decompress = function decompress(arrayBuffer) {
                var _extractStorageUnitEl = extractStorageUnitElementType(this._unitElement),
                    storageUnit = _extractStorageUnitEl.storageUnit,
                    elementType = _extractStorageUnitEl.elementType;

                var elementTraits = getElementTraits(elementType);
                var storageConstructor = getStorageConstructor(storageUnit);
                var storage = new storageConstructor(arrayBuffer, this._byteOffset, this._unitCount);
                var result = new Array(this._length);

                for (var i = 0; i < this._length; ++i) {
                  result[i] = elementTraits.decompress(storage, i);
                }

                return result;
              };

              return CompactValueTypeArray;
            }(), _class3$6.StorageUnit = StorageUnit, _class3$6.ElementType = ElementType, _temp$9), (_descriptor$7 = _applyDecoratedDescriptor(_class2$9.prototype, "_byteOffset", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor2$3 = _applyDecoratedDescriptor(_class2$9.prototype, "_unitCount", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor3$3 = _applyDecoratedDescriptor(_class2$9.prototype, "_unitElement", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return combineStorageUnitElementType(StorageUnit.Uint8, ElementType.Scalar);
              }
            }), _descriptor4$2 = _applyDecoratedDescriptor(_class2$9.prototype, "_length", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            })), _class2$9)) || _class$a));

            function getElementTraits(elementType) {
              return BuiltinElementTypeTraits[elementType];
            }

            function getStorageConstructor(unit) {
              switch (unit) {
                case StorageUnit.Uint8:
                  return Uint8Array;

                case StorageUnit.Uint16:
                  return Uint16Array;

                case StorageUnit.Uint32:
                  return Uint32Array;

                case StorageUnit.Int8:
                  return Int8Array;

                case StorageUnit.Int16:
                  return Int16Array;

                case StorageUnit.Int32:
                  return Int32Array;

                case StorageUnit.Float32:
                  return Float32Array;

                case StorageUnit.Float64:
                  return Float64Array;
              }
            }

            var BuiltinElementTypeTraits = (_BuiltinElementTypeTr = {}, _BuiltinElementTypeTr[ElementType.Scalar] = {
              requiredUnits: 1,
              compress: function compress(storage, index, value) {
                storage[index] = value;
              },
              decompress: function decompress(storage, index) {
                return storage[index];
              }
            }, _BuiltinElementTypeTr[ElementType.Vec2] = {
              requiredUnits: 2,
              compress: function compress(storage, index, value) {
                storage[index * 2] = value.x;
                storage[index * 2 + 1] = value.y;
              },
              decompress: function decompress(storage, index) {
                return new Vec3(storage[index * 2], storage[index * 2 + 1]);
              }
            }, _BuiltinElementTypeTr[ElementType.Vec3] = {
              requiredUnits: 3,
              compress: function compress(storage, index, value) {
                storage[index * 3] = value.x;
                storage[index * 3 + 1] = value.y;
                storage[index * 3 + 2] = value.z;
              },
              decompress: function decompress(storage, index) {
                return new Vec3(storage[index * 3], storage[index * 3 + 1], storage[index * 3 + 2]);
              }
            }, _BuiltinElementTypeTr[ElementType.Vec4] = {
              requiredUnits: 4,
              compress: function compress(storage, index, value) {
                storage[index * 4] = value.x;
                storage[index * 4 + 1] = value.y;
                storage[index * 4 + 2] = value.z;
                storage[index * 4 + 3] = value.w;
              },
              decompress: function decompress(storage, index) {
                return new Vec4(storage[index * 4], storage[index * 4 + 1], storage[index * 4 + 2], storage[index * 4 + 3]);
              }
            }, _BuiltinElementTypeTr[ElementType.Quat] = {
              requiredUnits: 4,
              compress: function compress(storage, index, value) {
                storage[index * 4] = value.x;
                storage[index * 4 + 1] = value.y;
                storage[index * 4 + 2] = value.z;
                storage[index * 4 + 3] = value.w;
              },
              decompress: function decompress(storage, index) {
                return new Quat(storage[index * 4], storage[index * 4 + 1], storage[index * 4 + 2], storage[index * 4 + 3]);
              }
            }, _BuiltinElementTypeTr[ElementType.Mat4] = {
              requiredUnits: 16,
              compress: function compress(storage, index, value) {
                Mat4.toArray(storage, value, index * 16);
              },
              decompress: function decompress(storage, index) {
                return Mat4.fromArray(new Mat4(), storage, index * 16);
              }
            }, _BuiltinElementTypeTr);

            legacyCC._decorator = _decorator;

            function createNodeWithPrefab(node) {
              var prefabInfo = node._prefab;

              if (!prefabInfo) {
                return;
              }

              var prefabInstance = prefabInfo.instance;

              if (!prefabInstance) {
                return;
              }

              if (!prefabInfo.asset) {
                {
                  errorID(3701, node.name);
                }

                prefabInfo.instance = undefined;
                return;
              }

              var _objFlags = node._objFlags;
              var _parent = node._parent;
              var _id = node._id;
              var _prefab = node._prefab;
              legacyCC.game._isCloning = true;

              {
                prefabInfo.asset._doInstantiate(node);
              }

              legacyCC.game._isCloning = false;
              node._objFlags = _objFlags;
              node._parent = _parent;
              node._id = _id;

              if (node._prefab) {
                node._prefab.instance = _prefab === null || _prefab === void 0 ? void 0 : _prefab.instance;
              }
            }
            function generateTargetMap(node, targetMap, isRoot) {
              var _node$_prefab;

              if (!targetMap) {
                return;
              }

              var curTargetMap = targetMap;
              var prefabInstance = (_node$_prefab = node._prefab) === null || _node$_prefab === void 0 ? void 0 : _node$_prefab.instance;

              if (!isRoot && prefabInstance) {
                targetMap[prefabInstance.fileId] = {};
                curTargetMap = targetMap[prefabInstance.fileId];
              }

              var prefabInfo = node._prefab;

              if (prefabInfo) {
                curTargetMap[prefabInfo.fileId] = node;
              }

              var components = node.components;

              for (var i = 0; i < components.length; i++) {
                var comp = components[i];

                if (comp.__prefab) {
                  curTargetMap[comp.__prefab.fileId] = comp;
                }
              }

              for (var _i = 0; _i < node.children.length; _i++) {
                var childNode = node.children[_i];
                generateTargetMap(childNode, curTargetMap, false);
              }
            }
            function getTarget(localID, targetMap) {
              if (!localID) {
                return null;
              }

              var target = null;
              var targetIter = targetMap;

              for (var i = 0; i < localID.length; i++) {
                if (!targetIter) {
                  return null;
                }

                targetIter = targetIter[localID[i]];
              }

              target = targetIter;
              return target;
            }
            function applyMountedChildren(node, mountedChildren, targetMap) {
              if (!mountedChildren) {
                return;
              }

              for (var i = 0; i < mountedChildren.length; i++) {
                var childInfo = mountedChildren[i];

                if (childInfo && childInfo.targetInfo) {
                  var target = getTarget(childInfo.targetInfo.localID, targetMap);

                  if (!target) {
                    continue;
                  }

                  var curTargetMap = targetMap;
                  var localID = childInfo.targetInfo.localID;

                  if (localID.length > 0) {
                    for (var _i2 = 0; _i2 < localID.length - 1; _i2++) {
                      curTargetMap = curTargetMap[localID[_i2]];
                    }
                  }

                  if (childInfo.nodes) {
                    for (var _i3 = 0; _i3 < childInfo.nodes.length; _i3++) {
                      var childNode = childInfo.nodes[_i3];

                      if (!childNode) {
                        continue;
                      }

                      target._children.push(childNode);

                      childNode._parent = target;

                      generateTargetMap(childNode, curTargetMap, false);
                      childNode._siblingIndex = target._children.length - 1;

                      childNode._onBatchCreated(false);
                    }
                  }
                }
              }
            }
            function applyMountedComponents(node, mountedComponents, targetMap) {
              if (!mountedComponents) {
                return;
              }

              for (var i = 0; i < mountedComponents.length; i++) {
                var componentsInfo = mountedComponents[i];

                if (componentsInfo && componentsInfo.targetInfo) {
                  var target = getTarget(componentsInfo.targetInfo.localID, targetMap);

                  if (!target) {
                    continue;
                  }

                  if (componentsInfo.components) {
                    for (var _i4 = 0; _i4 < componentsInfo.components.length; _i4++) {
                      var comp = componentsInfo.components[_i4];

                      if (!comp) {
                        continue;
                      }

                      comp.node = target;

                      target._components.push(comp);
                    }
                  }
                }
              }
            }
            function applyRemovedComponents(node, removedComponents, targetMap) {
              if (!removedComponents) {
                return;
              }

              for (var i = 0; i < removedComponents.length; i++) {
                var targetInfo = removedComponents[i];

                if (targetInfo) {
                  var target = getTarget(targetInfo.localID, targetMap);

                  if (!target || !target.node) {
                    continue;
                  }

                  var index = target.node.components.indexOf(target);

                  if (index >= 0) {
                    target.node._components.splice(index, 1);
                  }
                }
              }
            }
            function applyPropertyOverrides(node, propertyOverrides, targetMap) {
              if (propertyOverrides.length <= 0) {
                return;
              }

              var target = null;

              for (var i = 0; i < propertyOverrides.length; i++) {
                var propOverride = propertyOverrides[i];

                if (propOverride && propOverride.targetInfo) {
                  var targetInfo = propOverride.targetInfo;
                  target = getTarget(targetInfo.localID, targetMap);

                  if (!target) {
                    continue;
                  }

                  var targetPropOwner = target;
                  var propertyPath = propOverride.propertyPath.slice();

                  if (propertyPath.length > 0) {
                    var targetPropName = propertyPath.pop();

                    if (!targetPropName) {
                      continue;
                    }

                    for (var _i5 = 0; _i5 < propertyPath.length; _i5++) {
                      var propName = propertyPath[_i5];
                      targetPropOwner = targetPropOwner[propName];

                      if (!targetPropOwner) {
                        break;
                      }
                    }

                    if (!targetPropOwner) {
                      continue;
                    }

                    if (Array.isArray(targetPropOwner)) {
                      if (targetPropName === 'length') {
                        targetPropOwner[targetPropName] = propOverride.value;
                      } else {
                        var index = Number.parseInt(targetPropName);

                        if (Number.isInteger(index) && index < targetPropOwner.length) {
                          targetPropOwner[targetPropName] = propOverride.value;
                        }
                      }
                    } else {
                      targetPropOwner[targetPropName] = propOverride.value;
                    }
                  }
                }
              }
            }
            function applyTargetOverrides(node) {
              var _node$_prefab2;

              var targetOverrides = (_node$_prefab2 = node._prefab) === null || _node$_prefab2 === void 0 ? void 0 : _node$_prefab2.targetOverrides;

              if (targetOverrides) {
                for (var i = 0; i < targetOverrides.length; i++) {
                  var _targetOverride$targe, _targetOverride$targe2;

                  var targetOverride = targetOverrides[i];
                  var source = targetOverride.source;
                  var sourceInfo = targetOverride.sourceInfo;

                  if (sourceInfo) {
                    var _targetOverride$sourc, _targetOverride$sourc2;

                    var sourceInstance = (_targetOverride$sourc = targetOverride.source) === null || _targetOverride$sourc === void 0 ? void 0 : (_targetOverride$sourc2 = _targetOverride$sourc._prefab) === null || _targetOverride$sourc2 === void 0 ? void 0 : _targetOverride$sourc2.instance;

                    if (sourceInstance && sourceInstance.targetMap) {
                      source = getTarget(sourceInfo.localID, sourceInstance.targetMap);
                    }
                  }

                  if (!source) {
                    continue;
                  }

                  var target = null;
                  var targetInfo = targetOverride.targetInfo;

                  if (!targetInfo) {
                    continue;
                  }

                  var targetInstance = (_targetOverride$targe = targetOverride.target) === null || _targetOverride$targe === void 0 ? void 0 : (_targetOverride$targe2 = _targetOverride$targe._prefab) === null || _targetOverride$targe2 === void 0 ? void 0 : _targetOverride$targe2.instance;

                  if (!targetInstance || !targetInstance.targetMap) {
                    continue;
                  }

                  target = getTarget(targetInfo.localID, targetInstance.targetMap);

                  if (!target) {
                    continue;
                  }

                  var propertyPath = targetOverride.propertyPath.slice();
                  var targetPropOwner = source;

                  if (propertyPath.length > 0) {
                    var targetPropName = propertyPath.pop();

                    if (!targetPropName) {
                      return;
                    }

                    for (var _i6 = 0; _i6 < propertyPath.length; _i6++) {
                      var propName = propertyPath[_i6];
                      targetPropOwner = targetPropOwner[propName];

                      if (!targetPropOwner) {
                        break;
                      }
                    }

                    if (!targetPropOwner) {
                      continue;
                    }

                    targetPropOwner[targetPropName] = target;
                  }
                }
              }
            }

            var _dec$b, _dec2$4, _class$b, _class2$a, _descriptor$8, _descriptor2$4, _descriptor3$4, _descriptor4$3, _descriptor5$2, _class3$7, _temp$a;
            var v3_a = new Vec3();
            var q_a = new Quat();
            var q_b = new Quat();
            var qt_1$1 = new Quat();
            var m3_1$2 = new Mat3();
            var m3_scaling = new Mat3();
            var m4_1 = new Mat4();
            var array_a = [];

            var BookOfChange = function () {
              function BookOfChange() {
                this._chunkHandles = [];
                this._chunks = [];
                this._freelists = [];

                this._createChunk();
              }

              var _proto = BookOfChange.prototype;

              _proto.alloc = function alloc() {
                var chunkCount = this._freelists.length;

                for (var i = 0; i < chunkCount; ++i) {
                  if (!this._freelists[i].length) continue;
                  return this._createView(i);
                }

                this._createChunk();

                return this._createView(chunkCount);
              };

              _proto.free = function free(view, idx) {
                var chunkCount = this._freelists.length;

                for (var i = 0; i < chunkCount; ++i) {
                  if (this._chunks[i] !== view) continue;

                  this._freelists[i].push(idx);

                  return;
                }
              };

              _proto.clear = function clear() {
                var chunkCount = this._chunks.length;

                for (var i = 0; i < chunkCount; ++i) {
                  this._chunks[i].fill(0);
                }
              };

              _proto._createChunk = function _createChunk() {
                var handle = RawBufferPool.alloc(BookOfChange.CAPACITY_PER_CHUNK * 4);

                this._chunkHandles.push(handle);

                this._chunks.push(new Uint32Array(RawBufferPool.getBuffer(handle)));

                var freelist = [];

                for (var i = 0; i < BookOfChange.CAPACITY_PER_CHUNK; ++i) {
                  freelist.push(i);
                }

                this._freelists.push(freelist);
              };

              _proto._createView = function _createView(chunkIdx) {
                var chunk = this._chunks[chunkIdx];

                var offset = this._freelists[chunkIdx].pop();

                var handle = this._chunkHandles[chunkIdx];
                handle += offset << BookOfChange.BIT_SHIFT;
                return [chunk, offset, handle];
              };

              return BookOfChange;
            }();

            BookOfChange.CAPACITY_PER_CHUNK = 256;
            BookOfChange.BIT_SHIFT = 16;
            var bookOfChange = new BookOfChange();
            var Node$1 = exports('Node', (_dec$b = ccclass('cc.Node'), _dec2$4 = type(Vec3), _dec$b(_class$b = (_class2$a = (_temp$a = _class3$7 = function (_BaseNode) {
              _inheritsLoose(Node, _BaseNode);

              function Node(name) {
                var _this;

                _this = _BaseNode.call(this, name) || this;
                _this._uiProps = new NodeUIProperties(_assertThisInitialized(_this));
                _this._static = false;
                _this._pos = new Vec3();
                _this._rot = new Quat();
                _this._scale = new Vec3(1, 1, 1);
                _this._mat = new Mat4();

                _initializerDefineProperty(_this, "_lpos", _descriptor$8, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_lrot", _descriptor2$4, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_lscale", _descriptor3$4, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_layer", _descriptor4$3, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_euler", _descriptor5$2, _assertThisInitialized(_this));

                _this._dirtyFlags = TransformBit.NONE;
                _this._hasChangedFlagsChunk = void 0;
                _this._hasChangedFlagsOffset = void 0;
                _this._eulerDirty = false;
                _this._poolHandle = NULL_HANDLE;
                _this._poolHandle = NodePool.alloc();
                NodePool.set(_this._poolHandle, NodeView.LAYER, _this._layer);

                var _bookOfChange$alloc = bookOfChange.alloc(),
                    chunk = _bookOfChange$alloc[0],
                    offset = _bookOfChange$alloc[1],
                    handle = _bookOfChange$alloc[2];

                _this._hasChangedFlagsChunk = chunk;
                _this._hasChangedFlagsOffset = offset;
                NodePool.set(_this._poolHandle, NodeView.HAS_CHANGED_FLAGS, handle);
                return _this;
              }

              Node.isNode = function isNode(obj) {
                return obj instanceof Node && (obj.constructor === Node || !(obj instanceof legacyCC.Scene));
              };

              var _proto2 = Node.prototype;

              _proto2.destroy = function destroy() {
                if (this._poolHandle) {
                  NodePool.free(this._poolHandle);
                  this._poolHandle = NULL_HANDLE;
                }

                bookOfChange.free(this._hasChangedFlagsChunk, this._hasChangedFlagsOffset);
                return _BaseNode.prototype.destroy.call(this);
              };

              _proto2.setParent = function setParent(value, keepWorldTransform) {
                if (keepWorldTransform === void 0) {
                  keepWorldTransform = false;
                }

                if (keepWorldTransform) {
                  this.updateWorldTransform();
                }

                _BaseNode.prototype.setParent.call(this, value, keepWorldTransform);
              };

              _proto2._onSetParent = function _onSetParent(oldParent, keepWorldTransform) {
                _BaseNode.prototype._onSetParent.call(this, oldParent, keepWorldTransform);

                if (keepWorldTransform) {
                  var parent = this._parent;

                  if (parent) {
                    parent.updateWorldTransform();
                    Mat4.multiply(m4_1, Mat4.invert(m4_1, parent._mat), this._mat);
                    Mat4.toRTS(m4_1, this._lrot, this._lpos, this._lscale);
                  } else {
                    Vec3.copy(this._lpos, this._pos);
                    Quat.copy(this._lrot, this._rot);
                    Vec3.copy(this._lscale, this._scale);
                  }

                  this._eulerDirty = true;
                }

                this.invalidateChildren(TransformBit.TRS);
              };

              _proto2._onHierarchyChanged = function _onHierarchyChanged(oldParent) {
                this.eventProcessor.reattach();

                _BaseNode.prototype._onHierarchyChangedBase.call(this, oldParent);
              };

              _proto2._onBatchCreated = function _onBatchCreated(dontSyncChildPrefab) {
                var _this$_prefab;

                NodePool.set(this._poolHandle, NodeView.LAYER, this._layer);
                NodePool.setVec3(this._poolHandle, NodeView.WORLD_SCALE, this._scale);
                var prefabInstance = (_this$_prefab = this._prefab) === null || _this$_prefab === void 0 ? void 0 : _this$_prefab.instance;

                if (!dontSyncChildPrefab && prefabInstance) {
                  createNodeWithPrefab(this);
                }

                this.hasChangedFlags = TransformBit.TRS;
                this._dirtyFlags = TransformBit.TRS;
                this._uiProps.uiTransformDirty = true;
                var len = this._children.length;

                for (var i = 0; i < len; ++i) {
                  this._children[i]._siblingIndex = i;

                  this._children[i]._onBatchCreated(dontSyncChildPrefab);
                }

                if (!dontSyncChildPrefab && prefabInstance) {
                  var targetMap = {};
                  prefabInstance.targetMap = targetMap;
                  generateTargetMap(this, targetMap, true);
                  applyMountedChildren(this, prefabInstance.mountedChildren, targetMap);
                  applyRemovedComponents(this, prefabInstance.removedComponents, targetMap);
                  applyMountedComponents(this, prefabInstance.mountedComponents, targetMap);
                  applyPropertyOverrides(this, prefabInstance.propertyOverrides, targetMap);
                }

                applyTargetOverrides(this);
              };

              _proto2._onBeforeSerialize = function _onBeforeSerialize() {
                this.eulerAngles;
              };

              _proto2._onPostActivated = function _onPostActivated(active) {
                if (active) {
                  eventManager.resumeTarget(this);
                  this.invalidateChildren(TransformBit.TRS);
                } else {
                  eventManager.pauseTarget(this);
                }
              };

              _proto2.translate = function translate(trans, ns) {
                var space = ns || NodeSpace.LOCAL;

                if (space === NodeSpace.LOCAL) {
                  Vec3.transformQuat(v3_a, trans, this._lrot);
                  this._lpos.x += v3_a.x;
                  this._lpos.y += v3_a.y;
                  this._lpos.z += v3_a.z;
                } else if (space === NodeSpace.WORLD) {
                  if (this._parent) {
                    Quat.invert(q_a, this._parent.worldRotation);
                    Vec3.transformQuat(v3_a, trans, q_a);
                    var _scale = this.worldScale;
                    this._lpos.x += v3_a.x / _scale.x;
                    this._lpos.y += v3_a.y / _scale.y;
                    this._lpos.z += v3_a.z / _scale.z;
                  } else {
                    this._lpos.x += trans.x;
                    this._lpos.y += trans.y;
                    this._lpos.z += trans.z;
                  }
                }

                this.invalidateChildren(TransformBit.POSITION);

                if (this._eventMask & TRANSFORM_ON) {
                  this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.POSITION);
                }

                NodePool.setVec3(this._poolHandle, NodeView.WORLD_POSITION, this.worldPosition);
              };

              _proto2.rotate = function rotate(rot, ns) {
                var space = ns || NodeSpace.LOCAL;
                Quat.normalize(q_a, rot);

                if (space === NodeSpace.LOCAL) {
                  Quat.multiply(this._lrot, this._lrot, q_a);
                } else if (space === NodeSpace.WORLD) {
                  var worldRot = this.worldRotation;
                  Quat.multiply(q_b, q_a, worldRot);
                  Quat.invert(q_a, worldRot);
                  Quat.multiply(q_b, q_a, q_b);
                  Quat.multiply(this._lrot, this._lrot, q_b);
                }

                this._eulerDirty = true;
                this.invalidateChildren(TransformBit.ROTATION);

                if (this._eventMask & TRANSFORM_ON) {
                  this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.ROTATION);
                }

                NodePool.setVec4(this._poolHandle, NodeView.WORLD_ROTATION, this.worldRotation);
              };

              _proto2.lookAt = function lookAt(pos, up) {
                this.getWorldPosition(v3_a);
                Vec3.subtract(v3_a, v3_a, pos);
                Vec3.normalize(v3_a, v3_a);
                Quat.fromViewUp(q_a, v3_a, up);
                this.setWorldRotation(q_a);
              };

              _proto2.invalidateChildren = function invalidateChildren(dirtyBit) {
                var childDirtyBit = dirtyBit | TransformBit.POSITION;
                array_a[0] = this;
                var i = 0;

                while (i >= 0) {
                  var cur = array_a[i--];
                  var hasChangedFlags = cur.hasChangedFlags;

                  if (cur.isValid && (cur._dirtyFlags & hasChangedFlags & dirtyBit) !== dirtyBit) {
                    cur._dirtyFlags |= dirtyBit;
                    cur._uiProps.uiTransformDirty = true;
                    cur._hasChangedFlagsChunk[cur._hasChangedFlagsOffset] = hasChangedFlags | dirtyBit;
                    var children = cur._children;
                    var len = children.length;

                    for (var j = 0; j < len; ++j) {
                      array_a[++i] = children[j];
                    }
                  }

                  dirtyBit = childDirtyBit;
                }
              };

              _proto2.updateWorldTransform = function updateWorldTransform() {
                if (!this._dirtyFlags) {
                  return;
                }

                var cur = this;
                var i = 0;

                while (cur && cur._dirtyFlags) {
                  array_a[i++] = cur;
                  cur = cur._parent;
                }

                var child;
                var dirtyBits = 0;
                var childMat;
                var curMat;
                var childPos;
                var childLPos;
                var childRot;

                while (i) {
                  child = array_a[--i];
                  dirtyBits |= child._dirtyFlags;

                  if (cur) {
                    if (dirtyBits & TransformBit.POSITION) {
                      childMat = child._mat;
                      curMat = cur._mat;
                      childPos = child._pos;
                      childLPos = child._lpos;
                      childRot = child._rot;
                      Vec3.transformMat4(childPos, childLPos, curMat);
                      childMat.m12 = childPos.x;
                      childMat.m13 = childPos.y;
                      childMat.m14 = childPos.z;
                      NodePool.setVec3(child._poolHandle, NodeView.WORLD_POSITION, childPos);
                    }

                    if (dirtyBits & TransformBit.RS) {
                      Mat4.fromRTS(child._mat, child._lrot, child._lpos, child._lscale);
                      Mat4.multiply(child._mat, cur._mat, child._mat);

                      if (dirtyBits & TransformBit.ROTATION) {
                        Quat.multiply(child._rot, cur._rot, child._lrot);
                        NodePool.setVec4(child._poolHandle, NodeView.WORLD_ROTATION, child._rot);
                      }

                      Mat3.fromQuat(m3_1$2, Quat.conjugate(qt_1$1, child._rot));
                      Mat3.multiplyMat4(m3_1$2, m3_1$2, child._mat);
                      child._scale.x = m3_1$2.m00;
                      child._scale.y = m3_1$2.m04;
                      child._scale.z = m3_1$2.m08;
                      NodePool.setVec3(child._poolHandle, NodeView.WORLD_SCALE, child._scale);
                    }
                  } else {
                    if (dirtyBits & TransformBit.POSITION) {
                      Vec3.copy(child._pos, child._lpos);
                      child._mat.m12 = child._pos.x;
                      child._mat.m13 = child._pos.y;
                      child._mat.m14 = child._pos.z;
                      NodePool.setVec3(child._poolHandle, NodeView.WORLD_POSITION, child._pos);
                    }

                    if (dirtyBits & TransformBit.RS) {
                      if (dirtyBits & TransformBit.ROTATION) {
                        Quat.copy(child._rot, child._lrot);
                        NodePool.setVec4(child._poolHandle, NodeView.WORLD_ROTATION, child._rot);
                      }

                      if (dirtyBits & TransformBit.SCALE) {
                        Vec3.copy(child._scale, child._lscale);
                        NodePool.setVec3(child._poolHandle, NodeView.WORLD_SCALE, child._scale);
                        Mat4.fromRTS(child._mat, child._rot, child._pos, child._scale);
                      }
                    }
                  }

                  if (dirtyBits !== TransformBit.NONE) {
                    NodePool.setMat4(child._poolHandle, NodeView.WORLD_MATRIX, child._mat);
                  }

                  child._dirtyFlags = TransformBit.NONE;
                  cur = child;
                }
              };

              _proto2.setPosition = function setPosition(val, y, z) {
                if (y === undefined && z === undefined) {
                  Vec3.copy(this._lpos, val);
                } else if (z === undefined) {
                  Vec3.set(this._lpos, val, y, this._lpos.z);
                } else {
                  Vec3.set(this._lpos, val, y, z);
                }

                this.invalidateChildren(TransformBit.POSITION);

                if (this._eventMask & TRANSFORM_ON) {
                  this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.POSITION);
                }
              };

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

              _proto2.setRotation = function setRotation(val, y, z, w) {
                if (y === undefined || z === undefined || w === undefined) {
                  Quat.copy(this._lrot, val);
                } else {
                  Quat.set(this._lrot, val, y, z, w);
                }

                this._eulerDirty = true;
                this.invalidateChildren(TransformBit.ROTATION);

                if (this._eventMask & TRANSFORM_ON) {
                  this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.ROTATION);
                }
              };

              _proto2.setRotationFromEuler = function setRotationFromEuler(val, y, zOpt) {
                var z = zOpt === undefined ? this._euler.z : zOpt;

                if (y === undefined) {
                  Vec3.copy(this._euler, val);
                  Quat.fromEuler(this._lrot, val.x, val.y, val.z);
                } else {
                  Vec3.set(this._euler, val, y, z);
                  Quat.fromEuler(this._lrot, val, y, z);
                }

                this._eulerDirty = false;
                this.invalidateChildren(TransformBit.ROTATION);

                if (this._eventMask & TRANSFORM_ON) {
                  this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.ROTATION);
                }
              };

              _proto2.getRotation = function getRotation(out) {
                if (out) {
                  return Quat.set(out, this._lrot.x, this._lrot.y, this._lrot.z, this._lrot.w);
                }

                return Quat.copy(new Quat(), this._lrot);
              };

              _proto2.setScale = function setScale(val, y, z) {
                if (y === undefined && z === undefined) {
                  Vec3.copy(this._lscale, val);
                } else if (z === undefined) {
                  Vec3.set(this._lscale, val, y, this._lscale.z);
                } else {
                  Vec3.set(this._lscale, val, y, z);
                }

                this.invalidateChildren(TransformBit.SCALE);

                if (this._eventMask & TRANSFORM_ON) {
                  this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.SCALE);
                }
              };

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

              _proto2.inverseTransformPoint = function inverseTransformPoint(out, p) {
                Vec3.copy(out, p);
                var cur = this;
                var i = 0;

                while (cur._parent) {
                  array_a[i++] = cur;
                  cur = cur._parent;
                }

                while (i >= 0) {
                  Vec3.transformInverseRTS(out, out, cur._lrot, cur._lpos, cur._lscale);
                  cur = array_a[--i];
                }

                return out;
              };

              _proto2.setWorldPosition = function setWorldPosition(val, y, z) {
                if (y === undefined || z === undefined) {
                  Vec3.copy(this._pos, val);
                } else {
                  Vec3.set(this._pos, val, y, z);
                }

                NodePool.setVec3(this._poolHandle, NodeView.WORLD_POSITION, this._pos);
                var parent = this._parent;
                var local = this._lpos;

                if (parent) {
                  parent.updateWorldTransform();
                  Vec3.transformMat4(local, this._pos, Mat4.invert(m4_1, parent._mat));
                } else {
                  Vec3.copy(local, this._pos);
                }

                this.invalidateChildren(TransformBit.POSITION);

                if (this._eventMask & TRANSFORM_ON) {
                  this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.POSITION);
                }
              };

              _proto2.getWorldPosition = function getWorldPosition(out) {
                this.updateWorldTransform();

                if (out) {
                  return Vec3.copy(out, this._pos);
                }

                return Vec3.copy(new Vec3(), this._pos);
              };

              _proto2.setWorldRotation = function setWorldRotation(val, y, z, w) {
                if (y === undefined || z === undefined || w === undefined) {
                  Quat.copy(this._rot, val);
                } else {
                  Quat.set(this._rot, val, y, z, w);
                }

                NodePool.setVec4(this._poolHandle, NodeView.WORLD_ROTATION, this._rot);

                if (this._parent) {
                  this._parent.updateWorldTransform();

                  Quat.multiply(this._lrot, Quat.conjugate(this._lrot, this._parent._rot), this._rot);
                } else {
                  Quat.copy(this._lrot, this._rot);
                }

                this._eulerDirty = true;
                this.invalidateChildren(TransformBit.ROTATION);

                if (this._eventMask & TRANSFORM_ON) {
                  this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.ROTATION);
                }
              };

              _proto2.setWorldRotationFromEuler = function setWorldRotationFromEuler(x, y, z) {
                Quat.fromEuler(this._rot, x, y, z);

                if (this._parent) {
                  this._parent.updateWorldTransform();

                  Quat.multiply(this._lrot, Quat.conjugate(this._lrot, this._parent._rot), this._rot);
                } else {
                  Quat.copy(this._lrot, this._rot);
                }

                this._eulerDirty = true;
                this.invalidateChildren(TransformBit.ROTATION);

                if (this._eventMask & TRANSFORM_ON) {
                  this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.ROTATION);
                }
              };

              _proto2.getWorldRotation = function getWorldRotation(out) {
                this.updateWorldTransform();

                if (out) {
                  return Quat.copy(out, this._rot);
                }

                return Quat.copy(new Quat(), this._rot);
              };

              _proto2.setWorldScale = function setWorldScale(val, y, z) {
                if (y === undefined || z === undefined) {
                  Vec3.copy(this._scale, val);
                } else {
                  Vec3.set(this._scale, val, y, z);
                }

                NodePool.setVec3(this._poolHandle, NodeView.WORLD_SCALE, this._scale);
                var parent = this._parent;

                if (parent) {
                  parent.updateWorldTransform();
                  Mat3.fromQuat(m3_1$2, Quat.conjugate(qt_1$1, parent._rot));
                  Mat3.multiplyMat4(m3_1$2, m3_1$2, parent._mat);
                  m3_scaling.m00 = this._scale.x;
                  m3_scaling.m04 = this._scale.y;
                  m3_scaling.m08 = this._scale.z;
                  Mat3.multiply(m3_1$2, m3_scaling, Mat3.invert(m3_1$2, m3_1$2));
                  this._lscale.x = Vec3.set(v3_a, m3_1$2.m00, m3_1$2.m01, m3_1$2.m02).length();
                  this._lscale.y = Vec3.set(v3_a, m3_1$2.m03, m3_1$2.m04, m3_1$2.m05).length();
                  this._lscale.z = Vec3.set(v3_a, m3_1$2.m06, m3_1$2.m07, m3_1$2.m08).length();
                } else {
                  Vec3.copy(this._lscale, this._scale);
                }

                this.invalidateChildren(TransformBit.SCALE);

                if (this._eventMask & TRANSFORM_ON) {
                  this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.SCALE);
                }
              };

              _proto2.getWorldScale = function getWorldScale(out) {
                this.updateWorldTransform();

                if (out) {
                  return Vec3.copy(out, this._scale);
                }

                return Vec3.copy(new Vec3(), this._scale);
              };

              _proto2.getWorldMatrix = function getWorldMatrix(out) {
                this.updateWorldTransform();
                var target = out || new Mat4();
                return Mat4.copy(target, this._mat);
              };

              _proto2.getWorldRS = function getWorldRS(out) {
                this.updateWorldTransform();
                var target = out || new Mat4();
                Mat4.copy(target, this._mat);
                target.m12 = 0;
                target.m13 = 0;
                target.m14 = 0;
                return target;
              };

              _proto2.getWorldRT = function getWorldRT(out) {
                this.updateWorldTransform();
                var target = out || new Mat4();
                return Mat4.fromRT(target, this._rot, this._pos);
              };

              _proto2.setRTS = function setRTS(rot, pos, scale) {
                var dirtyBit = 0;

                if (rot) {
                  dirtyBit |= TransformBit.ROTATION;

                  if (rot.w !== undefined) {
                    Quat.copy(this._lrot, rot);
                    this._eulerDirty = true;
                  } else {
                    Vec3.copy(this._euler, rot);
                    Quat.fromEuler(this._lrot, rot.x, rot.y, rot.z);
                    this._eulerDirty = false;
                  }
                }

                if (pos) {
                  Vec3.copy(this._lpos, pos);
                  dirtyBit |= TransformBit.POSITION;
                }

                if (scale) {
                  Vec3.copy(this._lscale, scale);
                  dirtyBit |= TransformBit.SCALE;
                }

                if (dirtyBit) {
                  this.invalidateChildren(dirtyBit);

                  if (this._eventMask & TRANSFORM_ON) {
                    this.emit(SystemEventType.TRANSFORM_CHANGED, dirtyBit);
                  }
                }
              };

              _proto2.pauseSystemEvents = function pauseSystemEvents(recursive) {
                eventManager.pauseTarget(this, recursive);
              };

              _proto2.resumeSystemEvents = function resumeSystemEvents(recursive) {
                eventManager.resumeTarget(this, recursive);
              };

              Node.resetHasChangedFlags = function resetHasChangedFlags() {
                bookOfChange.clear();
              };

              Node.clearNodeArray = function clearNodeArray() {
                if (Node.ClearFrame < Node.ClearRound) {
                  Node.ClearFrame++;
                } else {
                  Node.ClearFrame = 0;
                  array_a.length = 0;
                }
              };

              _proto2.syncToNativeTransform = function syncToNativeTransform() {
                var v = this.hasChangedFlags;

                if (v) {
                  if (v & TransformBit.POSITION) {
                    NodePool.setVec3(this._poolHandle, NodeView.WORLD_POSITION, this.worldPosition);
                  }

                  if (v & TransformBit.ROTATION) {
                    NodePool.setVec4(this._poolHandle, NodeView.WORLD_ROTATION, this.worldRotation);
                  }

                  if (v & TransformBit.SCALE) {
                    NodePool.setVec3(this._poolHandle, NodeView.WORLD_SCALE, this.worldScale);
                  }
                }
              };

              _proto2.syncFromNativeTransform = function syncFromNativeTransform() {
                var v = this.hasChangedFlags;

                if (v) {
                  if (v & TransformBit.POSITION) {
                    NodePool.getVec3(this._poolHandle, NodeView.WORLD_POSITION, v3_a);
                    this.setWorldPosition(v3_a);
                  }

                  if (v & TransformBit.ROTATION) {
                    NodePool.getVec4(this._poolHandle, NodeView.WORLD_ROTATION, q_a);
                    this.setWorldRotation(q_a);
                  }

                  if (v & TransformBit.SCALE) {
                    NodePool.getVec3(this._poolHandle, NodeView.WORLD_SCALE, v3_a);
                    this.setWorldScale(v3_a);
                  }
                }
              };

              _createClass(Node, [{
                key: "handle",
                get: function get() {
                  return this._poolHandle;
                }
              }, {
                key: "position",
                get: function get() {
                  return this._lpos;
                },
                set: function set(val) {
                  this.setPosition(val);
                }
              }, {
                key: "worldPosition",
                get: function get() {
                  this.updateWorldTransform();
                  return this._pos;
                },
                set: function set(val) {
                  this.setWorldPosition(val);
                }
              }, {
                key: "rotation",
                get: function get() {
                  return this._lrot;
                },
                set: function set(val) {
                  this.setRotation(val);
                }
              }, {
                key: "eulerAngles",
                get: function get() {
                  if (this._eulerDirty) {
                    Quat.toEuler(this._euler, this._lrot);
                    this._eulerDirty = false;
                  }

                  return this._euler;
                },
                set: function set(val) {
                  this.setRotationFromEuler(val.x, val.y, val.z);
                }
              }, {
                key: "angle",
                get: function get() {
                  return this._euler.z;
                },
                set: function set(val) {
                  Vec3.set(this._euler, 0, 0, val);
                  Quat.fromAngleZ(this._lrot, val);
                  this._eulerDirty = false;
                  this.invalidateChildren(TransformBit.ROTATION);

                  if (this._eventMask & TRANSFORM_ON) {
                    this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.ROTATION);
                  }
                }
              }, {
                key: "worldRotation",
                get: function get() {
                  this.updateWorldTransform();
                  return this._rot;
                },
                set: function set(val) {
                  this.setWorldRotation(val);
                }
              }, {
                key: "scale",
                get: function get() {
                  return this._lscale;
                },
                set: function set(val) {
                  this.setScale(val);
                }
              }, {
                key: "worldScale",
                get: function get() {
                  this.updateWorldTransform();
                  return this._scale;
                },
                set: function set(val) {
                  this.setWorldScale(val);
                }
              }, {
                key: "matrix",
                set: function set(val) {
                  Mat4.toRTS(val, this._lrot, this._lpos, this._lscale);
                  this.invalidateChildren(TransformBit.TRS);
                  this._eulerDirty = true;

                  if (this._eventMask & TRANSFORM_ON) {
                    this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.TRS);
                  }
                }
              }, {
                key: "worldMatrix",
                get: function get() {
                  this.updateWorldTransform();
                  return this._mat;
                }
              }, {
                key: "forward",
                get: function get() {
                  return Vec3.transformQuat(new Vec3(), Vec3.FORWARD, this.worldRotation);
                },
                set: function set(dir) {
                  var len = dir.length();
                  Vec3.multiplyScalar(v3_a, dir, -1 / len);
                  Quat.fromViewUp(q_a, v3_a);
                  this.setWorldRotation(q_a);
                }
              }, {
                key: "layer",
                get: function get() {
                  return this._layer;
                },
                set: function set(l) {
                  this._layer = l;
                  NodePool.set(this._poolHandle, NodeView.LAYER, this._layer);
                  this.emit(SystemEventType.LAYER_CHANGED, this._layer);
                }
              }, {
                key: "hasChangedFlags",
                get: function get() {
                  return this._hasChangedFlagsChunk[this._hasChangedFlagsOffset];
                },
                set: function set(val) {
                  this._hasChangedFlagsChunk[this._hasChangedFlagsOffset] = val;
                }
              }]);

              return Node;
            }(BaseNode), _class3$7.EventType = SystemEventType, _class3$7.NodeSpace = NodeSpace, _class3$7.TransformDirtyBit = TransformBit, _class3$7.TransformBit = TransformBit, _class3$7.ClearFrame = 0, _class3$7.ClearRound = 1000, _temp$a), (_descriptor$8 = _applyDecoratedDescriptor(_class2$a.prototype, "_lpos", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new Vec3();
              }
            }), _descriptor2$4 = _applyDecoratedDescriptor(_class2$a.prototype, "_lrot", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new Quat();
              }
            }), _descriptor3$4 = _applyDecoratedDescriptor(_class2$a.prototype, "_lscale", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new Vec3(1, 1, 1);
              }
            }), _descriptor4$3 = _applyDecoratedDescriptor(_class2$a.prototype, "_layer", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return Layers.Enum.DEFAULT;
              }
            }), _descriptor5$2 = _applyDecoratedDescriptor(_class2$a.prototype, "_euler", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new Vec3();
              }
            }), _applyDecoratedDescriptor(_class2$a.prototype, "eulerAngles", [_dec2$4], Object.getOwnPropertyDescriptor(_class2$a.prototype, "eulerAngles"), _class2$a.prototype), _applyDecoratedDescriptor(_class2$a.prototype, "angle", [editable], Object.getOwnPropertyDescriptor(_class2$a.prototype, "angle"), _class2$a.prototype), _applyDecoratedDescriptor(_class2$a.prototype, "layer", [editable], Object.getOwnPropertyDescriptor(_class2$a.prototype, "layer"), _class2$a.prototype)), _class2$a)) || _class$b));
            legacyCC.Node = Node$1;

            var _dec$c, _class$c, _class2$b, _descriptor$9, _temp$b, _dec2$5, _dec3$2, _dec4$1, _dec5, _dec6, _class4, _class5, _descriptor2$5, _descriptor3$5, _descriptor4$4, _descriptor5$3, _descriptor6$1, _temp2, _dec7, _class7, _class8, _descriptor7$1, _temp3, _dec8, _dec9, _class10, _class11, _descriptor8$1, _descriptor9, _descriptor10, _temp4, _dec10, _dec11, _dec12, _class13, _class14, _descriptor11, _descriptor12, _temp5, _dec13, _dec14, _dec15, _class16, _class17, _descriptor13, _descriptor14, _temp6, _dec16, _dec17, _dec18, _dec19, _dec20, _dec21, _class19, _class20, _descriptor15, _descriptor16, _descriptor17, _descriptor18, _descriptor19, _descriptor20, _temp7, _dec22, _dec23, _dec24, _dec25, _dec26, _class22, _class23, _descriptor21, _descriptor22, _descriptor23, _descriptor24, _descriptor25, _temp8;

            var TargetInfo = (_dec$c = ccclass('cc.TargetInfo'), _dec$c(_class$c = (_class2$b = (_temp$b = function TargetInfo() {
              _initializerDefineProperty(this, "localID", _descriptor$9, this);
            }, _temp$b), (_descriptor$9 = _applyDecoratedDescriptor(_class2$b.prototype, "localID", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            })), _class2$b)) || _class$c);
            var TargetOverrideInfo = (_dec2$5 = ccclass('cc.TargetOverrideInfo'), _dec3$2 = type(CCObject), _dec4$1 = type(TargetInfo), _dec5 = type(Node$1), _dec6 = type(TargetInfo), _dec2$5(_class4 = (_class5 = (_temp2 = function TargetOverrideInfo() {
              _initializerDefineProperty(this, "source", _descriptor2$5, this);

              _initializerDefineProperty(this, "sourceInfo", _descriptor3$5, this);

              _initializerDefineProperty(this, "propertyPath", _descriptor4$4, this);

              _initializerDefineProperty(this, "target", _descriptor5$3, this);

              _initializerDefineProperty(this, "targetInfo", _descriptor6$1, this);
            }, _temp2), (_descriptor2$5 = _applyDecoratedDescriptor(_class5.prototype, "source", [serializable, _dec3$2], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor3$5 = _applyDecoratedDescriptor(_class5.prototype, "sourceInfo", [serializable, _dec4$1], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor4$4 = _applyDecoratedDescriptor(_class5.prototype, "propertyPath", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor5$3 = _applyDecoratedDescriptor(_class5.prototype, "target", [serializable, _dec5], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor6$1 = _applyDecoratedDescriptor(_class5.prototype, "targetInfo", [serializable, _dec6], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            })), _class5)) || _class4);
            var CompPrefabInfo = (_dec7 = ccclass('cc.CompPrefabInfo'), _dec7(_class7 = (_class8 = (_temp3 = function CompPrefabInfo() {
              _initializerDefineProperty(this, "fileId", _descriptor7$1, this);
            }, _temp3), (_descriptor7$1 = _applyDecoratedDescriptor(_class8.prototype, "fileId", [serializable, editable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return '';
              }
            })), _class8)) || _class7);
            var PropertyOverrideInfo = (_dec8 = ccclass('CCPropertyOverrideInfo'), _dec9 = type(TargetInfo), _dec8(_class10 = (_class11 = (_temp4 = function () {
              function PropertyOverrideInfo() {
                _initializerDefineProperty(this, "targetInfo", _descriptor8$1, this);

                _initializerDefineProperty(this, "propertyPath", _descriptor9, this);

                _initializerDefineProperty(this, "value", _descriptor10, this);
              }

              var _proto = PropertyOverrideInfo.prototype;

              _proto.isTarget = function isTarget(localID, propPath) {
              };

              return PropertyOverrideInfo;
            }(), _temp4), (_descriptor8$1 = _applyDecoratedDescriptor(_class11.prototype, "targetInfo", [serializable, _dec9], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor9 = _applyDecoratedDescriptor(_class11.prototype, "propertyPath", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor10 = _applyDecoratedDescriptor(_class11.prototype, "value", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: null
            })), _class11)) || _class10);
            var MountedChildrenInfo = (_dec10 = ccclass('cc.MountedChildrenInfo'), _dec11 = type(TargetInfo), _dec12 = type([Node$1]), _dec10(_class13 = (_class14 = (_temp5 = function () {
              function MountedChildrenInfo() {
                _initializerDefineProperty(this, "targetInfo", _descriptor11, this);

                _initializerDefineProperty(this, "nodes", _descriptor12, this);
              }

              var _proto2 = MountedChildrenInfo.prototype;

              _proto2.isTarget = function isTarget(localID) {
              };

              return MountedChildrenInfo;
            }(), _temp5), (_descriptor11 = _applyDecoratedDescriptor(_class14.prototype, "targetInfo", [serializable, _dec11], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor12 = _applyDecoratedDescriptor(_class14.prototype, "nodes", [serializable, _dec12], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            })), _class14)) || _class13);
            var MountedComponentsInfo = (_dec13 = ccclass('cc.MountedComponentsInfo'), _dec14 = type(TargetInfo), _dec15 = type([Component]), _dec13(_class16 = (_class17 = (_temp6 = function () {
              function MountedComponentsInfo() {
                _initializerDefineProperty(this, "targetInfo", _descriptor13, this);

                _initializerDefineProperty(this, "components", _descriptor14, this);
              }

              var _proto3 = MountedComponentsInfo.prototype;

              _proto3.isTarget = function isTarget(localID) {
              };

              return MountedComponentsInfo;
            }(), _temp6), (_descriptor13 = _applyDecoratedDescriptor(_class17.prototype, "targetInfo", [serializable, _dec14], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor14 = _applyDecoratedDescriptor(_class17.prototype, "components", [serializable, _dec15], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            })), _class17)) || _class16);
            var PrefabInstance = (_dec16 = ccclass('cc.PrefabInstance'), _dec17 = type(Node$1), _dec18 = type([MountedChildrenInfo]), _dec19 = type([MountedComponentsInfo]), _dec20 = type([PropertyOverrideInfo]), _dec21 = type([TargetInfo]), _dec16(_class19 = (_class20 = (_temp7 = function () {
              function PrefabInstance() {
                _initializerDefineProperty(this, "fileId", _descriptor15, this);

                _initializerDefineProperty(this, "prefabRootNode", _descriptor16, this);

                _initializerDefineProperty(this, "mountedChildren", _descriptor17, this);

                _initializerDefineProperty(this, "mountedComponents", _descriptor18, this);

                _initializerDefineProperty(this, "propertyOverrides", _descriptor19, this);

                _initializerDefineProperty(this, "removedComponents", _descriptor20, this);

                this.targetMap = {};
              }

              var _proto4 = PrefabInstance.prototype;

              _proto4.findPropertyOverride = function findPropertyOverride(localID, propPath) {
              };

              _proto4.removePropertyOverride = function removePropertyOverride(localID, propPath) {
              };

              return PrefabInstance;
            }(), _temp7), (_descriptor15 = _applyDecoratedDescriptor(_class20.prototype, "fileId", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return '';
              }
            }), _descriptor16 = _applyDecoratedDescriptor(_class20.prototype, "prefabRootNode", [serializable, _dec17], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: null
            }), _descriptor17 = _applyDecoratedDescriptor(_class20.prototype, "mountedChildren", [serializable, _dec18], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor18 = _applyDecoratedDescriptor(_class20.prototype, "mountedComponents", [serializable, _dec19], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor19 = _applyDecoratedDescriptor(_class20.prototype, "propertyOverrides", [serializable, _dec20], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor20 = _applyDecoratedDescriptor(_class20.prototype, "removedComponents", [serializable, _dec21], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            })), _class20)) || _class19);
            var PrefabInfo = (_dec22 = ccclass('cc.PrefabInfo'), _dec23 = type(Node$1), _dec24 = type(legacyCC.Prefab), _dec25 = type(PrefabInstance), _dec26 = type([TargetOverrideInfo]), _dec22(_class22 = (_class23 = (_temp8 = function PrefabInfo() {
              _initializerDefineProperty(this, "root", _descriptor21, this);

              _initializerDefineProperty(this, "asset", _descriptor22, this);

              _initializerDefineProperty(this, "fileId", _descriptor23, this);

              _initializerDefineProperty(this, "instance", _descriptor24, this);

              _initializerDefineProperty(this, "targetOverrides", _descriptor25, this);
            }, _temp8), (_descriptor21 = _applyDecoratedDescriptor(_class23.prototype, "root", [serializable, _dec23], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: null
            }), _descriptor22 = _applyDecoratedDescriptor(_class23.prototype, "asset", [serializable, _dec24], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: null
            }), _descriptor23 = _applyDecoratedDescriptor(_class23.prototype, "fileId", [serializable, editable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return '';
              }
            }), _descriptor24 = _applyDecoratedDescriptor(_class23.prototype, "instance", [serializable, _dec25], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: null
            }), _descriptor25 = _applyDecoratedDescriptor(_class23.prototype, "targetOverrides", [serializable, _dec26], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: null
            })), _class23)) || _class22);
            legacyCC._PrefabInfo = PrefabInfo;

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

            var _dec$d, _class$d, _class2$c, _descriptor$a, _descriptor2$6, _class3$8, _temp$c;
            var OptimizationPolicy = Enum({
              AUTO: 0,
              SINGLE_INSTANCE: 1,
              MULTI_INSTANCE: 2
            });
            var Prefab = exports('Prefab', (_dec$d = ccclass('cc.Prefab'), _dec$d(_class$d = (_class2$c = (_temp$c = _class3$8 = function (_Asset) {
              _inheritsLoose(Prefab, _Asset);

              function Prefab() {
                var _this;

                _this = _Asset.call(this) || this;

                _initializerDefineProperty(_this, "data", _descriptor$a, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "optimizationPolicy", _descriptor2$6, _assertThisInitialized(_this));

                _this._createFunction = void 0;
                _this._instantiatedTimes = void 0;
                _this._createFunction = null;
                _this._instantiatedTimes = 0;
                return _this;
              }

              var _proto = Prefab.prototype;

              _proto.createNode = function createNode(cb) {
                var node = legacyCC.instantiate(this);
                node.name = this.name;
                cb(null, node);
              };

              _proto.compileCreateFunction = function compileCreateFunction() {
                this._createFunction = compile(this.data);
              };

              _proto._doInstantiate = function _doInstantiate(rootToRedirect) {
                if (!this.data._prefab) {
                  warnID(3700);
                }

                if (!this._createFunction) {
                  this.compileCreateFunction();
                }

                return this._createFunction(rootToRedirect);
              };

              _proto._instantiate = function _instantiate() {
                var node;
                var useJit = false;

                {
                  if (this.optimizationPolicy === OptimizationPolicy.SINGLE_INSTANCE) {
                    useJit = false;
                  } else if (this.optimizationPolicy === OptimizationPolicy.MULTI_INSTANCE) {
                    useJit = true;
                  } else {
                    useJit = this._instantiatedTimes + 1 >= Prefab.OptimizationPolicyThreshold;
                  }
                }

                if (useJit) {
                  node = this._doInstantiate();

                  this.data._instantiate(node);
                } else {
                  node = this.data._instantiate();
                }

                ++this._instantiatedTimes;
                return node;
              };

              _proto.initDefault = function initDefault(uuid) {
                _Asset.prototype.initDefault.call(this, uuid);

                this.data = new Node$1();
                this.data.name = '(Missing Node)';
                var prefabInfo = new PrefabInfo();
                prefabInfo.asset = this;
                prefabInfo.root = this.data;
                this.data._prefab = prefabInfo;
              };

              _proto.validate = function validate() {
                return !!this.data;
              };

              return Prefab;
            }(Asset), _class3$8.OptimizationPolicy = OptimizationPolicy, _class3$8.OptimizationPolicyThreshold = 3, _temp$c), (_descriptor$a = _applyDecoratedDescriptor(_class2$c.prototype, "data", [serializable, editable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor2$6 = _applyDecoratedDescriptor(_class2$c.prototype, "optimizationPolicy", [serializable, editable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return OptimizationPolicy.AUTO;
              }
            })), _class2$c)) || _class$d));
            js.value(Prefab, '_utils', utils);
            legacyCC.Prefab = Prefab;

            {
              obsolete(legacyCC, 'cc._Prefab', 'Prefab');
            }

            var _dec$e, _dec2$6, _dec3$3, _class$e, _class2$d, _descriptor$b, _temp$d;
            var PrefabLink = exports('PrefabLink', (_dec$e = ccclass('cc.PrefabLink'), _dec2$6 = type(Prefab), _dec3$3 = visible(), _dec$e(_class$e = (_class2$d = (_temp$d = function (_Component) {
              _inheritsLoose(PrefabLink, _Component);

              function PrefabLink() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Component.call.apply(_Component, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "prefab", _descriptor$b, _assertThisInitialized(_this));

                return _this;
              }

              return PrefabLink;
            }(Component), _temp$d), (_descriptor$b = _applyDecoratedDescriptor(_class2$d.prototype, "prefab", [_dec2$6, serializable, _dec3$3], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            })), _class2$d)) || _class$e));

            var _vec3 = new Vec3();

            function WorldNode3DToLocalNodeUI(mainCamera, wpos, uiNode, out) {
              if (!out) {
                out = new Vec3();
              }

              mainCamera.convertToUINode(wpos, uiNode, out);
              var pos = uiNode.position;
              out.add(pos);
              return out;
            }
            function WorldNode3DToWorldNodeUI(mainCamera, wpos, out) {
              if (!out) {
                out = new Vec3();
              }

              mainCamera.worldToScreen(wpos, out);
              out.x /= legacyCC.view.getScaleX();
              out.y /= legacyCC.view.getScaleY();
              return out;
            }
            var convertUtils = exports('convertUtils', {
              WorldNode3DToLocalNodeUI: WorldNode3DToLocalNodeUI,
              WorldNode3DToWorldNodeUI: WorldNode3DToWorldNodeUI
            });
            legacyCC.pipelineUtils = convertUtils;
            replaceProperty(legacyCC.pipelineUtils, 'cc.pipelineUtils', [{
              name: 'WorldNode3DToLocalNodeUI',
              newName: 'convertToUINode',
              targetName: 'cc.Camera.prototype',
              customFunction: function customFunction() {
                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                var camera = args[0];
                var out = args[3] || _vec3;
                camera.convertToUINode(args[1], args[2], out);
                out.add(args[2].position);
                return args[3] || out.clone();
              }
            }]);

            replaceProperty(SystemEventType, 'Node.EventType', [{
              name: 'POSITION_PART',
              newName: 'TRANSFORM_CHANGED'
            }, {
              name: 'ROTATION_PART',
              newName: 'TRANSFORM_CHANGED'
            }, {
              name: 'SCALE_PART',
              newName: 'TRANSFORM_CHANGED'
            }]);

            var AccelerometerInputSource = function () {
              function AccelerometerInputSource() {
                this.support = void 0;
                this._intervalInMileseconds = 200;
                this._accelTimer = 0;
                this._eventTarget = new EventTarget();
                this._deviceEventName = void 0;
                this._globalEventClass = void 0;
                this._didAccelerateFunc = void 0;
                this.support = window.DeviceMotionEvent !== undefined || window.DeviceOrientationEvent !== undefined;
                this._globalEventClass = window.DeviceMotionEvent || window.DeviceOrientationEvent;

                if (system.browserType === BrowserType.MOBILE_QQ) {
                  this._globalEventClass = window.DeviceOrientationEvent;
                }

                this._deviceEventName = this._globalEventClass === window.DeviceMotionEvent ? 'devicemotion' : 'deviceorientation';
                this._didAccelerateFunc = this._didAccelerate.bind(this);
              }

              var _proto = AccelerometerInputSource.prototype;

              _proto._registerEvent = function _registerEvent() {
                this._accelTimer = performance.now();
                window.addEventListener(this._deviceEventName, this._didAccelerateFunc, false);
              };

              _proto._unregisterEvent = function _unregisterEvent() {
                this._accelTimer = 0;
                window.removeEventListener(this._deviceEventName, this._didAccelerateFunc, false);
              };

              _proto._didAccelerate = function _didAccelerate(event) {
                var now = performance.now();

                if (now - this._accelTimer < this._intervalInMileseconds) {
                  return;
                }

                this._accelTimer = now;
                var x = 0;
                var y = 0;
                var z = 0;

                if (this._globalEventClass === window.DeviceMotionEvent) {
                  var deviceMotionEvent = event;
                  var eventAcceleration = deviceMotionEvent.accelerationIncludingGravity;
                  x = ((eventAcceleration === null || eventAcceleration === void 0 ? void 0 : eventAcceleration.x) || 0) * 0.1;
                  y = ((eventAcceleration === null || eventAcceleration === void 0 ? void 0 : eventAcceleration.y) || 0) * 0.1;
                  z = ((eventAcceleration === null || eventAcceleration === void 0 ? void 0 : eventAcceleration.z) || 0) * 0.1;
                } else {
                  var deviceOrientationEvent = event;
                  x = (deviceOrientationEvent.gamma || 0) / 90 * 0.981;
                  y = -((deviceOrientationEvent.beta || 0) / 90) * 0.981;
                  z = (deviceOrientationEvent.alpha || 0) / 90 * 0.981;
                }

                if (legacyCC.view._isRotated) {
                  var tmp = x;
                  x = -y;
                  y = tmp;
                }
                var LANDSCAPE_LEFT = -90;
                var PORTRAIT_UPSIDE_DOWN = 180;
                var LANDSCAPE_RIGHT = 90;
                var tmpX = x;

                if (window.orientation === LANDSCAPE_RIGHT) {
                  x = -y;
                  y = tmpX;
                } else if (window.orientation === LANDSCAPE_LEFT) {
                  x = y;
                  y = -tmpX;
                } else if (window.orientation === PORTRAIT_UPSIDE_DOWN) {
                  x = -x;
                  y = -y;
                }

                if (system.os === OS.ANDROID && system.browserType !== BrowserType.MOBILE_QQ) {
                  x = -x;
                  y = -y;
                }

                var accelerometer = {
                  type: SystemEventType.DEVICEMOTION,
                  x: x,
                  y: y,
                  z: z,
                  timestamp: performance.now()
                };

                this._eventTarget.emit(SystemEventType.DEVICEMOTION, accelerometer);
              };

              _proto.start = function start() {
                this._registerEvent();
              };

              _proto.stop = function stop() {
                this._unregisterEvent();
              };

              _proto.setInterval = function setInterval(intervalInMileseconds) {
                this._intervalInMileseconds = intervalInMileseconds;
              };

              _proto.onChange = function onChange(cb) {
                this._eventTarget.on(SystemEventType.DEVICEMOTION, cb);
              };

              return AccelerometerInputSource;
            }();

            var InputBox = function () {
              function InputBox() {
                this.support = void 0;
                this.support = true;
              }

              var _proto = InputBox.prototype;

              _proto.show = function show() {
                throw new Error('Method not implemented.');
              };

              _proto.hide = function hide() {
                throw new Error('Method not implemented.');
              };

              _proto.onChange = function onChange() {
                throw new Error('Method not implemented.');
              };

              _proto.onComplete = function onComplete() {
                throw new Error('Method not implemented.');
              };

              _proto.offChange = function offChange() {
                throw new Error('Method not implemented.');
              };

              _proto.offComplete = function offComplete() {
                throw new Error('Method not implemented.');
              };

              return InputBox;
            }();

            var KeyboardInputSource = function () {
              function KeyboardInputSource() {
                this.support = void 0;
                this._eventTarget = new EventTarget();
                this.support = document.documentElement.onkeyup !== undefined;

                this._registerEvent();
              }

              var _proto = KeyboardInputSource.prototype;

              _proto._registerEvent = function _registerEvent() {
                var canvas = document.getElementById('GameCanvas');
                canvas === null || canvas === void 0 ? void 0 : canvas.addEventListener('keydown', this._createCallback(SystemEventType.KEY_DOWN));
                canvas === null || canvas === void 0 ? void 0 : canvas.addEventListener('keyup', this._createCallback(SystemEventType.KEY_UP));
              };

              _proto._createCallback = function _createCallback(eventType) {
                var _this = this;

                return function (event) {
                  var inputEvent = {
                    type: eventType,
                    code: event.keyCode,
                    timestamp: performance.now()
                  };
                  event.stopPropagation();
                  event.preventDefault();

                  _this._eventTarget.emit(eventType, inputEvent);
                };
              };

              _proto.onDown = function onDown(cb) {
                this._eventTarget.on(SystemEventType.KEY_DOWN, cb);
              };

              _proto.onUp = function onUp(cb) {
                this._eventTarget.on(SystemEventType.KEY_UP, cb);
              };

              return KeyboardInputSource;
            }();

            var MouseInputSource = function () {
              function MouseInputSource() {
                this.support = void 0;
                this._canvas = void 0;
                this._eventTarget = new EventTarget();
                this._pointLocked = false;
                this._isPressed = false;
                this._preMousePos = new Vec2();
                this.support =  document.documentElement.onmouseup !== undefined;

                if (this.support) {
                  this._canvas = document.getElementById('GameCanvas');

                  if (!this._canvas && !TEST) {
                    console.warn('failed to access canvas');
                  }

                  this._registerEvent();
                }
              }

              var _proto = MouseInputSource.prototype;

              _proto._getCanvasRect = function _getCanvasRect() {
                var canvas = this._canvas;
                var box = canvas === null || canvas === void 0 ? void 0 : canvas.getBoundingClientRect();

                if (box) {
                  return new Rect(box.x, box.y, box.width, box.height);
                }

                return new Rect(0, 0, 0, 0);
              };

              _proto._getLocation = function _getLocation(event) {
                return new Vec2(event.clientX, event.clientY);
              };

              _proto._registerEvent = function _registerEvent() {
                var _this = this,
                    _this$_canvas,
                    _this$_canvas2,
                    _this$_canvas3,
                    _this$_canvas4;

                window.addEventListener('mousedown', function () {
                  _this._isPressed = true;
                });
                (_this$_canvas = this._canvas) === null || _this$_canvas === void 0 ? void 0 : _this$_canvas.addEventListener('mousedown', this._createCallback(SystemEventType.MOUSE_DOWN));
                (_this$_canvas2 = this._canvas) === null || _this$_canvas2 === void 0 ? void 0 : _this$_canvas2.addEventListener('mousemove', this._createCallback(SystemEventType.MOUSE_MOVE));
                window.addEventListener('mouseup', this._createCallback(SystemEventType.MOUSE_UP));
                (_this$_canvas3 = this._canvas) === null || _this$_canvas3 === void 0 ? void 0 : _this$_canvas3.addEventListener('mouseup', this._createCallback(SystemEventType.MOUSE_UP));
                (_this$_canvas4 = this._canvas) === null || _this$_canvas4 === void 0 ? void 0 : _this$_canvas4.addEventListener('wheel', function (event) {
                  var canvasRect = _this._getCanvasRect();

                  var location = _this._getLocation(event);

                  var wheelSensitivityFactor = 5;
                  var inputEvent = {
                    type: SystemEventType.MOUSE_WHEEL,
                    x: location.x - canvasRect.x,
                    y: canvasRect.y + canvasRect.height - location.y,
                    button: event.button,
                    deltaX: event.deltaX * wheelSensitivityFactor,
                    deltaY: -event.deltaY * wheelSensitivityFactor,
                    timestamp: performance.now(),
                    movementX: event.movementX,
                    movementY: event.movementY
                  };
                  event.stopPropagation();
                  event.preventDefault();

                  _this._eventTarget.emit(SystemEventType.MOUSE_WHEEL, inputEvent);
                });

                this._registerPointerLockEvent();
              };

              _proto._registerPointerLockEvent = function _registerPointerLockEvent() {
                var _this2 = this;

                var lockChangeAlert = function lockChangeAlert() {
                  var canvas = _this2._canvas;

                  if (document.pointerLockElement === canvas || document.mozPointerLockElement === canvas) {
                    _this2._pointLocked = true;
                  } else {
                    _this2._pointLocked = false;
                  }
                };

                if ('onpointerlockchange' in document) {
                  document.addEventListener('pointerlockchange', lockChangeAlert, false);
                } else if ('onmozpointerlockchange' in document) {
                  document.addEventListener('mozpointerlockchange', lockChangeAlert, false);
                }
              };

              _proto._createCallback = function _createCallback(eventType) {
                var _this3 = this;

                return function (event) {
                  var _this3$_canvas;

                  var canvasRect = _this3._getCanvasRect();

                  var location = _this3._getLocation(event);

                  var button = event.button;

                  switch (event.type) {
                    case 'mousedown':
                      (_this3$_canvas = _this3._canvas) === null || _this3$_canvas === void 0 ? void 0 : _this3$_canvas.focus();
                      _this3._isPressed = true;
                      break;

                    case 'mouseup':
                      _this3._isPressed = false;
                      break;

                    case 'mousemove':
                      if (!_this3._isPressed) {
                        button = -1;
                      }

                      break;
                  }

                  var inputEvent = {
                    type: eventType,
                    x: _this3._pointLocked ? _this3._preMousePos.x + event.movementX : location.x - canvasRect.x,
                    y: _this3._pointLocked ? _this3._preMousePos.y - event.movementY : canvasRect.y + canvasRect.height - location.y,
                    button: button,
                    timestamp: performance.now(),
                    movementX: event.movementX,
                    movementY: event.movementY
                  };

                  _this3._preMousePos.set(inputEvent.x, inputEvent.y);

                  event.stopPropagation();

                  if (event.target === _this3._canvas) {
                    event.preventDefault();
                  }

                  _this3._eventTarget.emit(eventType, inputEvent);
                };
              };

              _proto.onDown = function onDown(cb) {
                this._eventTarget.on(SystemEventType.MOUSE_DOWN, cb);
              };

              _proto.onMove = function onMove(cb) {
                this._eventTarget.on(SystemEventType.MOUSE_MOVE, cb);
              };

              _proto.onUp = function onUp(cb) {
                this._eventTarget.on(SystemEventType.MOUSE_UP, cb);
              };

              _proto.onWheel = function onWheel(cb) {
                this._eventTarget.on(SystemEventType.MOUSE_WHEEL, cb);
              };

              return MouseInputSource;
            }();

            var TouchInputSource = function () {
              function TouchInputSource() {
                this.support = void 0;
                this._canvas = void 0;
                this._eventTarget = new EventTarget();
                this.support = document.documentElement.ontouchstart !== undefined || document.ontouchstart !== undefined || navigator.msPointerEnabled;

                if (this.support) {
                  this._canvas = document.getElementById('GameCanvas');

                  if (!this._canvas && !TEST) {
                    console.warn('failed to access canvas');
                  }

                  this._registerEvent();
                }
              }

              var _proto = TouchInputSource.prototype;

              _proto._registerEvent = function _registerEvent() {
                var _this$_canvas, _this$_canvas2, _this$_canvas3, _this$_canvas4;

                (_this$_canvas = this._canvas) === null || _this$_canvas === void 0 ? void 0 : _this$_canvas.addEventListener('touchstart', this._createCallback(SystemEventType.TOUCH_START));
                (_this$_canvas2 = this._canvas) === null || _this$_canvas2 === void 0 ? void 0 : _this$_canvas2.addEventListener('touchmove', this._createCallback(SystemEventType.TOUCH_MOVE));
                (_this$_canvas3 = this._canvas) === null || _this$_canvas3 === void 0 ? void 0 : _this$_canvas3.addEventListener('touchend', this._createCallback(SystemEventType.TOUCH_END));
                (_this$_canvas4 = this._canvas) === null || _this$_canvas4 === void 0 ? void 0 : _this$_canvas4.addEventListener('touchcancel', this._createCallback(SystemEventType.TOUCH_CANCEL));
              };

              _proto._createCallback = function _createCallback(eventType) {
                var _this = this;

                return function (event) {
                  var canvasRect = _this._getCanvasRect();

                  var touchDataList = [];
                  var length = event.changedTouches.length;

                  for (var i = 0; i < length; ++i) {
                    var touch = event.changedTouches[i];

                    var location = _this._getLocation(touch);

                    var x = location.x - canvasRect.x;
                    var y = canvasRect.y + canvasRect.height - location.y;

                    if (legacyCC.view._isRotated) {
                      var tmp = x;
                      x = canvasRect.height - y;
                      y = tmp;
                    }

                    var touchData = {
                      identifier: touch.identifier,
                      x: x,
                      y: y,
                      force: touch.force
                    };
                    touchDataList.push(touchData);
                  }

                  var inputEvent = {
                    type: eventType,
                    changedTouches: touchDataList,
                    timestamp: performance.now()
                  };
                  event.stopPropagation();

                  if (event.target === _this._canvas) {
                    event.preventDefault();
                  }

                  if (event.type === 'touchstart') {
                    var _this$_canvas5;

                    (_this$_canvas5 = _this._canvas) === null || _this$_canvas5 === void 0 ? void 0 : _this$_canvas5.focus();
                  }

                  _this._eventTarget.emit(eventType, inputEvent);
                };
              };

              _proto._getCanvasRect = function _getCanvasRect() {
                var canvas = this._canvas;
                var box = canvas === null || canvas === void 0 ? void 0 : canvas.getBoundingClientRect();

                if (box) {
                  return new Rect(box.x, box.y, box.width, box.height);
                }

                return new Rect(0, 0, 0, 0);
              };

              _proto._getLocation = function _getLocation(event) {
                return new Vec2(event.clientX, event.clientY);
              };

              _proto.onStart = function onStart(cb) {
                this._eventTarget.on(SystemEventType.TOUCH_START, cb);
              };

              _proto.onMove = function onMove(cb) {
                this._eventTarget.on(SystemEventType.TOUCH_MOVE, cb);
              };

              _proto.onEnd = function onEnd(cb) {
                this._eventTarget.on(SystemEventType.TOUCH_END, cb);
              };

              _proto.onCancel = function onCancel(cb) {
                this._eventTarget.on(SystemEventType.TOUCH_CANCEL, cb);
              };

              return TouchInputSource;
            }();

            var Input = function () {
              function Input() {
                this._touch = new TouchInputSource();
                this._mouse = new MouseInputSource();
                this._keyboard = new KeyboardInputSource();
                this._accelerometer = new AccelerometerInputSource();
                this._inputBox = new InputBox();
                this._inputEventList = [];

                this._registerEvent();
              }

              var _proto = Input.prototype;

              _proto._registerEvent = function _registerEvent() {};

              _proto._pushEvent = function _pushEvent(inputEvent) {
                this._inputEventList.push(inputEvent);
              };

              _proto.pollEvent = function pollEvent() {
                return this._inputEventList.shift();
              };

              return Input;
            }();
            var input = new Input();

            var _vec2 = new Vec2();

            var EventMouse = exports('EventMouse', function (_Event) {
              _inheritsLoose(EventMouse, _Event);

              function EventMouse(eventType, bubbles, prevLoc) {
                var _this;

                _this = _Event.call(this, Event.MOUSE, bubbles) || this;
                _this.movementX = 0;
                _this.movementY = 0;
                _this.eventType = void 0;
                _this._button = EventMouse.BUTTON_MISSING;
                _this._x = 0;
                _this._y = 0;
                _this._prevX = 0;
                _this._prevY = 0;
                _this._scrollX = 0;
                _this._scrollY = 0;
                _this.eventType = eventType;

                if (prevLoc) {
                  _this._prevX = prevLoc.x;
                  _this._prevY = prevLoc.y;
                }

                return _this;
              }

              var _proto = EventMouse.prototype;

              _proto.setScrollData = function setScrollData(scrollX, scrollY) {
                this._scrollX = scrollX;
                this._scrollY = scrollY;
              };

              _proto.getScrollX = function getScrollX() {
                return this._scrollX;
              };

              _proto.getScrollY = function getScrollY() {
                return this._scrollY;
              };

              _proto.setLocation = function setLocation(x, y) {
                this._x = x;
                this._y = y;
              };

              _proto.getLocation = function getLocation(out) {
                if (!out) {
                  out = new Vec2();
                }

                Vec2.set(out, this._x, this._y);
                return out;
              };

              _proto.getLocationInView = function getLocationInView(out) {
                if (!out) {
                  out = new Vec2();
                }

                Vec2.set(out, this._x, legacyCC.view._designResolutionSize.height - this._y);
                return out;
              };

              _proto.getUILocation = function getUILocation(out) {
                if (!out) {
                  out = new Vec2();
                }

                Vec2.set(out, this._x, this._y);

                legacyCC.view._convertPointWithScale(out);

                return out;
              };

              _proto.getPreviousLocation = function getPreviousLocation(out) {
                if (!out) {
                  out = new Vec2();
                }

                Vec2.set(out, this._prevX, this._prevY);
                return out;
              };

              _proto.getUIPreviousLocation = function getUIPreviousLocation(out) {
                if (!out) {
                  out = new Vec2();
                }

                Vec2.set(out, this._prevX, this._prevY);

                legacyCC.view._convertPointWithScale(out);

                return out;
              };

              _proto.getDelta = function getDelta(out) {
                if (!out) {
                  out = new Vec2();
                }

                Vec2.set(out, this._x - this._prevX, this._y - this._prevY);
                return out;
              };

              _proto.getDeltaX = function getDeltaX() {
                return this._x - this._prevX;
              };

              _proto.getDeltaY = function getDeltaY() {
                return this._y - this._prevY;
              };

              _proto.getUIDelta = function getUIDelta(out) {
                if (!out) {
                  out = new Vec2();
                }

                Vec2.set(out, (this._x - this._prevX) / legacyCC.view.getScaleX(), (this._y - this._prevY) / legacyCC.view.getScaleY());
                return out;
              };

              _proto.getUIDeltaX = function getUIDeltaX() {
                return (this._x - this._prevX) / legacyCC.view.getScaleX();
              };

              _proto.getUIDeltaY = function getUIDeltaY() {
                return (this._y - this._prevY) / legacyCC.view.getScaleY();
              };

              _proto.setButton = function setButton(button) {
                this._button = button;
              };

              _proto.getButton = function getButton() {
                return this._button;
              };

              _proto.getLocationX = function getLocationX() {
                return this._x;
              };

              _proto.getLocationY = function getLocationY() {
                return this._y;
              };

              _proto.getUILocationX = function getUILocationX() {
                var viewport = legacyCC.view.getViewportRect();
                return (this._x - viewport.x) / legacyCC.view.getScaleX();
              };

              _proto.getUILocationY = function getUILocationY() {
                var viewport = legacyCC.view.getViewportRect();
                return (this._y - viewport.y) / legacyCC.view.getScaleY();
              };

              return EventMouse;
            }(Event));
            EventMouse.BUTTON_MISSING = -1;
            EventMouse.BUTTON_LEFT = 0;
            EventMouse.BUTTON_RIGHT = 2;
            EventMouse.BUTTON_MIDDLE = 1;
            EventMouse.BUTTON_4 = 3;
            EventMouse.BUTTON_5 = 4;
            EventMouse.BUTTON_6 = 5;
            EventMouse.BUTTON_7 = 6;
            EventMouse.BUTTON_8 = 7;
            var EventTouch = exports('EventTouch', function (_Event2) {
              _inheritsLoose(EventTouch, _Event2);

              function EventTouch(changedTouches, bubbles, eventCode, touches) {
                var _this2;

                _this2 = _Event2.call(this, Event.TOUCH, bubbles) || this;
                _this2.touch = null;
                _this2.simulate = false;
                _this2._eventCode = void 0;
                _this2._touches = void 0;
                _this2._allTouches = void 0;
                _this2._eventCode = eventCode || '';
                _this2._touches = changedTouches || [];
                _this2._allTouches = touches || [];
                return _this2;
              }

              var _proto2 = EventTouch.prototype;

              _proto2.getEventCode = function getEventCode() {
                return this._eventCode;
              };

              _proto2.getTouches = function getTouches() {
                return this._touches;
              };

              _proto2.getAllTouches = function getAllTouches() {
                return this._allTouches;
              };

              _proto2.setLocation = function setLocation(x, y) {
                if (this.touch) {
                  this.touch.setTouchInfo(this.touch.getID(), x, y);
                }
              };

              _proto2.getLocation = function getLocation(out) {
                return this.touch ? this.touch.getLocation(out) : new Vec2();
              };

              _proto2.getUILocation = function getUILocation(out) {
                return this.touch ? this.touch.getUILocation(out) : new Vec2();
              };

              _proto2.getLocationInView = function getLocationInView(out) {
                return this.touch ? this.touch.getLocationInView(out) : new Vec2();
              };

              _proto2.getPreviousLocation = function getPreviousLocation(out) {
                return this.touch ? this.touch.getPreviousLocation(out) : new Vec2();
              };

              _proto2.getStartLocation = function getStartLocation(out) {
                return this.touch ? this.touch.getStartLocation(out) : new Vec2();
              };

              _proto2.getUIStartLocation = function getUIStartLocation(out) {
                return this.touch ? this.touch.getUIStartLocation(out) : new Vec2();
              };

              _proto2.getID = function getID() {
                return this.touch ? this.touch.getID() : null;
              };

              _proto2.getDelta = function getDelta(out) {
                return this.touch ? this.touch.getDelta(out) : new Vec2();
              };

              _proto2.getUIDelta = function getUIDelta(out) {
                return this.touch ? this.touch.getUIDelta(out) : new Vec2();
              };

              _proto2.getDeltaX = function getDeltaX() {
                return this.touch ? this.touch.getDelta(_vec2).x : 0;
              };

              _proto2.getDeltaY = function getDeltaY() {
                return this.touch ? this.touch.getDelta(_vec2).y : 0;
              };

              _proto2.getLocationX = function getLocationX() {
                return this.touch ? this.touch.getLocationX() : 0;
              };

              _proto2.getLocationY = function getLocationY() {
                return this.touch ? this.touch.getLocationY() : 0;
              };

              return EventTouch;
            }(Event));
            EventTouch.MAX_TOUCHES = 5;
            var EventAcceleration = exports('EventAcceleration', function (_Event3) {
              _inheritsLoose(EventAcceleration, _Event3);

              function EventAcceleration(acc, bubbles) {
                var _this3;

                _this3 = _Event3.call(this, Event.ACCELERATION, bubbles) || this;
                _this3.acc = void 0;
                _this3.acc = acc;
                return _this3;
              }

              return EventAcceleration;
            }(Event));
            var EventKeyboard = exports('EventKeyboard', function (_Event4) {
              _inheritsLoose(EventKeyboard, _Event4);

              function EventKeyboard(keyCode, isPressed, bubbles) {
                var _this4;

                _this4 = _Event4.call(this, Event.KEYBOARD, bubbles) || this;
                _this4.keyCode = void 0;
                _this4.rawEvent = void 0;
                _this4.isPressed = void 0;

                if (typeof keyCode === 'number') {
                  _this4.keyCode = keyCode;
                } else {
                  _this4.keyCode = keyCode.keyCode;
                  _this4.rawEvent = keyCode;
                }

                _this4.isPressed = isPressed;
                return _this4;
              }

              return EventKeyboard;
            }(Event));
            Event.EventMouse = EventMouse;
            Event.EventTouch = EventTouch;
            Event.EventAcceleration = EventAcceleration;
            Event.EventKeyboard = EventKeyboard;

            var _vec2$1 = new Vec2();

            var Touch = exports('Touch', function () {
              function Touch(x, y, id) {
                if (id === void 0) {
                  id = 0;
                }

                this._point = new Vec2();
                this._prevPoint = new Vec2();
                this._lastModified = 0;
                this._id = 0;
                this._startPoint = new Vec2();
                this._startPointCaptured = false;
                this.setTouchInfo(id, x, y);
              }

              var _proto = Touch.prototype;

              _proto.getLocation = function getLocation(out) {
                if (!out) {
                  out = new Vec2();
                }

                out.set(this._point.x, this._point.y);
                return out;
              };

              _proto.getLocationX = function getLocationX() {
                return this._point.x;
              };

              _proto.getLocationY = function getLocationY() {
                return this._point.y;
              };

              _proto.getUILocation = function getUILocation(out) {
                if (!out) {
                  out = new Vec2();
                }

                out.set(this._point.x, this._point.y);

                legacyCC.view._convertPointWithScale(out);

                return out;
              };

              _proto.getUILocationX = function getUILocationX() {
                var viewport = legacyCC.view.getViewportRect();
                return (this._point.x - viewport.x) / legacyCC.view.getScaleX();
              };

              _proto.getUILocationY = function getUILocationY() {
                var viewport = legacyCC.view.getViewportRect();
                return (this._point.y - viewport.y) / legacyCC.view.getScaleY();
              };

              _proto.getPreviousLocation = function getPreviousLocation(out) {
                if (!out) {
                  out = new Vec2();
                }

                out.set(this._prevPoint.x, this._prevPoint.y);
                return out;
              };

              _proto.getUIPreviousLocation = function getUIPreviousLocation(out) {
                if (!out) {
                  out = new Vec2();
                }

                out.set(this._prevPoint.x, this._prevPoint.y);

                legacyCC.view._convertPointWithScale(out);

                return out;
              };

              _proto.getStartLocation = function getStartLocation(out) {
                if (!out) {
                  out = new Vec2();
                }

                out.set(this._startPoint.x, this._startPoint.y);
                return out;
              };

              _proto.getUIStartLocation = function getUIStartLocation(out) {
                if (!out) {
                  out = new Vec2();
                }

                out.set(this._startPoint.x, this._startPoint.y);

                legacyCC.view._convertPointWithScale(out);

                return out;
              };

              _proto.getDelta = function getDelta(out) {
                if (!out) {
                  out = new Vec2();
                }

                out.set(this._point);
                out.subtract(this._prevPoint);
                return out;
              };

              _proto.getUIDelta = function getUIDelta(out) {
                if (!out) {
                  out = new Vec2();
                }

                _vec2$1.set(this._point);

                _vec2$1.subtract(this._prevPoint);

                out.set(legacyCC.view.getScaleX(), legacyCC.view.getScaleY());
                Vec2.divide(out, _vec2$1, out);
                return out;
              };

              _proto.getLocationInView = function getLocationInView(out) {
                if (!out) {
                  out = new Vec2();
                }

                out.set(this._point.x, legacyCC.view._designResolutionSize.height - this._point.y);
                return out;
              };

              _proto.getPreviousLocationInView = function getPreviousLocationInView(out) {
                if (!out) {
                  out = new Vec2();
                }

                out.set(this._prevPoint.x, legacyCC.view._designResolutionSize.height - this._prevPoint.y);
                return out;
              };

              _proto.getStartLocationInView = function getStartLocationInView(out) {
                if (!out) {
                  out = new Vec2();
                }

                out.set(this._startPoint.x, legacyCC.view._designResolutionSize.height - this._startPoint.y);
                return out;
              };

              _proto.getID = function getID() {
                return this._id;
              };

              _proto.setTouchInfo = function setTouchInfo(id, x, y) {
                if (id === void 0) {
                  id = 0;
                }

                this._prevPoint = this._point;
                this._point = new Vec2(x || 0, y || 0);
                this._id = id;

                if (!this._startPointCaptured) {
                  this._startPoint = new Vec2(this._point);
                  this._startPointCaptured = true;
                }
              };

              _proto.setPoint = function setPoint(x, y) {
                if (typeof x === 'object') {
                  this._point.x = x.x;
                  this._point.y = x.y;
                } else {
                  this._point.x = x || 0;
                  this._point.y = y || 0;
                }

                this._lastModified = legacyCC.director.getCurrentTime();
              };

              _proto.setPrevPoint = function setPrevPoint(x, y) {
                if (typeof x === 'object') {
                  this._prevPoint = new Vec2(x.x, x.y);
                } else {
                  this._prevPoint = new Vec2(x || 0, y || 0);
                }

                this._lastModified = legacyCC.director.getCurrentTime();
              };

              _createClass(Touch, [{
                key: "lastModified",
                get: function get() {
                  return this._lastModified;
                }
              }]);

              return Touch;
            }());
            legacyCC.Touch = Touch;

            var Acceleration = function Acceleration(x, y, z, timestamp) {
              if (x === void 0) {
                x = 0;
              }

              if (y === void 0) {
                y = 0;
              }

              if (z === void 0) {
                z = 0;
              }

              if (timestamp === void 0) {
                timestamp = 0;
              }

              this.x = void 0;
              this.y = void 0;
              this.z = void 0;
              this.timestamp = void 0;
              this.x = x;
              this.y = y;
              this.z = z;
              this.timestamp = timestamp;
            };

            var TOUCH_TIMEOUT = macro.TOUCH_TIMEOUT;

            var _vec2$2 = new Vec2();

            var _preLocation = new Vec2();

            var InputManager = function () {
              function InputManager() {
                this._isRegisterEvent = false;
                this._preTouchPoint = new Vec2();
                this._prevMousePoint = new Vec2();
                this._preTouchPool = [];
                this._preTouchPoolPointer = 0;
                this._touches = [];
                this._touchesIntegerDict = {};
                this._indexBitsUsed = 0;
                this._maxTouches = 8;
                this._glView = null;
              }

              var _proto = InputManager.prototype;

              _proto.handleTouchesBegin = function handleTouchesBegin(touches) {
                var handleTouches = [];
                var locTouchIntDict = this._touchesIntegerDict;

                for (var i = 0; i < touches.length; ++i) {
                  var touch = touches[i];
                  var touchID = touch.getID();

                  if (touchID === null) {
                    continue;
                  }

                  var _index = locTouchIntDict[touchID];

                  if (_index === undefined) {
                    var unusedIndex = this._getUnUsedIndex();

                    if (unusedIndex === -1) {
                      logID(2300, unusedIndex);
                      continue;
                    }

                    touch.getLocation(_vec2$2);
                    var curTouch = new Touch(_vec2$2.x, _vec2$2.y, touchID);
                    this._touches[unusedIndex] = curTouch;
                    touch.getPreviousLocation(_vec2$2);
                    curTouch.setPrevPoint(_vec2$2);
                    locTouchIntDict[touchID] = unusedIndex;
                    handleTouches.push(curTouch);
                  }
                }

                if (handleTouches.length > 0) {
                  var touchEvent = new EventTouch(handleTouches, false, SystemEventType.TOUCH_START, macro.ENABLE_MULTI_TOUCH ? this._getUsefulTouches() : handleTouches);
                  eventManager.dispatchEvent(touchEvent);
                }
              };

              _proto.handleTouchesMove = function handleTouchesMove(touches) {
                var handleTouches = [];
                var locTouches = this._touches;

                for (var i = 0; i < touches.length; ++i) {
                  var touch = touches[i];
                  var touchID = touch.getID();

                  if (touchID === null) {
                    continue;
                  }

                  var _index2 = this._touchesIntegerDict[touchID];

                  if (_index2 === undefined) {
                    continue;
                  }

                  if (locTouches[_index2]) {
                    touch.getLocation(_vec2$2);

                    locTouches[_index2].setPoint(_vec2$2);

                    touch.getPreviousLocation(_vec2$2);

                    locTouches[_index2].setPrevPoint(_vec2$2);

                    handleTouches.push(locTouches[_index2]);
                  }
                }

                if (handleTouches.length > 0) {
                  var touchEvent = new EventTouch(handleTouches, false, SystemEventType.TOUCH_MOVE, macro.ENABLE_MULTI_TOUCH ? this._getUsefulTouches() : handleTouches);
                  eventManager.dispatchEvent(touchEvent);
                }
              };

              _proto.handleTouchesEnd = function handleTouchesEnd(touches) {
                var handleTouches = this.getSetOfTouchesEndOrCancel(touches);

                if (handleTouches.length > 0) {
                  var touchEvent = new EventTouch(handleTouches, false, SystemEventType.TOUCH_END, macro.ENABLE_MULTI_TOUCH ? this._getUsefulTouches() : handleTouches);
                  eventManager.dispatchEvent(touchEvent);
                }

                this._preTouchPool.length = 0;
              };

              _proto.handleTouchesCancel = function handleTouchesCancel(touches) {
                var handleTouches = this.getSetOfTouchesEndOrCancel(touches);

                if (handleTouches.length > 0) {
                  var touchEvent = new EventTouch(handleTouches, false, SystemEventType.TOUCH_CANCEL, macro.ENABLE_MULTI_TOUCH ? this._getUsefulTouches() : handleTouches);
                  eventManager.dispatchEvent(touchEvent);
                }

                this._preTouchPool.length = 0;
              };

              _proto.getSetOfTouchesEndOrCancel = function getSetOfTouchesEndOrCancel(touches) {
                var handleTouches = [];
                var locTouches = this._touches;
                var locTouchesIntDict = this._touchesIntegerDict;

                for (var i = 0; i < touches.length; ++i) {
                  var touch = touches[i];
                  var touchID = touch.getID();

                  if (touchID === null) {
                    continue;
                  }

                  var _index3 = locTouchesIntDict[touchID];

                  if (_index3 === undefined) {
                    continue;
                  }

                  if (locTouches[_index3]) {
                    touch.getLocation(_vec2$2);

                    locTouches[_index3].setPoint(_vec2$2);

                    touch.getPreviousLocation(_vec2$2);

                    locTouches[_index3].setPrevPoint(_vec2$2);

                    handleTouches.push(locTouches[_index3]);

                    this._removeUsedIndexBit(_index3);

                    delete locTouchesIntDict[touchID];
                  }
                }

                return handleTouches;
              };

              _proto._getPreTouch = function _getPreTouch(touch) {
                var preTouch = null;
                var locPreTouchPool = this._preTouchPool;
                var id = touch.getID();

                for (var i = locPreTouchPool.length - 1; i >= 0; i--) {
                  if (locPreTouchPool[i].getID() === id) {
                    preTouch = locPreTouchPool[i];
                    break;
                  }
                }

                if (!preTouch) {
                  preTouch = touch;
                }

                return preTouch;
              };

              _proto._setPreTouch = function _setPreTouch(touch) {
                var find = false;
                var locPreTouchPool = this._preTouchPool;
                var id = touch.getID();

                for (var i = locPreTouchPool.length - 1; i >= 0; i--) {
                  if (locPreTouchPool[i].getID() === id) {
                    locPreTouchPool[i] = touch;
                    find = true;
                    break;
                  }
                }

                if (!find) {
                  if (locPreTouchPool.length <= 50) {
                    locPreTouchPool.push(touch);
                  } else {
                    locPreTouchPool[this._preTouchPoolPointer] = touch;
                    this._preTouchPoolPointer = (this._preTouchPoolPointer + 1) % 50;
                  }
                }
              };

              _proto._getViewPixelRatio = function _getViewPixelRatio() {
                return this._glView ? this._glView._devicePixelRatio : 1;
              };

              _proto._getTouch = function _getTouch(inputEvent) {
                var locPreTouch = this._preTouchPoint;

                var pixelRatio = this._getViewPixelRatio();

                var x = inputEvent.x * pixelRatio;
                var y = inputEvent.y * pixelRatio;
                var touch = new Touch(x, y, 0);
                touch.setPrevPoint(locPreTouch.x, locPreTouch.y);
                locPreTouch.x = x;
                locPreTouch.y = y;
                return touch;
              };

              _proto._getMouseEvent = function _getMouseEvent(inputEvent) {
                var locPreMouse = this._prevMousePoint;
                var mouseEvent = new EventMouse(inputEvent.type, false, locPreMouse);

                var pixelRatio = this._getViewPixelRatio();

                locPreMouse.x = inputEvent.x * pixelRatio;
                locPreMouse.y = inputEvent.y * pixelRatio;

                if (legacyCC.GAME_VIEW) {
                  locPreMouse.x /= legacyCC.gameView.canvas.width / legacyCC.game.canvas.width;
                  locPreMouse.y /= legacyCC.gameView.canvas.height / legacyCC.game.canvas.height;
                }

                mouseEvent.setLocation(locPreMouse.x, locPreMouse.y);
                mouseEvent.setButton(inputEvent.button);

                if (inputEvent.movementX) {
                  mouseEvent.movementX = inputEvent.movementX;
                }

                if (inputEvent.movementY) {
                  mouseEvent.movementY = inputEvent.movementY;
                }

                return mouseEvent;
              };

              _proto._getTouchList = function _getTouchList(inputEvent) {
                var touchList = [];
                var locPreTouch = this._preTouchPoint;
                var length = inputEvent.changedTouches.length;

                var pixelRatio = this._getViewPixelRatio();

                for (var i = 0; i < length; i++) {
                  var touchData = inputEvent.changedTouches[i];
                  var x = touchData.x * pixelRatio;
                  var y = touchData.y * pixelRatio;
                  var touch = new Touch(x, y, touchData.identifier);

                  this._getPreTouch(touch).getLocation(_preLocation);

                  touch.setPrevPoint(_preLocation.x, _preLocation.y);

                  this._setPreTouch(touch);

                  locPreTouch.x = x;
                  locPreTouch.y = y;
                  touchList.push(touch);

                  if (!macro.ENABLE_MULTI_TOUCH) {
                    break;
                  }
                }

                return touchList;
              };

              _proto._getUnUsedIndex = function _getUnUsedIndex() {
                var temp = this._indexBitsUsed;
                var now = legacyCC.director.getCurrentTime();

                for (var i = 0; i < this._maxTouches; i++) {
                  if (!(temp & 0x00000001)) {
                    this._indexBitsUsed |= 1 << i;
                    return i;
                  } else {
                    var touch = this._touches[i];

                    if (now - touch.lastModified > TOUCH_TIMEOUT) {
                      this._removeUsedIndexBit(i);

                      var touchID = touch.getID();

                      if (touchID !== null) {
                        delete this._touchesIntegerDict[touchID];
                      }

                      return i;
                    }
                  }

                  temp >>= 1;
                }

                return -1;
              };

              _proto._removeUsedIndexBit = function _removeUsedIndexBit(index) {
                if (index < 0 || index >= this._maxTouches) {
                  return;
                }

                var temp = 1 << index;
                temp = ~temp;
                this._indexBitsUsed &= temp;
              };

              _proto._getUsefulTouches = function _getUsefulTouches() {
                var touches = [];
                var touchDict = this._touchesIntegerDict;

                for (var id in touchDict) {
                  var _index4 = parseInt(id);

                  var usedID = touchDict[_index4];

                  if (usedID === undefined || usedID === null) {
                    continue;
                  }

                  var touch = this._touches[usedID];
                  touches.push(touch);
                }

                return touches;
              };

              _proto.setAccelerometerEnabled = function setAccelerometerEnabled(isEnable) {
                if (isEnable) {
                  input._accelerometer.start();
                } else {
                  input._accelerometer.stop();
                }
              };

              _proto.setAccelerometerInterval = function setAccelerometerInterval(intervalInMileseconds) {
                input._accelerometer.setInterval(intervalInMileseconds);
              };

              _proto.registerSystemEvent = function registerSystemEvent() {
                if (this._isRegisterEvent) {
                  return;
                }

                this._glView = legacyCC.view;

                if (input._mouse.support) {
                  this._registerMouseEvents();
                }

                if (input._touch.support) {
                  this._registerTouchEvents();
                }

                if (input._keyboard.support) {
                  this._registerKeyboardEvent();
                }

                if (input._accelerometer.support) {
                  this._registerAccelerometerEvent();
                }

                this._isRegisterEvent = true;
              };

              _proto._registerMouseEvents = function _registerMouseEvents() {
                var _this = this;

                input._mouse.onDown(function (inputEvent) {
                  var mouseEvent = _this._getMouseEvent(inputEvent);

                  var touch = _this._getTouch(inputEvent);

                  _this.handleTouchesBegin([touch]);

                  eventManager.dispatchEvent(mouseEvent);
                });

                input._mouse.onMove(function (inputEvent) {
                  var mouseEvent = _this._getMouseEvent(inputEvent);

                  var touch = _this._getTouch(inputEvent);

                  _this.handleTouchesMove([touch]);

                  eventManager.dispatchEvent(mouseEvent);
                });

                input._mouse.onUp(function (inputEvent) {
                  var mouseEvent = _this._getMouseEvent(inputEvent);

                  var touch = _this._getTouch(inputEvent);

                  _this.handleTouchesEnd([touch]);

                  eventManager.dispatchEvent(mouseEvent);
                });

                input._mouse.onWheel(function (inputEvent) {
                  var mouseEvent = _this._getMouseEvent(inputEvent);

                  mouseEvent.setScrollData(inputEvent.deltaX, inputEvent.deltaY);
                  eventManager.dispatchEvent(mouseEvent);
                });
              };

              _proto._registerTouchEvents = function _registerTouchEvents() {
                var _this2 = this;

                input._touch.onStart(function (inputEvent) {
                  var touchList = _this2._getTouchList(inputEvent);

                  _this2.handleTouchesBegin(touchList);
                });

                input._touch.onMove(function (inputEvent) {
                  var touchList = _this2._getTouchList(inputEvent);

                  _this2.handleTouchesMove(touchList);
                });

                input._touch.onEnd(function (inputEvent) {
                  var touchList = _this2._getTouchList(inputEvent);

                  _this2.handleTouchesEnd(touchList);
                });

                input._touch.onCancel(function (inputEvent) {
                  var touchList = _this2._getTouchList(inputEvent);

                  _this2.handleTouchesCancel(touchList);
                });
              };

              _proto._registerKeyboardEvent = function _registerKeyboardEvent() {
                input._keyboard.onDown(function (inputEvent) {
                  eventManager.dispatchEvent(new EventKeyboard(inputEvent.code, true));
                });

                input._keyboard.onUp(function (inputEvent) {
                  eventManager.dispatchEvent(new EventKeyboard(inputEvent.code, false));
                });
              };

              _proto._registerAccelerometerEvent = function _registerAccelerometerEvent() {
                input._accelerometer.onChange(function (inputEvent) {
                  var x = inputEvent.x,
                      y = inputEvent.y,
                      z = inputEvent.z,
                      timestamp = inputEvent.timestamp;
                  eventManager.dispatchEvent(new EventAcceleration(new Acceleration(x, y, z, timestamp)));
                });
              };

              return InputManager;
            }();

            var inputManager = new InputManager();
            legacyCC.internal.inputManager = inputManager;

            var keyboardListener = null;
            var accelerationListener = null;
            var touchListener = null;
            var mouseListener = null;
            var SystemEvent = exports('SystemEvent', function (_EventTarget) {
              _inheritsLoose(SystemEvent, _EventTarget);

              function SystemEvent() {
                return _EventTarget.call(this) || this;
              }

              var _proto = SystemEvent.prototype;

              _proto.setAccelerometerEnabled = function setAccelerometerEnabled(isEnabled) {

                if (isEnabled && window.DeviceMotionEvent && typeof DeviceMotionEvent.requestPermission === 'function') {
                  DeviceMotionEvent.requestPermission().then(function (response) {
                    logID(3520, response);
                    inputManager.setAccelerometerEnabled(response === 'granted');
                  })["catch"](function (error) {
                    warnID(3521, error.message);
                    inputManager.setAccelerometerEnabled(false);
                  });
                } else {
                  inputManager.setAccelerometerEnabled(isEnabled);
                }
              };

              _proto.setAccelerometerInterval = function setAccelerometerInterval(interval) {

                inputManager.setAccelerometerInterval(interval);
              };

              _proto.on = function on(type, callback, target, once) {

                _EventTarget.prototype.on.call(this, type, callback, target, once);

                if (type === SystemEventType.KEY_DOWN || type === SystemEventType.KEY_UP) {
                  if (!keyboardListener) {
                    keyboardListener = EventListener.create({
                      event: EventListener.KEYBOARD,
                      onKeyPressed: function onKeyPressed(keyCode, event) {
                        event.type = SystemEventType.KEY_DOWN;
                        systemEvent.emit(event.type, event);
                      },
                      onKeyReleased: function onKeyReleased(keyCode, event) {
                        event.type = SystemEventType.KEY_UP;
                        systemEvent.emit(event.type, event);
                      }
                    });
                    eventManager.addListener(keyboardListener, 256);
                  }
                }

                if (type === SystemEventType.DEVICEMOTION) {
                  if (!accelerationListener) {
                    accelerationListener = EventListener.create({
                      event: EventListener.ACCELERATION,
                      callback: function callback(acc, event) {
                        event.type = SystemEventType.DEVICEMOTION;
                        legacyCC.systemEvent.emit(event.type, event);
                      }
                    });
                    eventManager.addListener(accelerationListener, 256);
                  }
                }

                if (type === SystemEventType.TOUCH_START || type === SystemEventType.TOUCH_MOVE || type === SystemEventType.TOUCH_END || type === SystemEventType.TOUCH_CANCEL) {
                  if (!touchListener) {
                    touchListener = EventListener.create({
                      event: EventListener.TOUCH_ONE_BY_ONE,
                      onTouchBegan: function onTouchBegan(touch, event) {
                        event.type = SystemEventType.TOUCH_START;
                        legacyCC.systemEvent.emit(event.type, touch, event);
                        return true;
                      },
                      onTouchMoved: function onTouchMoved(touch, event) {
                        event.type = SystemEventType.TOUCH_MOVE;
                        legacyCC.systemEvent.emit(event.type, touch, event);
                      },
                      onTouchEnded: function onTouchEnded(touch, event) {
                        event.type = SystemEventType.TOUCH_END;
                        legacyCC.systemEvent.emit(event.type, touch, event);
                      },
                      onTouchCancelled: function onTouchCancelled(touch, event) {
                        event.type = SystemEventType.TOUCH_CANCEL;
                        legacyCC.systemEvent.emit(event.type, touch, event);
                      }
                    });
                    eventManager.addListener(touchListener, 256);
                  }
                }

                if (type === SystemEventType.MOUSE_DOWN || type === SystemEventType.MOUSE_MOVE || type === SystemEventType.MOUSE_UP || type === SystemEventType.MOUSE_WHEEL) {
                  if (!mouseListener) {
                    mouseListener = EventListener.create({
                      event: EventListener.MOUSE,
                      onMouseDown: function onMouseDown(event) {
                        event.type = SystemEventType.MOUSE_DOWN;
                        legacyCC.systemEvent.emit(event.type, event);
                      },
                      onMouseMove: function onMouseMove(event) {
                        event.type = SystemEventType.MOUSE_MOVE;
                        legacyCC.systemEvent.emit(event.type, event);
                      },
                      onMouseUp: function onMouseUp(event) {
                        event.type = SystemEventType.MOUSE_UP;
                        legacyCC.systemEvent.emit(event.type, event);
                      },
                      onMouseScroll: function onMouseScroll(event) {
                        event.type = SystemEventType.MOUSE_WHEEL;
                        legacyCC.systemEvent.emit(event.type, event);
                      }
                    });
                    eventManager.addListener(mouseListener, 256);
                  }
                }

                return callback;
              };

              _proto.off = function off(type, callback, target) {

                _EventTarget.prototype.off.call(this, type, callback, target);

                if (keyboardListener && (type === SystemEventType.KEY_DOWN || type === SystemEventType.KEY_UP)) {
                  var hasKeyDownEventListener = this.hasEventListener(SystemEventType.KEY_DOWN);
                  var hasKeyUpEventListener = this.hasEventListener(SystemEventType.KEY_UP);

                  if (!hasKeyDownEventListener && !hasKeyUpEventListener) {
                    eventManager.removeListener(keyboardListener);
                    keyboardListener = null;
                  }
                }

                if (accelerationListener && type === SystemEventType.DEVICEMOTION) {
                  eventManager.removeListener(accelerationListener);
                  accelerationListener = null;
                }

                if (touchListener && (type === SystemEventType.TOUCH_START || type === SystemEventType.TOUCH_MOVE || type === SystemEventType.TOUCH_END || type === SystemEventType.TOUCH_CANCEL)) {
                  var hasTouchStart = this.hasEventListener(SystemEventType.TOUCH_START);
                  var hasTouchMove = this.hasEventListener(SystemEventType.TOUCH_MOVE);
                  var hasTouchEnd = this.hasEventListener(SystemEventType.TOUCH_END);
                  var hasTouchCancel = this.hasEventListener(SystemEventType.TOUCH_CANCEL);

                  if (!hasTouchStart && !hasTouchMove && !hasTouchEnd && !hasTouchCancel) {
                    eventManager.removeListener(touchListener);
                    touchListener = null;
                  }
                }

                if (mouseListener && (type === SystemEventType.MOUSE_DOWN || type === SystemEventType.MOUSE_MOVE || type === SystemEventType.MOUSE_UP || type === SystemEventType.MOUSE_WHEEL)) {
                  var hasMouseDown = this.hasEventListener(SystemEventType.MOUSE_DOWN);
                  var hasMouseMove = this.hasEventListener(SystemEventType.MOUSE_MOVE);
                  var hasMouseUp = this.hasEventListener(SystemEventType.MOUSE_UP);
                  var hasMouseWheel = this.hasEventListener(SystemEventType.MOUSE_WHEEL);

                  if (!hasMouseDown && !hasMouseMove && !hasMouseUp && !hasMouseWheel) {
                    eventManager.removeListener(mouseListener);
                    mouseListener = null;
                  }
                }
              };

              return SystemEvent;
            }(EventTarget));
            SystemEvent.EventType = SystemEventType;
            legacyCC.SystemEvent = SystemEvent;
            var systemEvent = exports('systemEvent', new SystemEvent());
            legacyCC.systemEvent = systemEvent;

            var viewSize = system.getViewSize();
            var pixelRatio = system.pixelRatio;
            var sys = exports('sys', {
              NetworkType: NetworkType,
              Language: Language,
              OS: OS,
              Platform: Platform,
              BrowserType: BrowserType,
              isNative: system.isNative,
              isBrowser: system.isBrowser,
              isMobile: system.isMobile,
              isLittleEndian: system.isLittleEndian,
              platform: system.platform,
              language: system.language,
              languageCode: system.nativeLanguage,
              os: system.os,
              osVersion: system.osVersion,
              osMainVersion: system.osMainVersion,
              browserType: system.browserType,
              browserVersion: system.browserVersion,
              windowPixelResolution: {
                width: viewSize.width * pixelRatio,
                height: viewSize.height * pixelRatio
              },
              capabilities: {
                canvas: system.supportCapability.canvas,
                opengl: system.supportCapability.gl,
                webp: system.supportCapability.webp,
                imageBitmap: system.supportCapability.imageBitmap,
                touches: false,
                mouse: false,
                keyboard: false,
                accelerometer: false
              },
              localStorage: null,
              getNetworkType: function getNetworkType() {
                return system.networkType;
              },
              getBatteryLevel: function getBatteryLevel() {
                return system.getBatteryLevel();
              },
              garbageCollect: function garbageCollect() {
                system.triggerGC();
              },
              isObjectValid: function isObjectValid(obj) {
                if (obj === null || obj === undefined) {
                  return false;
                }

                return true;
              },
              dump: function dump() {
                var str = '';
                str += "isMobile : " + this.isMobile + "\r\n";
                str += "language : " + this.language + "\r\n";
                str += "browserType : " + this.browserType + "\r\n";
                str += "browserVersion : " + this.browserVersion + "\r\n";
                str += "capabilities : " + JSON.stringify(this.capabilities) + "\r\n";
                str += "os : " + this.os + "\r\n";
                str += "osVersion : " + this.osVersion + "\r\n";
                str += "platform : " + this.platform + "\r\n";
                str += "Using " + (legacyCC.game.renderType === legacyCC.game.RENDER_TYPE_WEBGL ? 'WEBGL' : 'CANVAS') + " renderer.\r\n";
                log(str);
              },
              openURL: function openURL(url) {
                system.openURL(url);
              },
              now: function now() {
                return system.now();
              },
              restartVM: function restartVM() {
                system.restartJSVM();
              },
              getSafeAreaRect: function getSafeAreaRect() {
                var locView = legacyCC.view;
                var edge = system.getSafeAreaEdge();
                var viewSize = system.getViewSize();
                var leftBottom = new Vec2(edge.left, viewSize.height - edge.bottom);
                var rightTop = new Vec2(viewSize.width - edge.right, edge.top);
                var relatedPos = {
                  left: 0,
                  top: 0,
                  width: viewSize.width,
                  height: viewSize.height
                };
                locView.convertToLocationInView(leftBottom.x, leftBottom.y, relatedPos, leftBottom);
                locView.convertToLocationInView(rightTop.x, rightTop.y, relatedPos, rightTop);

                locView._convertPointWithScale(leftBottom);

                locView._convertPointWithScale(rightTop);

                var x = leftBottom.x;
                var y = leftBottom.y;
                var width = rightTop.x - leftBottom.x;
                var height = rightTop.y - leftBottom.y;
                return new Rect(x, y, width, height);
              },
              __init: function __init() {
                try {
                  var localStorage = sys.localStorage = window.localStorage;
                  localStorage.setItem('storage', '');
                  localStorage.removeItem('storage');
                  localStorage = null;
                } catch (e) {
                  var warn = function warn() {
                    warnID(5200);
                  };

                  sys.localStorage = {
                    getItem: warn,
                    setItem: warn,
                    removeItem: warn,
                    clear: warn
                  };
                }

                var win = window;
                var nav = win.navigator;
                var doc = document;
                var docEle = doc.documentElement;
                var capabilities = sys.capabilities;

                if (docEle.ontouchstart !== undefined || doc.ontouchstart !== undefined || nav.msPointerEnabled) {
                  capabilities.touches = true;
                }

                if (docEle.onmouseup !== undefined) {
                  capabilities.mouse = true;
                }

                if (docEle.onkeyup !== undefined) {
                  capabilities.keyboard = true;
                }

                if (win.DeviceMotionEvent || win.DeviceOrientationEvent) {
                  capabilities.accelerometer = true;
                }

                sys.__isWebIOS14OrIPadOS14Env = (sys.os === OS.IOS || sys.os === OS.OSX) && system.isBrowser && /(OS 1[4-9])|(Version\/1[4-9])/.test(window.navigator.userAgent);
                system.onViewResize(function () {
                  var viewSize = system.getViewSize();
                  sys.windowPixelResolution = {
                    width: Math.round(viewSize.width * pixelRatio),
                    height: Math.round(viewSize.height * pixelRatio)
                  };
                });
              }
            });

            sys.__init();

            legacyCC.sys = sys;

            var _dec$f, _dec2$7, _dec3$4, _dec4$2, _class$f, _class2$e, _descriptor$c, _descriptor2$7, _descriptor3$6, _temp$e;
            var RenderStage = exports('RenderStage', (_dec$f = ccclass('RenderStage'), _dec2$7 = displayOrder(), _dec3$4 = displayOrder(), _dec4$2 = displayOrder(), _dec$f(_class$f = (_class2$e = (_temp$e = function () {
              function RenderStage() {
                _initializerDefineProperty(this, "_name", _descriptor$c, this);

                _initializerDefineProperty(this, "_priority", _descriptor2$7, this);

                _initializerDefineProperty(this, "_tag", _descriptor3$6, this);
              }

              var _proto = RenderStage.prototype;

              _proto.initialize = function initialize(info) {
                this._name = info.name;
                this._priority = info.priority;

                if (info.tag) {
                  this._tag = info.tag;
                }

                return true;
              };

              _proto.activate = function activate(pipeline, flow) {
                this._pipeline = pipeline;
                this._flow = flow;
              };

              _createClass(RenderStage, [{
                key: "name",
                get: function get() {
                  return this._name;
                }
              }, {
                key: "priority",
                get: function get() {
                  return this._priority;
                }
              }, {
                key: "tag",
                get: function get() {
                  return this._tag;
                }
              }]);

              return RenderStage;
            }(), _temp$e), (_descriptor$c = _applyDecoratedDescriptor(_class2$e.prototype, "_name", [_dec2$7, serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return '';
              }
            }), _descriptor2$7 = _applyDecoratedDescriptor(_class2$e.prototype, "_priority", [_dec3$4, serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor3$6 = _applyDecoratedDescriptor(_class2$e.prototype, "_tag", [_dec4$2, serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            })), _class2$e)) || _class$f));
            legacyCC.RenderStage = RenderStage;

            var _dec$g, _dec2$8, _dec3$5, _dec4$3, _dec5$1, _dec6$1, _class$g, _class2$f, _descriptor$d, _descriptor2$8, _descriptor3$7, _descriptor4$5, _temp$f;
            var RenderFlow = exports('RenderFlow', (_dec$g = ccclass('RenderFlow'), _dec2$8 = displayOrder(), _dec3$5 = displayOrder(), _dec4$3 = displayOrder(), _dec5$1 = displayOrder(), _dec6$1 = type([RenderStage]), _dec$g(_class$g = (_class2$f = (_temp$f = function () {
              function RenderFlow() {
                _initializerDefineProperty(this, "_name", _descriptor$d, this);

                _initializerDefineProperty(this, "_priority", _descriptor2$8, this);

                _initializerDefineProperty(this, "_tag", _descriptor3$7, this);

                _initializerDefineProperty(this, "_stages", _descriptor4$5, this);
              }

              var _proto = RenderFlow.prototype;

              _proto.initialize = function initialize(info) {
                this._name = info.name;
                this._priority = info.priority;
                this._stages = info.stages;

                if (info.tag) {
                  this._tag = info.tag;
                }

                return true;
              };

              _proto.activate = function activate(pipeline) {
                this._pipeline = pipeline;

                this._stages.sort(function (a, b) {
                  return a.priority - b.priority;
                });

                for (var i = 0, len = this._stages.length; i < len; i++) {
                  this._stages[i].activate(pipeline, this);
                }
              };

              _proto.render = function render(camera) {
                for (var i = 0, len = this._stages.length; i < len; i++) {
                  this._stages[i].render(camera);
                }
              };

              _proto.destroy = function destroy() {
                for (var i = 0, len = this._stages.length; i < len; i++) {
                  this._stages[i].destroy();
                }

                this._stages.length = 0;
              };

              _createClass(RenderFlow, [{
                key: "name",
                get: function get() {
                  return this._name;
                }
              }, {
                key: "priority",
                get: function get() {
                  return this._priority;
                }
              }, {
                key: "tag",
                get: function get() {
                  return this._tag;
                }
              }, {
                key: "stages",
                get: function get() {
                  return this._stages;
                }
              }, {
                key: "pipeline",
                get: function get() {
                  return this._pipeline;
                }
              }]);

              return RenderFlow;
            }(), _temp$f), (_descriptor$d = _applyDecoratedDescriptor(_class2$f.prototype, "_name", [_dec2$8, serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return '';
              }
            }), _descriptor2$8 = _applyDecoratedDescriptor(_class2$f.prototype, "_priority", [_dec3$5, serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor3$7 = _applyDecoratedDescriptor(_class2$f.prototype, "_tag", [_dec4$3, serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor4$5 = _applyDecoratedDescriptor(_class2$f.prototype, "_stages", [_dec5$1, _dec6$1, serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            })), _class2$f)) || _class$g));
            legacyCC.RenderFlow = RenderFlow;

            var _dec$h, _class$h, _class2$g, _descriptor$e, _descriptor2$9, _descriptor3$8, _descriptor4$6, _class3$9, _temp$g;
            var EffectAsset = exports('EffectAsset', (_dec$h = ccclass('cc.EffectAsset'), _dec$h(_class$h = (_class2$g = (_temp$g = _class3$9 = function (_Asset) {
              _inheritsLoose(EffectAsset, _Asset);

              function EffectAsset() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "techniques", _descriptor$e, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "shaders", _descriptor2$9, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "combinations", _descriptor3$8, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "hideInEditor", _descriptor4$6, _assertThisInitialized(_this));

                return _this;
              }

              EffectAsset.register = function register(asset) {
                EffectAsset._effects[asset.name] = asset;
              };

              EffectAsset.remove = function remove(name) {
                if (EffectAsset._effects[name]) {
                  delete EffectAsset._effects[name];
                  return;
                }

                for (var n in EffectAsset._effects) {
                  if (EffectAsset._effects[n]._uuid === name) {
                    delete EffectAsset._effects[n];
                    return;
                  }
                }
              };

              EffectAsset.get = function get(name) {
                if (EffectAsset._effects[name]) {
                  return EffectAsset._effects[name];
                }

                for (var n in EffectAsset._effects) {
                  if (EffectAsset._effects[n]._uuid === name) {
                    return EffectAsset._effects[n];
                  }
                }

                return null;
              };

              EffectAsset.getAll = function getAll() {
                return EffectAsset._effects;
              };

              var _proto = EffectAsset.prototype;

              _proto.onLoaded = function onLoaded() {
                programLib.register(this);
                EffectAsset.register(this);

                {
                  legacyCC.game.once(legacyCC.Game.EVENT_ENGINE_INITED, this._precompile, this);
                }
              };

              _proto._precompile = function _precompile() {
                var _this2 = this;

                var root = legacyCC.director.root;

                var _loop = function _loop(i) {
                  var shader = _this2.shaders[i];
                  var combination = _this2.combinations[i];

                  if (!combination) {
                    return "continue";
                  }

                  var defines = Object.keys(combination).reduce(function (out, name) {
                    return out.reduce(function (acc, cur) {
                      var choices = combination[name];

                      for (var _i = 0; _i < choices.length; ++_i) {
                        var _defines = _extends({}, cur);

                        _defines[name] = choices[_i];
                        acc.push(_defines);
                      }

                      return acc;
                    }, []);
                  }, [{}]);
                  defines.forEach(function (defines) {
                    return programLib.getGFXShader(root.device, shader.name, defines, root.pipeline);
                  });
                };

                for (var i = 0; i < this.shaders.length; i++) {
                  var _ret = _loop(i);

                  if (_ret === "continue") continue;
                }
              };

              _proto.destroy = function destroy() {
                EffectAsset.remove(this.name);
                return _Asset.prototype.destroy.call(this);
              };

              _proto.initDefault = function initDefault(uuid) {
                _Asset.prototype.initDefault.call(this, uuid);

                var effect = EffectAsset.get('unlit');
                this.name = 'unlit';
                this.shaders = effect.shaders;
                this.combinations = effect.combinations;
                this.techniques = effect.techniques;
              };

              _proto.validate = function validate() {
                return this.techniques.length > 0 && this.shaders.length > 0;
              };

              return EffectAsset;
            }(Asset), _class3$9._effects = {}, _temp$g), (_descriptor$e = _applyDecoratedDescriptor(_class2$g.prototype, "techniques", [serializable, editable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor2$9 = _applyDecoratedDescriptor(_class2$g.prototype, "shaders", [serializable, editable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor3$8 = _applyDecoratedDescriptor(_class2$g.prototype, "combinations", [serializable, editable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor4$6 = _applyDecoratedDescriptor(_class2$g.prototype, "hideInEditor", [serializable, editorOnly], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            })), _class2$g)) || _class$h));
            legacyCC.EffectAsset = EffectAsset;

            var _dec$i, _dec2$9, _dec3$6, _dec4$4, _dec5$2, _class$i, _class2$h, _descriptor$f, _descriptor2$a, _temp$h;
            var idGenerator$3 = new IDGenerator('RenderTex');

            var _colorAttachment = new ColorAttachment();

            _colorAttachment.endAccesses = [AccessType.FRAGMENT_SHADER_READ_TEXTURE];

            var _depthStencilAttachment = new DepthStencilAttachment();

            var passInfo = new RenderPassInfo([_colorAttachment], _depthStencilAttachment);
            var _windowInfo = {
              width: 1,
              height: 1,
              renderPassInfo: passInfo
            };
            var RenderTexture = exports('RenderTexture', (_dec$i = ccclass('cc.RenderTexture'), _dec2$9 = rangeMin(), _dec3$6 = rangeMax(), _dec4$4 = rangeMin(), _dec5$2 = rangeMax(), _dec$i(_class$i = (_class2$h = (_temp$h = function (_Asset) {
              _inheritsLoose(RenderTexture, _Asset);

              function RenderTexture() {
                var _this;

                _this = _Asset.call(this) || this;

                _initializerDefineProperty(_this, "_width", _descriptor$f, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_height", _descriptor2$a, _assertThisInitialized(_this));

                _this._textureHash = 0;
                _this._id = void 0;
                _this._window = null;
                _this._id = idGenerator$3.getNewId();
                _this._textureHash = murmurhash2_32_gc(_this._id, 666);
                return _this;
              }

              var _proto = RenderTexture.prototype;

              _proto.getHash = function getHash() {
                return this._textureHash;
              };

              _proto.initialize = function initialize(info) {
                this._name = info.name || '';
                this._width = info.width;
                this._height = info.height;

                this._initWindow(info);
              };

              _proto.reset = function reset(info) {
                this.initialize(info);
              };

              _proto.destroy = function destroy() {
                if (this._window) {
                  var root = legacyCC.director.root;
                  root.destroyWindow(this._window);
                  this._window = null;
                }

                return _Asset.prototype.destroy.call(this);
              };

              _proto.resize = function resize(width, height) {
                this._width = width;
                this._height = height;

                if (this._window) {
                  this._window.resize(width, height);
                }

                this.emit('resize', this._window);
              };

              _proto.getGFXTexture = function getGFXTexture() {
                return this._window && this._window.framebuffer.colorTextures[0];
              };

              _proto.getGFXSampler = function getGFXSampler() {
                var root = legacyCC.director.root;
                return samplerLib.getSampler(root.device, defaultSamplerHash);
              };

              _proto.getSamplerHash = function getSamplerHash() {
                return defaultSamplerHash;
              };

              _proto.onLoaded = function onLoaded() {
                this._initWindow();

                this.loaded = true;
                this.emit('load');
              };

              _proto._initWindow = function _initWindow(info) {
                var root = legacyCC.director.root;
                _windowInfo.title = this._name;
                _windowInfo.width = this._width;
                _windowInfo.height = this._height;
                _windowInfo.renderPassInfo = info && info.passInfo ? info.passInfo : passInfo;

                if (this._window) {
                  this._window.destroy();

                  this._window.initialize(root.device, _windowInfo);
                } else {
                  this._window = root.createWindow(_windowInfo);
                }
              };

              _proto.initDefault = function initDefault(uuid) {
                _Asset.prototype.initDefault.call(this, uuid);

                this._width = this._height = 1;

                this._initWindow();
              };

              _proto.validate = function validate() {
                return this.width >= 1 && this.width <= 2048 && this.height >= 1 && this.height <= 2048;
              };

              _createClass(RenderTexture, [{
                key: "width",
                get: function get() {
                  return this._width;
                }
              }, {
                key: "height",
                get: function get() {
                  return this._height;
                }
              }, {
                key: "window",
                get: function get() {
                  return this._window;
                }
              }]);

              return RenderTexture;
            }(Asset), _temp$h), (_descriptor$f = _applyDecoratedDescriptor(_class2$h.prototype, "_width", [serializable, _dec2$9, _dec3$6], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1;
              }
            }), _descriptor2$a = _applyDecoratedDescriptor(_class2$h.prototype, "_height", [serializable, _dec4$4, _dec5$2], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1;
              }
            })), _class2$h)) || _class$i));
            legacyCC.RenderTexture = RenderTexture;

            var _dec$j, _dec2$a, _class$j, _class2$i, _descriptor$g, _descriptor2$b, _descriptor3$9, _descriptor4$7, _descriptor5$4, _temp$i;
            var Material = exports('Material', (_dec$j = ccclass('cc.Material'), _dec2$a = type(EffectAsset), _dec$j(_class$j = (_class2$i = (_temp$i = function (_Asset) {
              _inheritsLoose(Material, _Asset);

              Material.getHash = function getHash(material) {
                var hash = 0;

                for (var _iterator = _createForOfIteratorHelperLoose(material.passes), _step; !(_step = _iterator()).done;) {
                  var pass = _step.value;
                  hash ^= pass.hash;
                }

                return hash;
              };

              function Material() {
                var _this;

                _this = _Asset.call(this) || this;

                _initializerDefineProperty(_this, "_effectAsset", _descriptor$g, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_techIdx", _descriptor2$b, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_defines", _descriptor3$9, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_states", _descriptor4$7, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_props", _descriptor5$4, _assertThisInitialized(_this));

                _this._passes = [];
                _this._hash = 0;
                _this.loaded = false;
                return _this;
              }

              var _proto = Material.prototype;

              _proto.initialize = function initialize(info) {
                if (this._passes.length) {
                  warnID(12005);
                  return;
                }

                if (!this._defines) {
                  this._defines = [];
                }

                if (!this._states) {
                  this._states = [];
                }

                if (!this._props) {
                  this._props = [];
                }

                if (info.technique !== undefined) {
                  this._techIdx = info.technique;
                }

                if (info.effectAsset) {
                  this._effectAsset = info.effectAsset;
                } else if (info.effectName) {
                  this._effectAsset = EffectAsset.get(info.effectName);
                }

                if (info.defines) {
                  this._prepareInfo(info.defines, this._defines);
                }

                if (info.states) {
                  this._prepareInfo(info.states, this._states);
                }

                this._update();
              };

              _proto.reset = function reset(info) {
                this.initialize(info);
              };

              _proto.destroy = function destroy() {
                this._doDestroy();

                return _Asset.prototype.destroy.call(this);
              };

              _proto.recompileShaders = function recompileShaders(overrides, passIdx) {
                console.warn("Shaders in material asset '" + this.name + "' cannot be modified at runtime, please instantiate the material first.");
              };

              _proto.overridePipelineStates = function overridePipelineStates(overrides, passIdx) {
                console.warn("Pipeline states in material asset '" + this.name + "' cannot be modified at runtime, please instantiate the material first.");
              };

              _proto.onLoaded = function onLoaded() {
                this._update();

                this.loaded = true;
                this.emit('load');
              };

              _proto.resetUniforms = function resetUniforms(clearPasses) {
                if (clearPasses === void 0) {
                  clearPasses = true;
                }

                this._props.length = this._passes.length;

                for (var i = 0; i < this._props.length; i++) {
                  this._props[i] = {};
                }

                if (!clearPasses) {
                  return;
                }

                for (var _iterator2 = _createForOfIteratorHelperLoose(this._passes), _step2; !(_step2 = _iterator2()).done;) {
                  var pass = _step2.value;
                  pass.resetUBOs();
                  pass.resetTextures();
                }
              };

              _proto.setProperty = function setProperty(name, val, passIdx) {
                var success = false;

                if (passIdx === undefined) {
                  var passes = this._passes;
                  var len = passes.length;

                  for (var i = 0; i < len; i++) {
                    var pass = passes[i];

                    if (this._uploadProperty(pass, name, val)) {
                      this._props[pass.propertyIndex][name] = val;
                      success = true;
                    }
                  }
                } else {
                  if (passIdx >= this._passes.length) {
                    console.warn("illegal pass index: " + passIdx + ".");
                    return;
                  }

                  var _pass = this._passes[passIdx];

                  if (this._uploadProperty(_pass, name, val)) {
                    this._props[_pass.propertyIndex][name] = val;
                    success = true;
                  }
                }

                if (!success) {
                  console.warn("illegal property name: " + name + ".");
                }
              };

              _proto.getProperty = function getProperty(name, passIdx) {
                if (passIdx === undefined) {
                  var propsArray = this._props;
                  var len = propsArray.length;

                  for (var i = 0; i < len; i++) {
                    var props = propsArray[i];

                    if (name in props) {
                      return props[name];
                    }
                  }
                } else {
                  if (passIdx >= this._props.length) {
                    console.warn("illegal pass index: " + passIdx + ".");
                    return null;
                  }

                  var _props = this._props[this._passes[passIdx].propertyIndex];

                  if (name in _props) {
                    return _props[name];
                  }
                }

                return null;
              };

              _proto.copy = function copy(mat) {
                this._techIdx = mat._techIdx;
                this._props.length = mat._props.length;

                for (var i = 0; i < mat._props.length; i++) {
                  this._props[i] = _extends({}, mat._props[i]);
                }

                this._defines.length = mat._defines.length;

                for (var _i = 0; _i < mat._defines.length; _i++) {
                  this._defines[_i] = _extends({}, mat._defines[_i]);
                }

                this._states.length = mat._states.length;

                for (var _i2 = 0; _i2 < mat._states.length; _i2++) {
                  this._states[_i2] = _extends({}, mat._states[_i2]);
                }

                this._effectAsset = mat._effectAsset;

                this._update();
              };

              _proto._prepareInfo = function _prepareInfo(patch, cur) {
                var patchArray = patch;

                if (!Array.isArray(patchArray)) {
                  var len = this._effectAsset ? this._effectAsset.techniques[this._techIdx].passes.length : 1;
                  patchArray = Array(len).fill(patchArray);
                }

                for (var i = 0; i < patchArray.length; ++i) {
                  Object.assign(cur[i] || (cur[i] = {}), patchArray[i]);
                }
              };

              _proto._createPasses = function _createPasses() {
                var tech = this._effectAsset.techniques[this._techIdx || 0];

                if (!tech) {
                  return [];
                }

                var passNum = tech.passes.length;
                var passes = [];

                for (var k = 0; k < passNum; ++k) {
                  var passInfo = tech.passes[k];
                  var propIdx = passInfo.passIndex = k;
                  var defines = passInfo.defines = this._defines[propIdx] || (this._defines[propIdx] = {});
                  var states = passInfo.stateOverrides = this._states[propIdx] || (this._states[propIdx] = {});

                  if (passInfo.propertyIndex !== undefined) {
                    Object.assign(defines, this._defines[passInfo.propertyIndex]);
                    Object.assign(states, this._states[passInfo.propertyIndex]);
                  }

                  if (passInfo.embeddedMacros !== undefined) {
                    Object.assign(defines, passInfo.embeddedMacros);
                  }

                  if (passInfo["switch"] && !defines[passInfo["switch"]]) {
                    continue;
                  }

                  var pass = new Pass(legacyCC.director.root);
                  pass.initialize(passInfo);
                  passes.push(pass);
                }

                return passes;
              };

              _proto._update = function _update(keepProps) {
                var _this2 = this;

                if (keepProps === void 0) {
                  keepProps = true;
                }

                if (this._effectAsset) {
                  this._passes = this._createPasses();
                  var totalPasses = this._effectAsset.techniques[this._techIdx].passes.length;
                  this._props.length = totalPasses;

                  if (keepProps) {
                    this._passes.forEach(function (pass, i) {
                      var props = _this2._props[i];

                      if (!props) {
                        props = _this2._props[i] = {};
                      }

                      if (pass.propertyIndex !== undefined) {
                        Object.assign(props, _this2._props[pass.propertyIndex]);
                      }

                      for (var p in props) {
                        _this2._uploadProperty(pass, p, props[p]);
                      }
                    });
                  } else {
                    for (var i = 0; i < this._props.length; i++) {
                      this._props[i] = {};
                    }
                  }
                }

                this._hash = Material.getHash(this);
              };

              _proto._uploadProperty = function _uploadProperty(pass, name, val) {
                var handle = pass.getHandle(name);

                if (!handle) {
                  return false;
                }

                var propertyType = Pass.getPropertyTypeFromHandle(handle);

                if (propertyType === PropertyType.BUFFER) {
                  if (Array.isArray(val)) {
                    pass.setUniformArray(handle, val);
                  } else if (val !== null) {
                    pass.setUniform(handle, val);
                  } else {
                    pass.resetUniform(name);
                  }
                } else if (propertyType === PropertyType.TEXTURE) {
                  if (Array.isArray(val)) {
                    for (var i = 0; i < val.length; i++) {
                      this._bindTexture(pass, handle, val[i], i);
                    }
                  } else if (val) {
                    this._bindTexture(pass, handle, val);
                  } else {
                    pass.resetTexture(name);
                  }
                }

                return true;
              };

              _proto._bindTexture = function _bindTexture(pass, handle, val, index) {
                var binding = Pass.getBindingFromHandle(handle);

                if (val instanceof Texture) {
                  pass.bindTexture(binding, val, index);
                } else if (val instanceof TextureBase || val instanceof RenderTexture) {
                  var texture = val.getGFXTexture();

                  if (!texture || !texture.width || !texture.height) {
                    return;
                  }

                  pass.bindTexture(binding, texture, index);
                  pass.bindSampler(binding, val.getGFXSampler(), index);
                }
              };

              _proto._doDestroy = function _doDestroy() {
                if (this._passes && this._passes.length) {
                  for (var _iterator3 = _createForOfIteratorHelperLoose(this._passes), _step3; !(_step3 = _iterator3()).done;) {
                    var pass = _step3.value;
                    pass.destroy();
                  }
                }

                this._passes.length = 0;
              };

              _proto.initDefault = function initDefault(uuid) {
                _Asset.prototype.initDefault.call(this, uuid);

                this.initialize({
                  effectName: 'unlit',
                  defines: {
                    USE_COLOR: true
                  }
                });
                this.setProperty('mainColor', new Color('#ff00ff'));
              };

              _proto.validate = function validate() {
                return !!this._effectAsset && !this._effectAsset.isDefault && this.passes.length > 0;
              };

              _createClass(Material, [{
                key: "effectAsset",
                get: function get() {
                  return this._effectAsset;
                }
              }, {
                key: "effectName",
                get: function get() {
                  return this._effectAsset ? this._effectAsset.name : '';
                }
              }, {
                key: "technique",
                get: function get() {
                  return this._techIdx;
                }
              }, {
                key: "passes",
                get: function get() {
                  return this._passes;
                }
              }, {
                key: "hash",
                get: function get() {
                  return this._hash;
                }
              }, {
                key: "parent",
                get: function get() {
                  return null;
                }
              }, {
                key: "owner",
                get: function get() {
                  return null;
                }
              }]);

              return Material;
            }(Asset), _temp$i), (_descriptor$g = _applyDecoratedDescriptor(_class2$i.prototype, "_effectAsset", [_dec2$a], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor2$b = _applyDecoratedDescriptor(_class2$i.prototype, "_techIdx", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor3$9 = _applyDecoratedDescriptor(_class2$i.prototype, "_defines", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor4$7 = _applyDecoratedDescriptor(_class2$i.prototype, "_states", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor5$4 = _applyDecoratedDescriptor(_class2$i.prototype, "_props", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            })), _class2$i)) || _class$j));
            legacyCC.Material = Material;

            var ShadowType = Enum({
              Planar: 0,
              ShadowMap: 1
            });
            var PCFType = Enum({
              HARD: 0,
              SOFT: 1,
              SOFT_2X: 2
            });
            var SHADOW_TYPE_NONE = ShadowType.ShadowMap + 1;
            var Shadows = function () {
              function Shadows() {
                this.sphere = new Sphere(0.0, 0.0, 0.0, 0.01);
                this.maxReceived = 4;
                this._normal = new Vec3(0, 1, 0);
                this._shadowColor = new Color(0, 0, 0, 76);
                this._matLight = new Mat4();
                this._material = null;
                this._instancingMaterial = null;
                this._size = new Vec2(512, 512);
                this._handle = NULL_HANDLE;
                this._handle = ShadowsPool.alloc();
              }

              var _proto = Shadows.prototype;

              _proto.getPlanarShader = function getPlanarShader(patches) {
                if (!this._material) {
                  this._material = new Material();

                  this._material.initialize({
                    effectName: 'planar-shadow'
                  });

                  ShadowsPool.set(this._handle, ShadowsView.PLANAR_PASS, this._material.passes[0].handle);
                }

                return this._material.passes[0].getShaderVariant(patches);
              };

              _proto.getPlanarInstanceShader = function getPlanarInstanceShader(patches) {
                if (!this._instancingMaterial) {
                  this._instancingMaterial = new Material();

                  this._instancingMaterial.initialize({
                    effectName: 'planar-shadow',
                    defines: {
                      USE_INSTANCING: true
                    }
                  });

                  ShadowsPool.set(this._handle, ShadowsView.INSTANCE_PASS, this._instancingMaterial.passes[0].handle);
                }

                return this._instancingMaterial.passes[0].getShaderVariant(patches);
              };

              _proto.initialize = function initialize(shadowsInfo) {
                ShadowsPool.set(this._handle, ShadowsView.TYPE, shadowsInfo.enabled ? shadowsInfo.type : SHADOW_TYPE_NONE);
                ShadowsPool.set(this._handle, ShadowsView.NEAR, shadowsInfo.near);
                ShadowsPool.set(this._handle, ShadowsView.FAR, shadowsInfo.far);
                ShadowsPool.set(this._handle, ShadowsView.ASPECT, shadowsInfo.aspect);
                ShadowsPool.set(this._handle, ShadowsView.ORTHO_SIZE, shadowsInfo.orthoSize);
                this._size = shadowsInfo.shadowMapSize;
                ShadowsPool.setVec2(this._handle, ShadowsView.SIZE, this._size);
                ShadowsPool.set(this._handle, ShadowsView.PCF_TYPE, shadowsInfo.pcf);
                Vec3.copy(this._normal, shadowsInfo.normal);
                ShadowsPool.setVec3(this._handle, ShadowsView.NORMAL, this._normal);
                ShadowsPool.set(this._handle, ShadowsView.DISTANCE, shadowsInfo.distance);

                this._shadowColor.set(shadowsInfo.shadowColor);

                ShadowsPool.setVec4(this._handle, ShadowsView.COLOR, this._shadowColor);
                ShadowsPool.set(this._handle, ShadowsView.BIAS, shadowsInfo.bias);
                ShadowsPool.set(this._handle, ShadowsView.PACKING, shadowsInfo.packing ? 1 : 0);
                ShadowsPool.set(this._handle, ShadowsView.LINEAR, shadowsInfo.linear ? 1 : 0);
                ShadowsPool.set(this._handle, ShadowsView.SELF_SHADOW, shadowsInfo.selfShadow ? 1 : 0);
                ShadowsPool.set(this._handle, ShadowsView.NORMAL_BIAS, shadowsInfo.normalBias);
                ShadowsPool.set(this._handle, ShadowsView.ENABLE, shadowsInfo.enabled ? 1 : 0);
                this.maxReceived = shadowsInfo.maxReceived;
                ShadowsPool.set(this._handle, ShadowsView.AUTO_ADAPT, shadowsInfo.autoAdapt ? 1 : 0);
              };

              _proto.activate = function activate() {
                if (this.enabled) {
                  if (this.type === ShadowType.ShadowMap) {
                    this._updatePipeline();
                  } else {
                    this._updatePlanarInfo();
                  }
                } else {
                  var root = legacyCC.director.root;
                  var pipeline = root.pipeline;
                  pipeline.macros.CC_RECEIVE_SHADOW = 0;
                  root.onGlobalPipelineStateChanged();
                }
              };

              _proto._updatePlanarInfo = function _updatePlanarInfo() {
                if (!this._material) {
                  this._material = new Material();

                  this._material.initialize({
                    effectName: 'planar-shadow'
                  });

                  ShadowsPool.set(this._handle, ShadowsView.PLANAR_PASS, this._material.passes[0].handle);
                }

                if (!this._instancingMaterial) {
                  this._instancingMaterial = new Material();

                  this._instancingMaterial.initialize({
                    effectName: 'planar-shadow',
                    defines: {
                      USE_INSTANCING: true
                    }
                  });

                  ShadowsPool.set(this._handle, ShadowsView.INSTANCE_PASS, this._instancingMaterial.passes[0].handle);
                }

                var root = legacyCC.director.root;
                var pipeline = root.pipeline;
                pipeline.macros.CC_RECEIVE_SHADOW = 0;
                root.onGlobalPipelineStateChanged();
              };

              _proto._updatePipeline = function _updatePipeline() {
                var root = legacyCC.director.root;
                var pipeline = root.pipeline;
                pipeline.macros.CC_RECEIVE_SHADOW = 1;
                root.onGlobalPipelineStateChanged();
              };

              _proto.destroy = function destroy() {
                if (this._material) {
                  this._material.destroy();
                }

                if (this._instancingMaterial) {
                  this._instancingMaterial.destroy();
                }

                if (this._handle) {
                  ShadowsPool.free(this._handle);
                  this._handle = NULL_HANDLE;
                }

                this.sphere.destroy();
              };

              _createClass(Shadows, [{
                key: "enabled",
                get: function get() {
                  if (ShadowsPool.get(this._handle, ShadowsView.ENABLE)) {
                    return true;
                  }

                  return false;
                },
                set: function set(val) {
                  ShadowsPool.set(this._handle, ShadowsView.ENABLE, val ? 1 : 0);
                  if (!val) ShadowsPool.set(this._handle, ShadowsView.TYPE, SHADOW_TYPE_NONE);
                  this.activate();
                }
              }, {
                key: "normal",
                get: function get() {
                  return this._normal;
                },
                set: function set(val) {
                  Vec3.copy(this._normal, val);
                  ShadowsPool.setVec3(this._handle, ShadowsView.NORMAL, this._normal);
                }
              }, {
                key: "distance",
                get: function get() {
                  return ShadowsPool.get(this._handle, ShadowsView.DISTANCE);
                },
                set: function set(val) {
                  ShadowsPool.set(this._handle, ShadowsView.DISTANCE, val);
                }
              }, {
                key: "shadowColor",
                get: function get() {
                  return this._shadowColor;
                },
                set: function set(color) {
                  this._shadowColor = color;
                  ShadowsPool.setVec4(this._handle, ShadowsView.COLOR, color);
                }
              }, {
                key: "type",
                get: function get() {
                  return ShadowsPool.get(this._handle, ShadowsView.TYPE);
                },
                set: function set(val) {
                  ShadowsPool.set(this._handle, ShadowsView.TYPE, this.enabled ? val : SHADOW_TYPE_NONE);
                  this.activate();
                }
              }, {
                key: "near",
                get: function get() {
                  return ShadowsPool.get(this._handle, ShadowsView.NEAR);
                },
                set: function set(val) {
                  ShadowsPool.set(this._handle, ShadowsView.NEAR, val);
                }
              }, {
                key: "far",
                get: function get() {
                  return ShadowsPool.get(this._handle, ShadowsView.FAR);
                },
                set: function set(val) {
                  ShadowsPool.set(this._handle, ShadowsView.FAR, val);
                }
              }, {
                key: "aspect",
                get: function get() {
                  return ShadowsPool.get(this._handle, ShadowsView.ASPECT);
                },
                set: function set(val) {
                  ShadowsPool.set(this._handle, ShadowsView.ASPECT, val);
                }
              }, {
                key: "orthoSize",
                get: function get() {
                  return ShadowsPool.get(this._handle, ShadowsView.ORTHO_SIZE);
                },
                set: function set(val) {
                  ShadowsPool.set(this._handle, ShadowsView.ORTHO_SIZE, val);
                }
              }, {
                key: "size",
                get: function get() {
                  return this._size;
                },
                set: function set(val) {
                  this._size = val;
                  ShadowsPool.setVec2(this._handle, ShadowsView.SIZE, this._size);
                }
              }, {
                key: "pcf",
                get: function get() {
                  return ShadowsPool.get(this._handle, ShadowsView.PCF_TYPE);
                },
                set: function set(val) {
                  ShadowsPool.set(this._handle, ShadowsView.PCF_TYPE, val);
                }
              }, {
                key: "shadowMapDirty",
                get: function get() {
                  if (ShadowsPool.get(this._handle, ShadowsView.SHADOW_MAP_DIRTY)) {
                    return true;
                  }

                  return false;
                },
                set: function set(val) {
                  ShadowsPool.set(this._handle, ShadowsView.SHADOW_MAP_DIRTY, val ? 1 : 0);
                }
              }, {
                key: "bias",
                get: function get() {
                  return ShadowsPool.get(this._handle, ShadowsView.BIAS);
                },
                set: function set(val) {
                  ShadowsPool.set(this._handle, ShadowsView.BIAS, val);
                }
              }, {
                key: "packing",
                get: function get() {
                  if (ShadowsPool.get(this._handle, ShadowsView.PACKING)) {
                    return true;
                  }

                  return false;
                },
                set: function set(val) {
                  ShadowsPool.set(this._handle, ShadowsView.PACKING, val ? 1 : 0);
                }
              }, {
                key: "linear",
                get: function get() {
                  if (ShadowsPool.get(this._handle, ShadowsView.LINEAR)) {
                    return true;
                  }

                  return false;
                },
                set: function set(val) {
                  ShadowsPool.set(this._handle, ShadowsView.LINEAR, val ? 1 : 0);
                }
              }, {
                key: "selfShadow",
                get: function get() {
                  if (ShadowsPool.get(this._handle, ShadowsView.SELF_SHADOW)) {
                    return true;
                  }

                  return false;
                },
                set: function set(val) {
                  ShadowsPool.set(this._handle, ShadowsView.SELF_SHADOW, val ? 1 : 0);
                }
              }, {
                key: "normalBias",
                get: function get() {
                  return ShadowsPool.get(this._handle, ShadowsView.NORMAL_BIAS);
                },
                set: function set(val) {
                  ShadowsPool.set(this._handle, ShadowsView.NORMAL_BIAS, val);
                }
              }, {
                key: "autoAdapt",
                get: function get() {
                  if (ShadowsPool.get(this._handle, ShadowsView.AUTO_ADAPT)) {
                    return true;
                  }

                  return false;
                },
                set: function set(val) {
                  ShadowsPool.set(this._handle, ShadowsView.AUTO_ADAPT, val ? 1 : 0);
                }
              }, {
                key: "matLight",
                get: function get() {
                  return this._matLight;
                }
              }, {
                key: "material",
                get: function get() {
                  return this._material;
                }
              }, {
                key: "instancingMaterial",
                get: function get() {
                  return this._instancingMaterial;
                }
              }, {
                key: "handle",
                get: function get() {
                  return this._handle;
                }
              }]);

              return Shadows;
            }();
            Shadows.MAX_FAR = 2000.0;
            Shadows.COEFFICIENT_OF_EXPANSION = 2.0 * Math.sqrt(3.0);
            legacyCC.Shadows = Shadows;

            var _tempVec3 = new Vec3();

            var _dir_negate = new Vec3();

            var _vec3_p = new Vec3();

            var _mat4_trans = new Mat4();

            var _castWorldBounds = new AABB();

            var _castBoundsInited = false;
            var _validLights = [];

            var _sphere = Sphere.create(0, 0, 0, 1);

            var roPool = new Pool$1(function () {
              return {
                model: null,
                depth: 0
              };
            }, 128);
            var shadowPool = new Pool$1(function () {
              return {
                model: null,
                depth: 0
              };
            }, 128);

            function getRenderObject(model, camera) {
              var depth = 0;

              if (model.node) {
                Vec3.subtract(_tempVec3, model.node.worldPosition, camera.position);
                depth = Vec3.dot(_tempVec3, camera.forward);
              }

              var ro = roPool.alloc();
              ro.model = model;
              ro.depth = depth;
              return ro;
            }

            function getCastShadowRenderObject(model, camera) {
              var depth = 0;

              if (model.node) {
                Vec3.subtract(_tempVec3, model.node.worldPosition, camera.position);
                depth = Vec3.dot(_tempVec3, camera.forward);
              }

              var ro = shadowPool.alloc();
              ro.model = model;
              ro.depth = depth;
              return ro;
            }

            function getShadowWorldMatrix(pipeline, rotation, dir, out) {
              var shadows = pipeline.pipelineSceneData.shadows;
              Vec3.negate(_dir_negate, dir);
              var distance = shadows.sphere.radius * Shadows.COEFFICIENT_OF_EXPANSION;
              Vec3.multiplyScalar(_vec3_p, _dir_negate, distance);
              Vec3.add(_vec3_p, _vec3_p, shadows.sphere.center);
              out.set(_vec3_p);
              Mat4.fromRT(_mat4_trans, rotation, _vec3_p);
              return _mat4_trans;
            }

            function updateDirLight(pipeline, light) {
              var shadows = pipeline.pipelineSceneData.shadows;
              var dir = light.direction;
              var n = shadows.normal;
              var d = shadows.distance + 0.001;
              var NdL = Vec3.dot(n, dir);
              var scale = 1 / NdL;
              var lx = dir.x * scale;
              var ly = dir.y * scale;
              var lz = dir.z * scale;
              var nx = n.x;
              var ny = n.y;
              var nz = n.z;
              var m = shadows.matLight;
              m.m00 = 1 - nx * lx;
              m.m01 = -nx * ly;
              m.m02 = -nx * lz;
              m.m03 = 0;
              m.m04 = -ny * lx;
              m.m05 = 1 - ny * ly;
              m.m06 = -ny * lz;
              m.m07 = 0;
              m.m08 = -nz * lx;
              m.m09 = -nz * ly;
              m.m10 = 1 - nz * lz;
              m.m11 = 0;
              m.m12 = lx * d;
              m.m13 = ly * d;
              m.m14 = lz * d;
              m.m15 = 1;
              pipeline.pipelineUBO.updateShadowUBORange(UBOShadow.MAT_LIGHT_PLANE_PROJ_OFFSET, shadows.matLight);
            }

            function updatePlanarPROJ(shadowInfo, light, shadowUBO) {
              var dir = light.direction;
              var n = shadowInfo.normal;
              var d = shadowInfo.distance + 0.001;
              var NdL = Vec3.dot(n, dir);
              var scale = 1 / NdL;
              var lx = dir.x * scale;
              var ly = dir.y * scale;
              var lz = dir.z * scale;
              var nx = n.x;
              var ny = n.y;
              var nz = n.z;
              var m = shadowInfo.matLight;
              m.m00 = 1 - nx * lx;
              m.m01 = -nx * ly;
              m.m02 = -nx * lz;
              m.m03 = 0;
              m.m04 = -ny * lx;
              m.m05 = 1 - ny * ly;
              m.m06 = -ny * lz;
              m.m07 = 0;
              m.m08 = -nz * lx;
              m.m09 = -nz * ly;
              m.m10 = 1 - nz * lz;
              m.m11 = 0;
              m.m12 = lx * d;
              m.m13 = ly * d;
              m.m14 = lz * d;
              m.m15 = 1;
              Mat4.toArray(shadowUBO, m, UBOShadow.MAT_LIGHT_PLANE_PROJ_OFFSET);
            }
            function lightCollecting(camera, lightNumber) {
              _validLights.length = 0;
              var scene = camera.scene;

              _validLights.push(scene.mainLight);

              var spotLights = scene.spotLights;

              for (var i = 0; i < spotLights.length; i++) {
                var light = spotLights[i];
                Sphere.set(_sphere, light.position.x, light.position.y, light.position.z, light.range);

                if (intersect.sphereFrustum(_sphere, camera.frustum) && lightNumber > _validLights.length) {
                  _validLights.push(light);
                }
              }

              return _validLights;
            }
            function sceneCulling(pipeline, camera) {
              var scene = camera.scene;
              var mainLight = scene.mainLight;
              var sceneData = pipeline.pipelineSceneData;
              var shadows = sceneData.shadows;
              var skybox = sceneData.skybox;
              var renderObjects = sceneData.renderObjects;
              roPool.freeArray(renderObjects);
              renderObjects.length = 0;
              var shadowObjects = null;
              _castBoundsInited = false;

              if (shadows.enabled) {
                pipeline.pipelineUBO.updateShadowUBORange(UBOShadow.SHADOW_COLOR_OFFSET, shadows.shadowColor);

                if (shadows.type === ShadowType.ShadowMap) {
                  shadowObjects = pipeline.pipelineSceneData.shadowObjects;
                  shadowPool.freeArray(shadowObjects);
                  shadowObjects.length = 0;
                }
              }

              if (mainLight) {
                if (shadows.type === ShadowType.Planar) {
                  updateDirLight(pipeline, mainLight);
                }
              }

              if (skybox.enabled && skybox.model && camera.clearFlag & SKYBOX_FLAG) {
                renderObjects.push(getRenderObject(skybox.model, camera));
              }

              var models = scene.models;
              var visibility = camera.visibility;

              for (var i = 0; i < models.length; i++) {
                var model = models[i];

                if (model.enabled) {
                  if (model.node && (visibility & model.node.layer) === model.node.layer || visibility & model.visFlags) {
                    if (shadowObjects != null && model.castShadow && model.worldBounds) {
                      if (!_castBoundsInited) {
                        _castWorldBounds.copy(model.worldBounds);

                        _castBoundsInited = true;
                      }

                      AABB.merge(_castWorldBounds, _castWorldBounds, model.worldBounds);
                      shadowObjects.push(getCastShadowRenderObject(model, camera));
                    }

                    if (model.worldBounds && !intersect.aabbFrustum(model.worldBounds, camera.frustum)) {
                      continue;
                    }

                    renderObjects.push(getRenderObject(model, camera));
                  }
                }
              }

              if (_castWorldBounds) {
                AABB.toBoundingSphere(shadows.sphere, _castWorldBounds);
              }
            }

            var matShadowView = new Mat4();
            var matShadowViewProj = new Mat4();
            var vec3_center = new Vec3();
            var vec4ShadowInfo = new Vec4();
            var PipelineUBO = function () {
              function PipelineUBO() {
                this._globalUBO = new Float32Array(UBOGlobal.COUNT);
                this._cameraUBO = new Float32Array(UBOCamera.COUNT);
                this._shadowUBO = new Float32Array(UBOShadow.COUNT);
              }

              PipelineUBO.updateGlobalUBOView = function updateGlobalUBOView(pipeline, bufferView) {
                var device = pipeline.device;
                var root = legacyCC.director.root;
                var fv = bufferView;
                var shadingWidth = Math.floor(device.width);
                var shadingHeight = Math.floor(device.height);
                fv[UBOGlobal.TIME_OFFSET] = root.cumulativeTime;
                fv[UBOGlobal.TIME_OFFSET + 1] = root.frameTime;
                fv[UBOGlobal.TIME_OFFSET + 2] = legacyCC.director.getTotalFrames();
                fv[UBOGlobal.SCREEN_SIZE_OFFSET] = device.width;
                fv[UBOGlobal.SCREEN_SIZE_OFFSET + 1] = device.height;
                fv[UBOGlobal.SCREEN_SIZE_OFFSET + 2] = 1.0 / device.width;
                fv[UBOGlobal.SCREEN_SIZE_OFFSET + 3] = 1.0 / device.height;
                fv[UBOGlobal.NATIVE_SIZE_OFFSET] = shadingWidth;
                fv[UBOGlobal.NATIVE_SIZE_OFFSET + 1] = shadingHeight;
                fv[UBOGlobal.NATIVE_SIZE_OFFSET + 2] = 1.0 / fv[UBOGlobal.NATIVE_SIZE_OFFSET];
                fv[UBOGlobal.NATIVE_SIZE_OFFSET + 3] = 1.0 / fv[UBOGlobal.NATIVE_SIZE_OFFSET + 1];
              };

              PipelineUBO.updateCameraUBOView = function updateCameraUBOView(pipeline, bufferView, camera) {
                var device = pipeline.device;
                var scene = camera.scene ? camera.scene : legacyCC.director.getScene().renderScene;
                var mainLight = scene.mainLight;
                var sceneData = pipeline.pipelineSceneData;
                var ambient = sceneData.ambient;
                var fog = sceneData.fog;
                var shadingWidth = Math.floor(device.width);
                var shadingHeight = Math.floor(device.height);
                var cv = bufferView;
                var exposure = camera.exposure;
                var isHDR = sceneData.isHDR;
                var shadingScale = sceneData.shadingScale;
                var fpScale = sceneData.fpScale;
                cv[UBOCamera.SCREEN_SCALE_OFFSET] = camera.width / shadingWidth * shadingScale;
                cv[UBOCamera.SCREEN_SCALE_OFFSET + 1] = camera.height / shadingHeight * shadingScale;
                cv[UBOCamera.SCREEN_SCALE_OFFSET + 2] = 1.0 / cv[UBOCamera.SCREEN_SCALE_OFFSET];
                cv[UBOCamera.SCREEN_SCALE_OFFSET + 3] = 1.0 / cv[UBOCamera.SCREEN_SCALE_OFFSET + 1];
                cv[UBOCamera.EXPOSURE_OFFSET] = exposure;
                cv[UBOCamera.EXPOSURE_OFFSET + 1] = 1.0 / exposure;
                cv[UBOCamera.EXPOSURE_OFFSET + 2] = isHDR ? 1.0 : 0.0;
                cv[UBOCamera.EXPOSURE_OFFSET + 3] = fpScale / exposure;

                if (mainLight) {
                  Vec3.toArray(cv, mainLight.direction, UBOCamera.MAIN_LIT_DIR_OFFSET);
                  Vec3.toArray(cv, mainLight.color, UBOCamera.MAIN_LIT_COLOR_OFFSET);

                  if (mainLight.useColorTemperature) {
                    var colorTempRGB = mainLight.colorTemperatureRGB;
                    cv[UBOCamera.MAIN_LIT_COLOR_OFFSET] *= colorTempRGB.x;
                    cv[UBOCamera.MAIN_LIT_COLOR_OFFSET + 1] *= colorTempRGB.y;
                    cv[UBOCamera.MAIN_LIT_COLOR_OFFSET + 2] *= colorTempRGB.z;
                  }

                  if (isHDR) {
                    cv[UBOCamera.MAIN_LIT_COLOR_OFFSET + 3] = mainLight.illuminance * fpScale;
                  } else {
                    cv[UBOCamera.MAIN_LIT_COLOR_OFFSET + 3] = mainLight.illuminance * exposure;
                  }
                } else {
                  Vec3.toArray(cv, Vec3.UNIT_Z, UBOCamera.MAIN_LIT_DIR_OFFSET);
                  Vec4.toArray(cv, Vec4.ZERO, UBOCamera.MAIN_LIT_COLOR_OFFSET);
                }

                var skyColor = ambient.colorArray;

                if (isHDR) {
                  skyColor[3] = ambient.skyIllum * fpScale;
                } else {
                  skyColor[3] = ambient.skyIllum * exposure;
                }

                cv.set(skyColor, UBOCamera.AMBIENT_SKY_OFFSET);
                cv.set(ambient.albedoArray, UBOCamera.AMBIENT_GROUND_OFFSET);
                Mat4.toArray(cv, camera.matView, UBOCamera.MAT_VIEW_OFFSET);
                Mat4.toArray(cv, camera.node.worldMatrix, UBOCamera.MAT_VIEW_INV_OFFSET);
                Vec3.toArray(cv, camera.position, UBOCamera.CAMERA_POS_OFFSET);
                Mat4.toArray(cv, camera.matProj, UBOCamera.MAT_PROJ_OFFSET);
                Mat4.toArray(cv, camera.matProjInv, UBOCamera.MAT_PROJ_INV_OFFSET);
                Mat4.toArray(cv, camera.matViewProj, UBOCamera.MAT_VIEW_PROJ_OFFSET);
                Mat4.toArray(cv, camera.matViewProjInv, UBOCamera.MAT_VIEW_PROJ_INV_OFFSET);
                cv[UBOCamera.CAMERA_POS_OFFSET + 3] = this.getCombineSignY();
                cv.set(fog.colorArray, UBOCamera.GLOBAL_FOG_COLOR_OFFSET);
                cv[UBOCamera.GLOBAL_FOG_BASE_OFFSET] = fog.fogStart;
                cv[UBOCamera.GLOBAL_FOG_BASE_OFFSET + 1] = fog.fogEnd;
                cv[UBOCamera.GLOBAL_FOG_BASE_OFFSET + 2] = fog.fogDensity;
                cv[UBOCamera.GLOBAL_FOG_ADD_OFFSET] = fog.fogTop;
                cv[UBOCamera.GLOBAL_FOG_ADD_OFFSET + 1] = fog.fogRange;
                cv[UBOCamera.GLOBAL_FOG_ADD_OFFSET + 2] = fog.fogAtten;
              };

              PipelineUBO.updateShadowUBOView = function updateShadowUBOView(pipeline, bufferView, camera) {
                var device = pipeline.device;
                var mainLight = camera.scene.mainLight;
                var sceneData = pipeline.pipelineSceneData;
                var shadowInfo = sceneData.shadows;
                var sv = bufferView;

                if (shadowInfo.enabled) {
                  if (mainLight && shadowInfo.type === ShadowType.ShadowMap) {
                    var shadowCameraView;
                    var x = 0;
                    var y = 0;
                    var far = 0;

                    if (shadowInfo.autoAdapt) {
                      shadowCameraView = getShadowWorldMatrix(pipeline, mainLight.node.getWorldRotation(), mainLight.direction, vec3_center);
                      var radius = shadowInfo.sphere.radius;
                      x = radius * shadowInfo.aspect;
                      y = radius;
                      var halfFar = Vec3.distance(shadowInfo.sphere.center, vec3_center);
                      far = Math.min(halfFar * Shadows.COEFFICIENT_OF_EXPANSION, Shadows.MAX_FAR);
                    } else {
                      shadowCameraView = mainLight.node.getWorldMatrix();
                      x = shadowInfo.orthoSize * shadowInfo.aspect;
                      y = shadowInfo.orthoSize;
                      far = shadowInfo.far;
                    }

                    Mat4.toArray(sv, shadowCameraView, UBOShadow.MAT_LIGHT_VIEW_OFFSET);
                    Mat4.invert(matShadowView, shadowCameraView);
                    Mat4.ortho(matShadowViewProj, -x, x, -y, y, shadowInfo.near, far, device.capabilities.clipSpaceMinZ, device.capabilities.clipSpaceSignY);
                    Mat4.multiply(matShadowViewProj, matShadowViewProj, matShadowView);
                    Mat4.toArray(sv, matShadowViewProj, UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET);
                    var isSupportHalfFloat = supportsHalfFloatTexture(device);
                    var linear = shadowInfo.linear && isSupportHalfFloat ? 1.0 : 0.0;
                    sv[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SELF_INFO_OFFSET + 0] = shadowInfo.near;
                    sv[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SELF_INFO_OFFSET + 1] = far;
                    sv[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SELF_INFO_OFFSET + 2] = linear;
                    sv[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SELF_INFO_OFFSET + 3] = shadowInfo.selfShadow ? 1.0 : 0.0;
                    sv[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 0] = shadowInfo.size.x;
                    sv[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 1] = shadowInfo.size.y;
                    sv[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 2] = shadowInfo.pcf;
                    sv[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 3] = shadowInfo.bias;
                    var packing = shadowInfo.packing ? 1.0 : isSupportHalfFloat ? 0.0 : 1.0;
                    sv[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 0] = 0.0;
                    sv[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 1] = packing;
                    sv[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 2] = shadowInfo.normalBias;
                    sv[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 3] = 0.0;
                  } else if (mainLight && shadowInfo.type === ShadowType.Planar) {
                    updatePlanarPROJ(shadowInfo, mainLight, sv);
                  }

                  Color.toArray(sv, shadowInfo.shadowColor, UBOShadow.SHADOW_COLOR_OFFSET);
                }
              };

              PipelineUBO.updateShadowUBOLightView = function updateShadowUBOLightView(pipeline, bufferView, light) {
                var device = pipeline.device;
                var shadowInfo = pipeline.pipelineSceneData.shadows;
                var sv = bufferView;
                var isSupportHalfFloat = supportsHalfFloatTexture(device);
                var linear = shadowInfo.linear && isSupportHalfFloat ? 1.0 : 0.0;
                var packing = shadowInfo.packing ? 1.0 : isSupportHalfFloat ? 0.0 : 1.0;
                var _x = 0;
                var _y = 0;
                var _far = 0;
                var shadowCameraView;

                switch (light.type) {
                  case LightType.DIRECTIONAL:
                    light.update();

                    if (shadowInfo.autoAdapt) {
                      var node = light.node;

                      if (node) {
                        shadowCameraView = getShadowWorldMatrix(pipeline, node.getWorldRotation(), light.direction, vec3_center);
                      }

                      var radius = shadowInfo.sphere.radius;
                      _x = radius * shadowInfo.aspect;
                      _y = radius;
                      var halfFar = Vec3.distance(shadowInfo.sphere.center, vec3_center);
                      _far = Math.min(halfFar * Shadows.COEFFICIENT_OF_EXPANSION, Shadows.MAX_FAR);
                    } else {
                      shadowCameraView = light.node.getWorldMatrix();
                      _x = shadowInfo.orthoSize * shadowInfo.aspect;
                      _y = shadowInfo.orthoSize;
                      _far = shadowInfo.far;
                    }

                    Mat4.toArray(sv, shadowCameraView, UBOShadow.MAT_LIGHT_VIEW_OFFSET);
                    Mat4.invert(matShadowView, shadowCameraView);
                    vec4ShadowInfo.set(shadowInfo.near, _far, linear, shadowInfo.selfShadow ? 1.0 : 0.0);
                    Vec4.toArray(sv, vec4ShadowInfo, UBOShadow.SHADOW_NEAR_FAR_LINEAR_SELF_INFO_OFFSET);
                    vec4ShadowInfo.set(0.0, packing, shadowInfo.normalBias, 0.0);
                    Vec4.toArray(sv, vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET);
                    Mat4.ortho(matShadowViewProj, -_x, _x, -_y, _y, shadowInfo.near, _far, device.capabilities.clipSpaceMinZ, device.capabilities.clipSpaceSignY);
                    break;

                  case LightType.SPOT:
                    Mat4.toArray(sv, light.node.getWorldMatrix(), UBOShadow.MAT_LIGHT_VIEW_OFFSET);
                    Mat4.invert(matShadowView, light.node.getWorldMatrix());
                    vec4ShadowInfo.set(0.01, light.range, linear, shadowInfo.selfShadow ? 1.0 : 0.0);
                    Vec4.toArray(sv, vec4ShadowInfo, UBOShadow.SHADOW_NEAR_FAR_LINEAR_SELF_INFO_OFFSET);
                    vec4ShadowInfo.set(1.0, packing, shadowInfo.normalBias, 0.0);
                    Vec4.toArray(sv, vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET);
                    Mat4.perspective(matShadowViewProj, light.spotAngle, light.aspect, 0.001, light.range);
                    break;
                }

                Mat4.multiply(matShadowViewProj, matShadowViewProj, matShadowView);
                Mat4.toArray(sv, matShadowViewProj, UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET);
                vec4ShadowInfo.set(shadowInfo.size.x, shadowInfo.size.y, shadowInfo.pcf, shadowInfo.bias);
                Vec4.toArray(sv, vec4ShadowInfo, UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET);
                Color.toArray(sv, shadowInfo.shadowColor, UBOShadow.SHADOW_COLOR_OFFSET);
              };

              PipelineUBO.getCombineSignY = function getCombineSignY() {
                return PipelineUBO._combineSignY;
              };

              var _proto = PipelineUBO.prototype;

              _proto._initCombineSignY = function _initCombineSignY() {
                var device = this._device;
                PipelineUBO._combineSignY = device.capabilities.screenSpaceSignY * 0.5 + 0.5 << 1 | device.capabilities.clipSpaceSignY * 0.5 + 0.5;
              };

              _proto.activate = function activate(device, pipeline) {
                this._device = device;
                this._pipeline = pipeline;
                var ds = this._pipeline.descriptorSet;

                this._initCombineSignY();

                var globalUBO = device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, UBOGlobal.SIZE, UBOGlobal.SIZE));
                ds.bindBuffer(UBOGlobal.BINDING, globalUBO);
                var cameraUBO = device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, UBOCamera.SIZE, UBOCamera.SIZE));
                ds.bindBuffer(UBOCamera.BINDING, cameraUBO);
                var shadowUBO = device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, UBOShadow.SIZE, UBOShadow.SIZE));
                ds.bindBuffer(UBOShadow.BINDING, shadowUBO);
              };

              _proto.updateGlobalUBO = function updateGlobalUBO() {
                var globalDSManager = this._pipeline.globalDSManager;
                var ds = this._pipeline.descriptorSet;
                var cmdBuffer = this._pipeline.commandBuffers;
                ds.update();
                PipelineUBO.updateGlobalUBOView(this._pipeline, this._globalUBO);
                cmdBuffer[0].updateBuffer(ds.getBuffer(UBOGlobal.BINDING), this._globalUBO);
                globalDSManager.bindBuffer(UBOGlobal.BINDING, ds.getBuffer(UBOGlobal.BINDING));
                globalDSManager.update();
              };

              _proto.updateCameraUBO = function updateCameraUBO(camera) {
                var globalDSManager = this._pipeline.globalDSManager;
                var ds = this._pipeline.descriptorSet;
                var cmdBuffer = this._pipeline.commandBuffers;
                PipelineUBO.updateCameraUBOView(this._pipeline, this._cameraUBO, camera);
                cmdBuffer[0].updateBuffer(ds.getBuffer(UBOCamera.BINDING), this._cameraUBO);
                globalDSManager.bindBuffer(UBOCamera.BINDING, ds.getBuffer(UBOCamera.BINDING));
                globalDSManager.update();
              };

              _proto.updateShadowUBO = function updateShadowUBO(camera) {
                var sceneData = this._pipeline.pipelineSceneData;
                var shadowInfo = sceneData.shadows;
                if (!shadowInfo.enabled) return;
                var ds = this._pipeline.descriptorSet;
                var cmdBuffer = this._pipeline.commandBuffers;
                var shadowFrameBufferMap = sceneData.shadowFrameBufferMap;
                var mainLight = camera.scene.mainLight;
                ds.update();

                if (mainLight && shadowFrameBufferMap.has(mainLight)) {
                  ds.bindTexture(UNIFORM_SHADOWMAP_BINDING, shadowFrameBufferMap.get(mainLight).colorTextures[0]);
                }

                PipelineUBO.updateShadowUBOView(this._pipeline, this._shadowUBO, camera);
                cmdBuffer[0].updateBuffer(ds.getBuffer(UBOShadow.BINDING), this._shadowUBO);
              };

              _proto.updateShadowUBOLight = function updateShadowUBOLight(light) {
                var ds = this._pipeline.descriptorSet;
                PipelineUBO.updateShadowUBOLightView(this._pipeline, this._shadowUBO, light);
                ds.getBuffer(UBOShadow.BINDING).update(this._shadowUBO);
              };

              _proto.updateShadowUBORange = function updateShadowUBORange(offset, data) {
                if (data instanceof Mat4) {
                  Mat4.toArray(this._shadowUBO, data, offset);
                } else if (data instanceof Color) {
                  Color.toArray(this._shadowUBO, data, offset);
                }
              };

              _proto.destroy = function destroy() {};

              return PipelineUBO;
            }();
            PipelineUBO._combineSignY = 0;

            var FogType = Enum({
              LINEAR: 0,
              EXP: 1,
              EXP_SQUARED: 2,
              LAYERED: 3
            });
            var FOG_TYPE_NONE = FogType.LAYERED + 1;
            var Fog = function () {
              function Fog() {
                this._fogColor = new Color('#C8C8C8');
                this._colorArray = new Float32Array([0.2, 0.2, 0.2, 1.0]);
                this._handle = NULL_HANDLE;
                this._handle = FogPool.alloc();
              }

              var _proto = Fog.prototype;

              _proto.initialize = function initialize(fogInfo) {
                FogPool.set(this._handle, FogView.ENABLE, fogInfo.enabled ? 1 : 0);
                FogPool.set(this._handle, FogView.TYPE, fogInfo.enabled ? fogInfo.type : FOG_TYPE_NONE);

                this._fogColor.set(fogInfo.fogColor);

                Color.toArray(this._colorArray, this._fogColor);
                FogPool.setVec4(this._handle, FogView.COLOR, this._fogColor);
                FogPool.set(this._handle, FogView.DENSITY, fogInfo.fogDensity);
                FogPool.set(this._handle, FogView.START, fogInfo.fogStart);
                FogPool.set(this._handle, FogView.END, fogInfo.fogEnd);
                FogPool.set(this._handle, FogView.ATTEN, fogInfo.fogAtten);
                FogPool.set(this._handle, FogView.TOP, fogInfo.fogTop);
                FogPool.set(this._handle, FogView.RANGE, fogInfo.fogRange);
              };

              _proto.activate = function activate() {
                this._updatePipeline();
              };

              _proto._updatePipeline = function _updatePipeline() {
                var root = legacyCC.director.root;
                var value = this.enabled ? this.type : FOG_TYPE_NONE;
                var pipeline = root.pipeline;

                if (pipeline.macros.CC_USE_FOG === value) {
                  return;
                }

                pipeline.macros.CC_USE_FOG = value;
                root.onGlobalPipelineStateChanged();
              };

              _proto.destroy = function destroy() {
                if (this._handle) {
                  FogPool.free(this._handle);
                  this._handle = NULL_HANDLE;
                }
              };

              _createClass(Fog, [{
                key: "enabled",
                get: function get() {
                  return FogPool.get(this._handle, FogView.ENABLE);
                },
                set: function set(val) {
                  FogPool.set(this._handle, FogView.ENABLE, val ? 1 : 0);
                  if (!val) FogPool.set(this._handle, FogView.TYPE, FOG_TYPE_NONE);
                  val ? this.activate() : this._updatePipeline();
                }
              }, {
                key: "fogColor",
                get: function get() {
                  return this._fogColor;
                },
                set: function set(val) {
                  this._fogColor.set(val);

                  Color.toArray(this._colorArray, this._fogColor);
                  FogPool.setVec4(this._handle, FogView.COLOR, this._fogColor);
                }
              }, {
                key: "type",
                get: function get() {
                  return FogPool.get(this._handle, FogView.TYPE);
                },
                set: function set(val) {
                  FogPool.set(this._handle, FogView.TYPE, this.enabled ? val : FOG_TYPE_NONE);
                  if (this.enabled) this._updatePipeline();
                }
              }, {
                key: "fogDensity",
                get: function get() {
                  return FogPool.get(this._handle, FogView.DENSITY);
                },
                set: function set(val) {
                  FogPool.set(this._handle, FogView.DENSITY, val);
                }
              }, {
                key: "fogStart",
                get: function get() {
                  return FogPool.get(this._handle, FogView.START);
                },
                set: function set(val) {
                  FogPool.set(this._handle, FogView.START, val);
                }
              }, {
                key: "fogEnd",
                get: function get() {
                  return FogPool.get(this._handle, FogView.END);
                },
                set: function set(val) {
                  FogPool.set(this._handle, FogView.END, val);
                }
              }, {
                key: "fogAtten",
                get: function get() {
                  return FogPool.get(this._handle, FogView.ATTEN);
                },
                set: function set(val) {
                  FogPool.set(this._handle, FogView.ATTEN, val);
                }
              }, {
                key: "fogTop",
                get: function get() {
                  return FogPool.get(this._handle, FogView.TOP);
                },
                set: function set(val) {
                  FogPool.set(this._handle, FogView.TOP, val);
                }
              }, {
                key: "fogRange",
                get: function get() {
                  return FogPool.get(this._handle, FogView.RANGE);
                },
                set: function set(val) {
                  FogPool.set(this._handle, FogView.RANGE, val);
                }
              }, {
                key: "colorArray",
                get: function get() {
                  return this._colorArray;
                }
              }, {
                key: "handle",
                get: function get() {
                  return this._handle;
                }
              }]);

              return Fog;
            }();
            legacyCC.Fog = Fog;

            var PassInstance = function (_Pass) {
              _inheritsLoose(PassInstance, _Pass);

              function PassInstance(parent, owner) {
                var _this;

                _this = _Pass.call(this, parent.root) || this;
                _this._parent = void 0;
                _this._owner = void 0;
                _this._dontNotify = false;
                _this._parent = parent;
                _this._owner = owner;

                _this._doInit(_this._parent, true);

                for (var i = 0; i < _this._shaderInfo.blocks.length; i++) {
                  var u = _this._shaderInfo.blocks[i];
                  var block = _this._blocks[u.binding];
                  var parentBlock = _this._parent.blocks[u.binding];
                  block.set(parentBlock);
                }

                _this._rootBufferDirty = true;
                var paren = _this._parent;

                for (var _i = 0; _i < _this._shaderInfo.samplerTextures.length; _i++) {
                  var _u = _this._shaderInfo.samplerTextures[_i];

                  for (var j = 0; j < _u.count; j++) {
                    var sampler = paren._descriptorSet.getSampler(_u.binding, j);

                    var texture = paren._descriptorSet.getTexture(_u.binding, j);

                    _this._descriptorSet.bindSampler(_u.binding, sampler, j);

                    _this._descriptorSet.bindTexture(_u.binding, texture, j);
                  }
                }

                _Pass.prototype.tryCompile.call(_assertThisInitialized(_this));

                return _this;
              }

              var _proto = PassInstance.prototype;

              _proto.overridePipelineStates = function overridePipelineStates(original, overrides) {
                this._bs.reset();

                this._rs.reset();

                this._dss.reset();

                Pass.fillPipelineInfo(this, original);
                Pass.fillPipelineInfo(this, overrides);

                this._onStateChange();
              };

              _proto.tryCompile = function tryCompile(defineOverrides) {
                if (defineOverrides) {
                  if (!overrideMacros(this._defines, defineOverrides)) {
                    return false;
                  }
                }

                var res = _Pass.prototype.tryCompile.call(this);

                this._onStateChange();

                return res;
              };

              _proto.beginChangeStatesSilently = function beginChangeStatesSilently() {
                this._dontNotify = true;
              };

              _proto.endChangeStatesSilently = function endChangeStatesSilently() {
                this._dontNotify = false;
              };

              _proto._syncBatchingScheme = function _syncBatchingScheme() {
                this._defines.USE_BATCHING = this._defines.USE_INSTANCING = false;
                this.batchingScheme = 0;
              };

              _proto._onStateChange = function _onStateChange() {
                this.hash = Pass.getPassHash(this, this._hShaderDefault);

                this._owner.onPassStateChange(this._dontNotify);
              };

              _createClass(PassInstance, [{
                key: "parent",
                get: function get() {
                  return this._parent;
                }
              }]);

              return PassInstance;
            }(Pass);

            var MaterialInstance = function (_Material) {
              _inheritsLoose(MaterialInstance, _Material);

              function MaterialInstance(info) {
                var _this;

                _this = _Material.call(this) || this;
                _this._passes = [];
                _this._parent = void 0;
                _this._owner = void 0;
                _this._subModelIdx = 0;
                _this._parent = info.parent;
                _this._owner = info.owner || null;
                _this._subModelIdx = info.subModelIdx || 0;

                _this.copy(_this._parent);

                return _this;
              }

              var _proto = MaterialInstance.prototype;

              _proto.recompileShaders = function recompileShaders(overrides, passIdx) {
                if (!this._passes || !this.effectAsset) {
                  return;
                }

                if (passIdx === undefined) {
                  for (var _iterator = _createForOfIteratorHelperLoose(this._passes), _step; !(_step = _iterator()).done;) {
                    var pass = _step.value;
                    pass.tryCompile(overrides);
                  }
                } else {
                  this._passes[passIdx].tryCompile(overrides);
                }
              };

              _proto.overridePipelineStates = function overridePipelineStates(overrides, passIdx) {
                if (!this._passes || !this.effectAsset) {
                  return;
                }

                var passInfos = this.effectAsset.techniques[this.technique].passes;

                if (passIdx === undefined) {
                  for (var i = 0; i < this._passes.length; i++) {
                    var pass = this._passes[i];
                    var state = this._states[i] || (this._states[i] = {});

                    for (var key in overrides) {
                      state[key] = overrides[key];
                    }

                    pass.overridePipelineStates(passInfos[pass.passIndex], state);
                  }
                } else {
                  var _state = this._states[passIdx] || (this._states[passIdx] = {});

                  for (var _key in overrides) {
                    _state[_key] = overrides[_key];
                  }

                  this._passes[passIdx].overridePipelineStates(passInfos[passIdx], _state);
                }
              };

              _proto.destroy = function destroy() {
                this._doDestroy();

                return true;
              };

              _proto.onPassStateChange = function onPassStateChange(dontNotify) {
                this._hash = Material.getHash(this);

                if (!dontNotify && this._owner) {
                  this._owner._onRebuildPSO(this._subModelIdx, this);
                }
              };

              _proto._createPasses = function _createPasses() {
                var passes = [];
                var parentPasses = this._parent.passes;

                if (!parentPasses) {
                  return passes;
                }

                for (var k = 0; k < parentPasses.length; ++k) {
                  passes.push(new PassInstance(parentPasses[k], this));
                }

                return passes;
              };

              _createClass(MaterialInstance, [{
                key: "parent",
                get: function get() {
                  return this._parent;
                }
              }, {
                key: "owner",
                get: function get() {
                  return this._owner;
                }
              }]);

              return MaterialInstance;
            }(Material);

            var skybox_mesh = null;
            var skybox_material = null;
            var Skybox = function () {
              function Skybox() {
                this._envmap = null;
                this._globalDSManager = null;
                this._model = null;
                this._default = null;
                this._handle = NULL_HANDLE;
                this._handle = SkyboxPool.alloc();
              }

              var _proto = Skybox.prototype;

              _proto.initialize = function initialize(skyboxInfo) {
                SkyboxPool.set(this._handle, SkyboxView.ENABLE, skyboxInfo.enabled ? 1 : 0);
                SkyboxPool.set(this._handle, SkyboxView.USE_IBL, skyboxInfo.useIBL ? 1 : 0);
                SkyboxPool.set(this._handle, SkyboxView.IS_RGBE, skyboxInfo.isRGBE ? 1 : 0);
                this._envmap = skyboxInfo.envmap;
              };

              _proto.activate = function activate() {
                var pipeline = legacyCC.director.root.pipeline;
                var ambient = pipeline.pipelineSceneData.ambient;
                this._globalDSManager = pipeline.globalDSManager;
                this._default = builtinResMgr.get('default-cube-texture');

                if (!this._model) {
                  this._model = legacyCC.director.root.createModel(legacyCC.renderer.scene.Model);

                  this._model._initLocalDescriptors = function () {};
                }

                SkyboxPool.set(this._handle, SkyboxView.MODEL, this._model.handle);

                if (!this._envmap) {
                  this._envmap = this._default;
                }

                ambient.albedoArray[3] = this._envmap.mipmapLevel;

                if (!skybox_material) {
                  var mat = new Material();
                  mat.initialize({
                    effectName: 'skybox',
                    defines: {
                      USE_RGBE_CUBEMAP: this.isRGBE
                    }
                  });
                  skybox_material = new MaterialInstance({
                    parent: mat
                  });
                } else {
                  skybox_material.recompileShaders({
                    USE_RGBE_CUBEMAP: this.isRGBE
                  });
                }

                if (this.enabled) {
                  if (!skybox_mesh) {
                    skybox_mesh = legacyCC.utils.createMesh(legacyCC.primitives.box({
                      width: 2,
                      height: 2,
                      length: 2
                    }));
                  }

                  this._model.initSubModel(0, skybox_mesh.renderingSubMeshes[0], skybox_material);
                }

                this._updateGlobalBinding();

                this._updatePipeline();
              };

              _proto._updatePipeline = function _updatePipeline() {
                var value = this.useIBL ? this.isRGBE ? 2 : 1 : 0;
                var root = legacyCC.director.root;
                var pipeline = root.pipeline;
                var current = pipeline.macros.CC_USE_IBL;

                if (current === value) {
                  return;
                }

                pipeline.macros.CC_USE_IBL = value;
                root.onGlobalPipelineStateChanged();
              };

              _proto._updateGlobalBinding = function _updateGlobalBinding() {
                var texture = this.envmap.getGFXTexture();
                var sampler = samplerLib.getSampler(legacyCC.director._device, this.envmap.getSamplerHash());

                this._globalDSManager.bindSampler(UNIFORM_ENVIRONMENT_BINDING, sampler);

                this._globalDSManager.bindTexture(UNIFORM_ENVIRONMENT_BINDING, texture);

                this._globalDSManager.update();
              };

              _proto.destroy = function destroy() {
                if (this._handle) {
                  SkyboxPool.free(this._handle);
                  this._handle = NULL_HANDLE;
                }
              };

              _createClass(Skybox, [{
                key: "model",
                get: function get() {
                  return this._model;
                }
              }, {
                key: "enabled",
                get: function get() {
                  return SkyboxPool.get(this._handle, SkyboxView.ENABLE);
                },
                set: function set(val) {
                  SkyboxPool.set(this._handle, SkyboxView.ENABLE, val ? 1 : 0);
                  if (val) this.activate();else this._updatePipeline();
                }
              }, {
                key: "useIBL",
                get: function get() {
                  return SkyboxPool.get(this._handle, SkyboxView.USE_IBL);
                },
                set: function set(val) {
                  SkyboxPool.set(this._handle, SkyboxView.USE_IBL, val ? 1 : 0);

                  this._updatePipeline();
                }
              }, {
                key: "isRGBE",
                get: function get() {
                  return SkyboxPool.get(this._handle, SkyboxView.IS_RGBE);
                },
                set: function set(val) {
                  if (val) {
                    if (skybox_material) {
                      skybox_material.recompileShaders({
                        USE_RGBE_CUBEMAP: val
                      });
                    }

                    if (this._model) {
                      this._model.setSubModelMaterial(0, skybox_material);
                    }
                  }

                  SkyboxPool.set(this._handle, SkyboxView.IS_RGBE, val ? 1 : 0);

                  this._updatePipeline();
                }
              }, {
                key: "envmap",
                get: function get() {
                  return this._envmap;
                },
                set: function set(val) {
                  this._envmap = val || this._default;

                  if (this._envmap) {
                    legacyCC.director.root.pipeline.pipelineSceneData.ambient.albedoArray[3] = this._envmap.mipmapLevel;

                    this._updateGlobalBinding();
                  }
                }
              }, {
                key: "handle",
                get: function get() {
                  return this._handle;
                }
              }]);

              return Skybox;
            }();
            legacyCC.Skybox = Skybox;

            var PipelineSceneData = function () {
              function PipelineSceneData() {
                this.fog = new Fog();
                this.ambient = new Ambient();
                this.skybox = new Skybox();
                this.shadows = new Shadows();
                this.renderObjects = [];
                this.shadowObjects = [];
                this.shadowFrameBufferMap = new Map();
                this._handle = PipelineSceneDataPool.alloc();
                PipelineSceneDataPool.set(this._handle, PipelineSceneDataView.AMBIENT, this.ambient.handle);
                PipelineSceneDataPool.set(this._handle, PipelineSceneDataView.SKYBOX, this.skybox.handle);
                PipelineSceneDataPool.set(this._handle, PipelineSceneDataView.FOG, this.fog.handle);
                PipelineSceneDataPool.set(this._handle, PipelineSceneDataView.SHADOW, this.shadows.handle);
                PipelineSceneDataPool.set(this._handle, PipelineSceneDataView.IS_HDR, 0);
                PipelineSceneDataPool.set(this._handle, PipelineSceneDataView.SHADING_SCALE, 1.0);
                PipelineSceneDataPool.set(this._handle, PipelineSceneDataView.FP_SCALE, 1.0 / 1024.0);
              }

              var _proto = PipelineSceneData.prototype;

              _proto.initDeferredPassInfo = function initDeferredPassInfo() {
                var builinDeferred = builtinResMgr.get('builtin-deferred-material');

                if (builinDeferred) {
                  var passLit = builinDeferred.passes[0];
                  passLit.beginChangeStatesSilently();
                  passLit.tryCompile();
                  passLit.endChangeStatesSilently();
                }

                var builtinPostProcess = builtinResMgr.get('builtin-post-process-material');

                if (builtinPostProcess) {
                  var passPost = builtinPostProcess.passes[0];
                  passPost.beginChangeStatesSilently();
                  passPost.tryCompile();
                  passPost.endChangeStatesSilently();
                }

                if (builinDeferred) {
                  var _passLit = builinDeferred.passes[0];
                  PipelineSceneDataPool.set(this._handle, PipelineSceneDataView.DEFERRED_LIGHT_PASS, _passLit.handle);
                  PipelineSceneDataPool.set(this._handle, PipelineSceneDataView.DEFERRED_LIGHT_PASS_SHADER, _passLit.getShaderVariant());
                }

                if (builtinPostProcess) {
                  var _passPost = builtinPostProcess.passes[0];
                  PipelineSceneDataPool.set(this._handle, PipelineSceneDataView.DEFERRED_POST_PASS, _passPost.handle);
                  PipelineSceneDataPool.set(this._handle, PipelineSceneDataView.DEFERRED_POST_PASS_SHADER, _passPost.getShaderVariant());
                }
              };

              _proto.activate = function activate(device, pipeline) {
                this._device = device;
                this._pipeline = pipeline;
                this.initDeferredPassInfo();
                return true;
              };

              _proto.destroy = function destroy() {
                this.ambient.destroy();
                this.skybox.destroy();
                this.fog.destroy();
                this.shadows.destroy();

                if (this._handle) {
                  PipelineSceneDataPool.free(this._handle);
                }
              };

              _createClass(PipelineSceneData, [{
                key: "handle",
                get: function get() {
                  return this._handle;
                }
              }, {
                key: "isHDR",
                get: function get() {
                  return PipelineSceneDataPool.get(this._handle, PipelineSceneDataView.IS_HDR);
                },
                set: function set(val) {
                  PipelineSceneDataPool.set(this._handle, PipelineSceneDataView.IS_HDR, val ? 1 : 0);
                }
              }, {
                key: "shadingScale",
                get: function get() {
                  return PipelineSceneDataPool.get(this._handle, PipelineSceneDataView.SHADING_SCALE);
                },
                set: function set(val) {
                  PipelineSceneDataPool.set(this._handle, PipelineSceneDataView.SHADING_SCALE, val);
                }
              }, {
                key: "fpScale",
                get: function get() {
                  return PipelineSceneDataPool.get(this._handle, PipelineSceneDataView.FP_SCALE);
                },
                set: function set(val) {
                  PipelineSceneDataPool.set(this._handle, PipelineSceneDataView.FP_SCALE, val);
                }
              }, {
                key: "deferredLightPassHandle",
                get: function get() {
                  return PipelineSceneDataPool.get(this._handle, PipelineSceneDataView.DEFERRED_LIGHT_PASS);
                }
              }, {
                key: "deferredLightPassShaderHandle",
                get: function get() {
                  return PipelineSceneDataPool.get(this._handle, PipelineSceneDataView.DEFERRED_LIGHT_PASS_SHADER);
                }
              }, {
                key: "deferredPostPassHandle",
                get: function get() {
                  return PipelineSceneDataPool.get(this._handle, PipelineSceneDataView.DEFERRED_POST_PASS);
                }
              }, {
                key: "deferredPostPassShaderHandle",
                get: function get() {
                  return PipelineSceneDataPool.get(this._handle, PipelineSceneDataView.DEFERRED_POST_PASS_SHADER);
                }
              }]);

              return PipelineSceneData;
            }();

            var _samplerLinearInfo = [Filter.LINEAR, Filter.LINEAR, Filter.NONE, Address.CLAMP, Address.CLAMP, Address.CLAMP];
            var _samplerPointInfo = [Filter.POINT, Filter.POINT, Filter.NONE, Address.CLAMP, Address.CLAMP, Address.CLAMP];
            var GlobalDSManager = function () {
              function GlobalDSManager(pipeline) {
                this._device = void 0;
                this._descriptorSetMap = new Map();
                this._globalDescriptorSet = void 0;
                this._descriptorSetLayout = void 0;
                this._linearSampler = void 0;
                this._pointSampler = void 0;
                this._device = pipeline.device;
                var linearSamplerHash = genSamplerHash(_samplerLinearInfo);
                this._linearSampler = samplerLib.getSampler(this._device, linearSamplerHash);
                var pointSamplerHash = genSamplerHash(_samplerPointInfo);
                this._pointSampler = samplerLib.getSampler(this._device, pointSamplerHash);
                var layoutInfo = new DescriptorSetLayoutInfo(globalDescriptorSetLayout.bindings);
                this._descriptorSetLayout = this._device.createDescriptorSetLayout(layoutInfo);
                this._globalDescriptorSet = this._device.createDescriptorSet(new DescriptorSetInfo(this._descriptorSetLayout));
              }

              var _proto = GlobalDSManager.prototype;

              _proto.bindBuffer = function bindBuffer(binding, buffer) {
                this._globalDescriptorSet.bindBuffer(binding, buffer);

                var it = this._descriptorSetMap.values();

                var res = it.next();

                while (!res.done) {
                  var descriptorSet = res.value;
                  descriptorSet.bindBuffer(binding, buffer);
                  res = it.next();
                }
              };

              _proto.bindSampler = function bindSampler(binding, sampler) {
                this._globalDescriptorSet.bindSampler(binding, sampler);

                var it = this._descriptorSetMap.values();

                var res = it.next();

                while (!res.done) {
                  var descriptorSet = res.value;
                  descriptorSet.bindSampler(binding, sampler);
                  res = it.next();
                }
              };

              _proto.bindTexture = function bindTexture(binding, texture) {
                this._globalDescriptorSet.bindTexture(binding, texture);

                var it = this._descriptorSetMap.values();

                var res = it.next();

                while (!res.done) {
                  var descriptorSet = res.value;
                  descriptorSet.bindTexture(binding, texture);
                  res = it.next();
                }
              };

              _proto.update = function update() {
                this._globalDescriptorSet.update();

                var it = this._descriptorSetMap.values();

                var res = it.next();

                while (!res.done) {
                  var descriptorSet = res.value;
                  descriptorSet.update();
                  res = it.next();
                }
              };

              _proto.getOrCreateDescriptorSet = function getOrCreateDescriptorSet(idx) {
                var device = this._device;

                if (!this._descriptorSetMap.has(idx)) {
                  var globalDescriptorSet = this._globalDescriptorSet;
                  var descriptorSet = device.createDescriptorSet(new DescriptorSetInfo(this._descriptorSetLayout));

                  this._descriptorSetMap.set(idx, descriptorSet);

                  for (var i = PipelineGlobalBindings.UBO_GLOBAL; i < PipelineGlobalBindings.COUNT; i++) {
                    descriptorSet.bindBuffer(i, globalDescriptorSet.getBuffer(i));
                    descriptorSet.bindSampler(i, globalDescriptorSet.getSampler(i));
                    descriptorSet.bindTexture(i, globalDescriptorSet.getTexture(i));
                  }

                  var shadowBUO = device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, UBOShadow.SIZE, UBOShadow.SIZE));
                  descriptorSet.bindBuffer(UBOShadow.BINDING, shadowBUO);
                  descriptorSet.update();
                }

                return this._descriptorSetMap.get(idx);
              };

              _proto.destroy = function destroy() {
                this._descriptorSetLayout.destroy();

                this._linearSampler.destroy();

                this._pointSampler.destroy();
              };

              _createClass(GlobalDSManager, [{
                key: "descriptorSetMap",
                get: function get() {
                  return this._descriptorSetMap;
                }
              }, {
                key: "linearSampler",
                get: function get() {
                  return this._linearSampler;
                }
              }, {
                key: "pointSampler",
                get: function get() {
                  return this._pointSampler;
                }
              }, {
                key: "descriptorSetLayout",
                get: function get() {
                  return this._descriptorSetLayout;
                }
              }, {
                key: "globalDescriptorSet",
                get: function get() {
                  return this._globalDescriptorSet;
                }
              }]);

              return GlobalDSManager;
            }();

            var _dec$k, _dec2$b, _dec3$7, _dec4$5, _class$k, _class2$j, _descriptor$h, _descriptor2$c, _temp$j;
            var RenderPipeline = exports('RenderPipeline', (_dec$k = ccclass('cc.RenderPipeline'), _dec2$b = displayOrder(), _dec3$7 = displayOrder(), _dec4$5 = type([RenderFlow]), _dec$k(_class$k = (_class2$j = (_temp$j = function (_Asset) {
              _inheritsLoose(RenderPipeline, _Asset);

              function RenderPipeline() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "_tag", _descriptor$h, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_flows", _descriptor2$c, _assertThisInitialized(_this));

                _this._commandBuffers = [];
                _this._pipelineUBO = new PipelineUBO();
                _this._pipelineSceneData = new PipelineSceneData();
                _this._macros = {};
                _this._constantMacros = '';
                return _this;
              }

              var _proto = RenderPipeline.prototype;

              _proto.initialize = function initialize(info) {
                this._flows = info.flows;

                if (info.tag) {
                  this._tag = info.tag;
                }

                return true;
              };

              _proto.generateRenderArea = function generateRenderArea(camera) {
                var res = new Rect$1();
                var vp = camera.viewport;
                var sceneData = this.pipelineSceneData;
                var w = camera.window.hasOnScreenAttachments && this.device.surfaceTransform % 2 ? camera.height : camera.width;
                var h = camera.window.hasOnScreenAttachments && this.device.surfaceTransform % 2 ? camera.width : camera.height;
                res.x = vp.x * w;
                res.y = vp.y * h;
                res.width = vp.width * w * sceneData.shadingScale;
                res.height = vp.height * h * sceneData.shadingScale;
                return res;
              };

              _proto.activate = function activate() {
                this._device = legacyCC.director.root.device;
                this._globalDSManager = new GlobalDSManager(this);
                this._descriptorSet = this._globalDSManager.globalDescriptorSet;

                this._pipelineUBO.activate(this._device, this);

                this._pipelineSceneData.activate(this._device, this);

                for (var i = 0; i < this._flows.length; i++) {
                  this._flows[i].activate(this);
                }

                this._macros.CC_USE_HDR = this._pipelineSceneData.isHDR;

                this._generateConstantMacros();

                return true;
              };

              _proto.render = function render(cameras) {
                for (var j = 0; j < this.flows.length; j++) {
                  for (var i = 0; i < cameras.length; i++) {
                    var camera = cameras[i];
                    this.flows[j].render(camera);
                  }
                }
              };

              _proto.destroy = function destroy() {
                for (var i = 0; i < this._flows.length; i++) {
                  this._flows[i].destroy();
                }

                this._flows.length = 0;

                if (this._descriptorSet) {
                  this._descriptorSet.destroy();
                }

                this._globalDSManager.destroy();

                for (var _i = 0; _i < this._commandBuffers.length; _i++) {
                  this._commandBuffers[_i].destroy();
                }

                this._commandBuffers.length = 0;

                this._pipelineUBO.destroy();

                this._pipelineSceneData.destroy();

                return _Asset.prototype.destroy.call(this);
              };

              _proto.resize = function resize(width, height) {};

              _proto._generateConstantMacros = function _generateConstantMacros() {
                var str = '';
                str += "#define CC_DEVICE_SUPPORT_FLOAT_TEXTURE " + (this.device.hasFeature(Feature.TEXTURE_FLOAT) ? 1 : 0) + "\n";
                str += "#define CC_DEVICE_MAX_VERTEX_UNIFORM_VECTORS " + this.device.capabilities.maxVertexUniformVectors + "\n";
                str += "#define CC_DEVICE_MAX_FRAGMENT_UNIFORM_VECTORS " + this.device.capabilities.maxFragmentUniformVectors + "\n";
                this._constantMacros = str;
              };

              _createClass(RenderPipeline, [{
                key: "tag",
                get: function get() {
                  return this._tag;
                }
              }, {
                key: "flows",
                get: function get() {
                  return this._flows;
                }
              }, {
                key: "constantMacros",
                get: function get() {
                  return this._constantMacros;
                }
              }, {
                key: "macros",
                get: function get() {
                  return this._macros;
                }
              }, {
                key: "device",
                get: function get() {
                  return this._device;
                }
              }, {
                key: "globalDSManager",
                get: function get() {
                  return this._globalDSManager;
                }
              }, {
                key: "descriptorSetLayout",
                get: function get() {
                  return this._globalDSManager.descriptorSetLayout;
                }
              }, {
                key: "descriptorSet",
                get: function get() {
                  return this._descriptorSet;
                }
              }, {
                key: "commandBuffers",
                get: function get() {
                  return this._commandBuffers;
                }
              }, {
                key: "pipelineUBO",
                get: function get() {
                  return this._pipelineUBO;
                }
              }, {
                key: "pipelineSceneData",
                get: function get() {
                  return this._pipelineSceneData;
                }
              }]);

              return RenderPipeline;
            }(Asset), _temp$j), (_descriptor$h = _applyDecoratedDescriptor(_class2$j.prototype, "_tag", [_dec2$b, serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor2$c = _applyDecoratedDescriptor(_class2$j.prototype, "_flows", [_dec3$7, _dec4$5, serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            })), _class2$j)) || _class$k));
            legacyCC.RenderPipeline = RenderPipeline;

            var ForwardStagePriority;

            (function (ForwardStagePriority) {
              ForwardStagePriority[ForwardStagePriority["FORWARD"] = 10] = "FORWARD";
              ForwardStagePriority[ForwardStagePriority["UI"] = 20] = "UI";
            })(ForwardStagePriority || (ForwardStagePriority = {}));

            var ForwardFlowPriority;

            (function (ForwardFlowPriority) {
              ForwardFlowPriority[ForwardFlowPriority["SHADOW"] = 0] = "SHADOW";
              ForwardFlowPriority[ForwardFlowPriority["FORWARD"] = 1] = "FORWARD";
              ForwardFlowPriority[ForwardFlowPriority["UI"] = 10] = "UI";
            })(ForwardFlowPriority || (ForwardFlowPriority = {}));

            var PipelineStateManager = exports('PipelineStateManager', function () {
              function PipelineStateManager() {}

              PipelineStateManager.getOrCreatePipelineState = function getOrCreatePipelineState(device, pass, shader, renderPass, ia) {
                var hash1 = pass.hash;
                var hash2 = renderPass.hash;
                var hash3 = ia.attributesHash;
                var hash4 = shader.id;
                var newHash = hash1 ^ hash2 ^ hash3 ^ hash4;

                var pso = this._PSOHashMap.get(newHash);

                if (!pso) {
                  var inputState = new InputState(ia.attributes);
                  var psoInfo = new PipelineStateInfo(shader, pass.pipelineLayout, renderPass, inputState, pass.rasterizerState, pass.depthStencilState, pass.blendState, pass.primitive, pass.dynamicStates);
                  pso = device.createPipelineState(psoInfo);

                  this._PSOHashMap.set(newHash, pso);
                }

                return pso;
              };

              return PipelineStateManager;
            }());
            PipelineStateManager._PSOHashMap = new Map();

            var _dec$l, _dec2$c, _dec3$8, _dec4$6, _class$l, _class2$k, _descriptor$i, _descriptor2$d, _descriptor3$a, _descriptor4$8, _descriptor5$5, _descriptor6$2, _temp$k, _dec5$3, _dec6$2, _class4$1, _class5$1, _descriptor7$2, _descriptor8$2, _temp2$1, _dec7$1, _dec8$1, _class7$1, _class8$1, _descriptor9$1, _descriptor10$1, _temp3$1, _dec9$1, _dec10$1, _dec11$1, _class10$1, _class11$1, _descriptor11$1, _descriptor12$1, _descriptor13$1, _descriptor14$1, _descriptor15$1, _temp4$1, _dec12$1, _dec13$1, _dec14$1, _dec15$1, _dec16$1, _dec17$1, _class13$1, _class14$1, _descriptor16$1, _descriptor17$1, _descriptor18$1, _descriptor19$1, _descriptor20$1, _descriptor21$1, _temp5$1, _dec18$1, _dec19$1, _dec20$1, _dec21$1, _dec22$1, _dec23$1, _dec24$1, _dec25$1, _class16$1, _class17$1, _descriptor22$1, _descriptor23$1, _descriptor24$1, _descriptor25$1, _descriptor26, _descriptor27, _descriptor28, _descriptor29, _temp6$1, _dec26$1, _dec27, _dec28, _class19$1, _class20$1, _descriptor30, _descriptor31, _descriptor32, _temp7$1, _dec29, _dec30, _dec31, _class22$1, _class23$1, _descriptor33, _descriptor34, _descriptor35, _temp8$1;
            ccenum(TextureType);
            ccenum(TextureUsageBit);
            ccenum(StoreOp);
            ccenum(LoadOp);
            ccenum(AccessType);
            var RenderFlowTag;

            (function (RenderFlowTag) {
              RenderFlowTag[RenderFlowTag["SCENE"] = 0] = "SCENE";
              RenderFlowTag[RenderFlowTag["POSTPROCESS"] = 1] = "POSTPROCESS";
              RenderFlowTag[RenderFlowTag["UI"] = 2] = "UI";
            })(RenderFlowTag || (RenderFlowTag = {}));

            ccenum(RenderFlowTag);
            var RenderTextureDesc = (_dec$l = ccclass('RenderTextureDesc'), _dec2$c = type(TextureType), _dec3$8 = type(TextureUsageBit), _dec4$6 = type(Format), _dec$l(_class$l = (_class2$k = (_temp$k = function RenderTextureDesc() {
              _initializerDefineProperty(this, "name", _descriptor$i, this);

              _initializerDefineProperty(this, "type", _descriptor2$d, this);

              _initializerDefineProperty(this, "usage", _descriptor3$a, this);

              _initializerDefineProperty(this, "format", _descriptor4$8, this);

              _initializerDefineProperty(this, "width", _descriptor5$5, this);

              _initializerDefineProperty(this, "height", _descriptor6$2, this);
            }, _temp$k), (_descriptor$i = _applyDecoratedDescriptor(_class2$k.prototype, "name", [serializable, editable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return '';
              }
            }), _descriptor2$d = _applyDecoratedDescriptor(_class2$k.prototype, "type", [_dec2$c], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return TextureType.TEX2D;
              }
            }), _descriptor3$a = _applyDecoratedDescriptor(_class2$k.prototype, "usage", [_dec3$8], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return TextureUsageBit.COLOR_ATTACHMENT;
              }
            }), _descriptor4$8 = _applyDecoratedDescriptor(_class2$k.prototype, "format", [_dec4$6], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return Format.UNKNOWN;
              }
            }), _descriptor5$5 = _applyDecoratedDescriptor(_class2$k.prototype, "width", [serializable, editable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return -1;
              }
            }), _descriptor6$2 = _applyDecoratedDescriptor(_class2$k.prototype, "height", [serializable, editable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return -1;
              }
            })), _class2$k)) || _class$l);
            var RenderTextureConfig = (_dec5$3 = ccclass('RenderTextureConfig'), _dec6$2 = type(RenderTexture), _dec5$3(_class4$1 = (_class5$1 = (_temp2$1 = function RenderTextureConfig() {
              _initializerDefineProperty(this, "name", _descriptor7$2, this);

              _initializerDefineProperty(this, "texture", _descriptor8$2, this);
            }, _temp2$1), (_descriptor7$2 = _applyDecoratedDescriptor(_class5$1.prototype, "name", [serializable, editable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return '';
              }
            }), _descriptor8$2 = _applyDecoratedDescriptor(_class5$1.prototype, "texture", [_dec6$2], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            })), _class5$1)) || _class4$1);
            var MaterialConfig = (_dec7$1 = ccclass('MaterialConfig'), _dec8$1 = type(Material), _dec7$1(_class7$1 = (_class8$1 = (_temp3$1 = function MaterialConfig() {
              _initializerDefineProperty(this, "name", _descriptor9$1, this);

              _initializerDefineProperty(this, "material", _descriptor10$1, this);
            }, _temp3$1), (_descriptor9$1 = _applyDecoratedDescriptor(_class8$1.prototype, "name", [serializable, editable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return '';
              }
            }), _descriptor10$1 = _applyDecoratedDescriptor(_class8$1.prototype, "material", [_dec8$1], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            })), _class8$1)) || _class7$1);
            var FrameBufferDesc = (_dec9$1 = ccclass('FrameBufferDesc'), _dec10$1 = type([CCString]), _dec11$1 = type(RenderTexture), _dec9$1(_class10$1 = (_class11$1 = (_temp4$1 = function FrameBufferDesc() {
              _initializerDefineProperty(this, "name", _descriptor11$1, this);

              _initializerDefineProperty(this, "renderPass", _descriptor12$1, this);

              _initializerDefineProperty(this, "colorTextures", _descriptor13$1, this);

              _initializerDefineProperty(this, "depthStencilTexture", _descriptor14$1, this);

              _initializerDefineProperty(this, "texture", _descriptor15$1, this);
            }, _temp4$1), (_descriptor11$1 = _applyDecoratedDescriptor(_class11$1.prototype, "name", [serializable, editable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return '';
              }
            }), _descriptor12$1 = _applyDecoratedDescriptor(_class11$1.prototype, "renderPass", [serializable, editable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor13$1 = _applyDecoratedDescriptor(_class11$1.prototype, "colorTextures", [_dec10$1], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor14$1 = _applyDecoratedDescriptor(_class11$1.prototype, "depthStencilTexture", [serializable, editable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return '';
              }
            }), _descriptor15$1 = _applyDecoratedDescriptor(_class11$1.prototype, "texture", [_dec11$1], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            })), _class11$1)) || _class10$1);
            var ColorDesc = (_dec12$1 = ccclass('ColorDesc'), _dec13$1 = type(Format), _dec14$1 = type(LoadOp), _dec15$1 = type(StoreOp), _dec16$1 = type([AccessType]), _dec17$1 = type([AccessType]), _dec12$1(_class13$1 = (_class14$1 = (_temp5$1 = function ColorDesc() {
              _initializerDefineProperty(this, "format", _descriptor16$1, this);

              _initializerDefineProperty(this, "loadOp", _descriptor17$1, this);

              _initializerDefineProperty(this, "storeOp", _descriptor18$1, this);

              _initializerDefineProperty(this, "sampleCount", _descriptor19$1, this);

              _initializerDefineProperty(this, "beginAccesses", _descriptor20$1, this);

              _initializerDefineProperty(this, "endAccesses", _descriptor21$1, this);
            }, _temp5$1), (_descriptor16$1 = _applyDecoratedDescriptor(_class14$1.prototype, "format", [_dec13$1], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return Format.UNKNOWN;
              }
            }), _descriptor17$1 = _applyDecoratedDescriptor(_class14$1.prototype, "loadOp", [_dec14$1], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return LoadOp.CLEAR;
              }
            }), _descriptor18$1 = _applyDecoratedDescriptor(_class14$1.prototype, "storeOp", [_dec15$1], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return StoreOp.STORE;
              }
            }), _descriptor19$1 = _applyDecoratedDescriptor(_class14$1.prototype, "sampleCount", [serializable, editable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1;
              }
            }), _descriptor20$1 = _applyDecoratedDescriptor(_class14$1.prototype, "beginAccesses", [_dec16$1], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor21$1 = _applyDecoratedDescriptor(_class14$1.prototype, "endAccesses", [_dec17$1], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [AccessType.PRESENT];
              }
            })), _class14$1)) || _class13$1);
            var DepthStencilDesc = (_dec18$1 = ccclass('DepthStencilDesc'), _dec19$1 = type(Format), _dec20$1 = type(LoadOp), _dec21$1 = type(StoreOp), _dec22$1 = type(LoadOp), _dec23$1 = type(StoreOp), _dec24$1 = type([AccessType]), _dec25$1 = type([AccessType]), _dec18$1(_class16$1 = (_class17$1 = (_temp6$1 = function DepthStencilDesc() {
              _initializerDefineProperty(this, "format", _descriptor22$1, this);

              _initializerDefineProperty(this, "depthLoadOp", _descriptor23$1, this);

              _initializerDefineProperty(this, "depthStoreOp", _descriptor24$1, this);

              _initializerDefineProperty(this, "stencilLoadOp", _descriptor25$1, this);

              _initializerDefineProperty(this, "stencilStoreOp", _descriptor26, this);

              _initializerDefineProperty(this, "sampleCount", _descriptor27, this);

              _initializerDefineProperty(this, "beginAccesses", _descriptor28, this);

              _initializerDefineProperty(this, "endAccesses", _descriptor29, this);
            }, _temp6$1), (_descriptor22$1 = _applyDecoratedDescriptor(_class17$1.prototype, "format", [_dec19$1], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return Format.UNKNOWN;
              }
            }), _descriptor23$1 = _applyDecoratedDescriptor(_class17$1.prototype, "depthLoadOp", [_dec20$1], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return LoadOp.CLEAR;
              }
            }), _descriptor24$1 = _applyDecoratedDescriptor(_class17$1.prototype, "depthStoreOp", [_dec21$1], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return StoreOp.STORE;
              }
            }), _descriptor25$1 = _applyDecoratedDescriptor(_class17$1.prototype, "stencilLoadOp", [_dec22$1], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return LoadOp.CLEAR;
              }
            }), _descriptor26 = _applyDecoratedDescriptor(_class17$1.prototype, "stencilStoreOp", [_dec23$1], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return StoreOp.STORE;
              }
            }), _descriptor27 = _applyDecoratedDescriptor(_class17$1.prototype, "sampleCount", [serializable, editable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1;
              }
            }), _descriptor28 = _applyDecoratedDescriptor(_class17$1.prototype, "beginAccesses", [_dec24$1], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor29 = _applyDecoratedDescriptor(_class17$1.prototype, "endAccesses", [_dec25$1], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [AccessType.DEPTH_STENCIL_ATTACHMENT_WRITE];
              }
            })), _class17$1)) || _class16$1);
            var RenderPassDesc = (_dec26$1 = ccclass('RenderPassDesc'), _dec27 = type([ColorDesc]), _dec28 = type(DepthStencilDesc), _dec26$1(_class19$1 = (_class20$1 = (_temp7$1 = function RenderPassDesc() {
              _initializerDefineProperty(this, "index", _descriptor30, this);

              _initializerDefineProperty(this, "colorAttachments", _descriptor31, this);

              _initializerDefineProperty(this, "depthStencilAttachment", _descriptor32, this);
            }, _temp7$1), (_descriptor30 = _applyDecoratedDescriptor(_class20$1.prototype, "index", [serializable, editable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return -1;
              }
            }), _descriptor31 = _applyDecoratedDescriptor(_class20$1.prototype, "colorAttachments", [_dec27], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor32 = _applyDecoratedDescriptor(_class20$1.prototype, "depthStencilAttachment", [_dec28], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new DepthStencilDesc();
              }
            })), _class20$1)) || _class19$1);
            var RenderQueueSortMode;

            (function (RenderQueueSortMode) {
              RenderQueueSortMode[RenderQueueSortMode["FRONT_TO_BACK"] = 0] = "FRONT_TO_BACK";
              RenderQueueSortMode[RenderQueueSortMode["BACK_TO_FRONT"] = 1] = "BACK_TO_FRONT";
            })(RenderQueueSortMode || (RenderQueueSortMode = {}));

            ccenum(RenderQueueSortMode);
            var RenderQueueDesc = (_dec29 = ccclass('RenderQueueDesc'), _dec30 = type(RenderQueueSortMode), _dec31 = type([CCString]), _dec29(_class22$1 = (_class23$1 = (_temp8$1 = function RenderQueueDesc() {
              _initializerDefineProperty(this, "isTransparent", _descriptor33, this);

              _initializerDefineProperty(this, "sortMode", _descriptor34, this);

              _initializerDefineProperty(this, "stages", _descriptor35, this);
            }, _temp8$1), (_descriptor33 = _applyDecoratedDescriptor(_class23$1.prototype, "isTransparent", [serializable, editable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor34 = _applyDecoratedDescriptor(_class23$1.prototype, "sortMode", [_dec30], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return RenderQueueSortMode.FRONT_TO_BACK;
              }
            }), _descriptor35 = _applyDecoratedDescriptor(_class23$1.prototype, "stages", [_dec31], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            })), _class23$1)) || _class22$1);

            function opaqueCompareFn(a, b) {
              return a.hash - b.hash || a.depth - b.depth || a.shaderId - b.shaderId;
            }
            function transparentCompareFn(a, b) {
              return a.hash - b.hash || b.depth - a.depth || a.shaderId - b.shaderId;
            }
            var RenderQueue = function () {
              function RenderQueue(desc) {
                this.queue = void 0;
                this._passDesc = void 0;
                this._passPool = void 0;
                this._passDesc = desc;
                this._passPool = new RecyclePool(function () {
                  return {
                    hash: 0,
                    depth: 0,
                    shaderId: 0,
                    subModel: null,
                    passIdx: 0
                  };
                }, 64);
                this.queue = new CachedArray(64, this._passDesc.sortFunc);
              }

              var _proto = RenderQueue.prototype;

              _proto.clear = function clear() {
                this.queue.clear();

                this._passPool.reset();
              };

              _proto.insertRenderPass = function insertRenderPass(renderObj, subModelIdx, passIdx) {
                var subModel = renderObj.model.subModels[subModelIdx];
                var pass = subModel.passes[passIdx];
                var isTransparent = pass.blendState.targets[0].blend;

                if (isTransparent !== this._passDesc.isTransparent || !(pass.phase & this._passDesc.phases)) {
                  return false;
                }

                var hash = 0 << 30 | pass.priority << 16 | subModel.priority << 8 | passIdx;

                var rp = this._passPool.add();

                rp.hash = hash;
                rp.depth = renderObj.depth || 0;
                rp.shaderId = SubModelPool.get(subModel.handle, SubModelView.SHADER_0 + passIdx);
                rp.subModel = subModel;
                rp.passIdx = passIdx;
                this.queue.push(rp);
                return true;
              };

              _proto.sort = function sort() {
                this.queue.sort();
              };

              _proto.recordCommandBuffer = function recordCommandBuffer(device, renderPass, cmdBuff) {
                for (var i = 0; i < this.queue.length; ++i) {
                  var _this$queue$array$i = this.queue.array[i],
                      subModel = _this$queue$array$i.subModel,
                      passIdx = _this$queue$array$i.passIdx;
                  var inputAssembler = subModel.inputAssembler,
                      hSubModel = subModel.handle;
                  var pass = subModel.passes[passIdx];
                  var shader = ShaderPool.get(SubModelPool.get(hSubModel, SubModelView.SHADER_0 + passIdx));
                  var pso = PipelineStateManager.getOrCreatePipelineState(device, pass, shader, renderPass, inputAssembler);
                  cmdBuff.bindPipelineState(pso);
                  cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet);
                  cmdBuff.bindDescriptorSet(SetIndex.LOCAL, subModel.descriptorSet);
                  cmdBuff.bindInputAssembler(inputAssembler);
                  cmdBuff.draw(inputAssembler);
                }
              };

              return RenderQueue;
            }();
            function convertRenderQueue(desc) {
              var phase = 0;

              for (var j = 0; j < desc.stages.length; j++) {
                phase |= getPhaseID(desc.stages[j]);
              }

              var sortFunc = opaqueCompareFn;

              switch (desc.sortMode) {
                case RenderQueueSortMode.BACK_TO_FRONT:
                  sortFunc = transparentCompareFn;
                  break;

                case RenderQueueSortMode.FRONT_TO_BACK:
                  sortFunc = opaqueCompareFn;
                  break;
              }

              return new RenderQueue({
                isTransparent: desc.isTransparent,
                phases: phase,
                sortFunc: sortFunc
              });
            }
            function renderQueueClearFunc(rq) {
              rq.clear();
            }
            function renderQueueSortFunc(rq) {
              rq.sort();
            }

            function SRGBToLinear(out, gamma) {
              out.x = gamma.x * gamma.x;
              out.y = gamma.y * gamma.y;
              out.z = gamma.z * gamma.z;
            }

            var RenderBatchedQueue = function () {
              function RenderBatchedQueue() {
                this.queue = new Set();
              }

              var _proto = RenderBatchedQueue.prototype;

              _proto.clear = function clear() {
                var it = this.queue.values();
                var res = it.next();

                while (!res.done) {
                  res.value.clear();
                  res = it.next();
                }

                this.queue.clear();
              };

              _proto.uploadBuffers = function uploadBuffers(cmdBuff) {
                var it = this.queue.values();
                var res = it.next();

                while (!res.done) {
                  for (var b = 0; b < res.value.batches.length; ++b) {
                    var batch = res.value.batches[b];

                    if (!batch.mergeCount) {
                      continue;
                    }

                    for (var v = 0; v < batch.vbs.length; ++v) {
                      batch.vbs[v].update(batch.vbDatas[v]);
                    }

                    cmdBuff.updateBuffer(batch.vbIdx, batch.vbIdxData.buffer);
                    cmdBuff.updateBuffer(batch.ubo, batch.uboData);
                  }

                  res = it.next();
                }
              };

              _proto.recordCommandBuffer = function recordCommandBuffer(device, renderPass, cmdBuff) {
                var it = this.queue.values();
                var res = it.next();

                while (!res.done) {
                  var boundPSO = false;

                  for (var b = 0; b < res.value.batches.length; ++b) {
                    var batch = res.value.batches[b];

                    if (!batch.mergeCount) {
                      continue;
                    }

                    if (!boundPSO) {
                      var shader = ShaderPool.get(batch.hShader);
                      var pso = PipelineStateManager.getOrCreatePipelineState(device, batch.pass, shader, renderPass, batch.ia);
                      cmdBuff.bindPipelineState(pso);
                      cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, batch.pass.descriptorSet);
                      boundPSO = true;
                    }

                    cmdBuff.bindDescriptorSet(SetIndex.LOCAL, batch.descriptorSet, res.value.dynamicOffsets);
                    cmdBuff.bindInputAssembler(batch.ia);
                    cmdBuff.draw(batch.ia);
                  }

                  res = it.next();
                }
              };

              return RenderBatchedQueue;
            }();

            var RenderInstancedQueue = function () {
              function RenderInstancedQueue() {
                this.queue = new Set();
              }

              var _proto = RenderInstancedQueue.prototype;

              _proto.clear = function clear() {
                var it = this.queue.values();
                var res = it.next();

                while (!res.done) {
                  res.value.clear();
                  res = it.next();
                }

                this.queue.clear();
              };

              _proto.uploadBuffers = function uploadBuffers(cmdBuff) {
                var it = this.queue.values();
                var res = it.next();

                while (!res.done) {
                  if (res.value.hasPendingModels) res.value.uploadBuffers(cmdBuff);
                  res = it.next();
                }
              };

              _proto.recordCommandBuffer = function recordCommandBuffer(device, renderPass, cmdBuff) {
                var it = this.queue.values();
                var res = it.next();

                while (!res.done) {
                  var _res$value = res.value,
                      instances = _res$value.instances,
                      pass = _res$value.pass,
                      hasPendingModels = _res$value.hasPendingModels;

                  if (hasPendingModels) {
                    cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet);
                    var lastPSO = null;

                    for (var b = 0; b < instances.length; ++b) {
                      var instance = instances[b];

                      if (!instance.count) {
                        continue;
                      }

                      var shader = ShaderPool.get(instance.hShader);
                      var pso = PipelineStateManager.getOrCreatePipelineState(device, pass, shader, renderPass, instance.ia);

                      if (lastPSO !== pso) {
                        cmdBuff.bindPipelineState(pso);
                        lastPSO = pso;
                      }

                      cmdBuff.bindDescriptorSet(SetIndex.LOCAL, DSPool.get(instance.hDescriptorSet), res.value.dynamicOffsets);
                      cmdBuff.bindInputAssembler(instance.ia);
                      cmdBuff.draw(instance.ia);
                    }
                  }

                  res = it.next();
                }
              };

              return RenderInstancedQueue;
            }();

            var BatchedBuffer = function () {
              BatchedBuffer.get = function get(pass, extraKey) {
                if (extraKey === void 0) {
                  extraKey = 0;
                }

                var buffers = BatchedBuffer._buffers;
                if (!buffers.has(pass)) buffers.set(pass, {});
                var record = buffers.get(pass);
                return record[extraKey] || (record[extraKey] = new BatchedBuffer(pass));
              };

              function BatchedBuffer(pass) {
                this.batches = [];
                this.dynamicOffsets = [];
                this._device = void 0;
                this._device = pass.device;
              }

              var _proto = BatchedBuffer.prototype;

              _proto.destroy = function destroy() {
                for (var i = 0; i < this.batches.length; ++i) {
                  var batch = this.batches[i];

                  for (var j = 0; j < batch.vbs.length; ++j) {
                    batch.vbs[j].destroy();
                  }

                  batch.vbIdx.destroy();
                  batch.ia.destroy();
                  batch.ubo.destroy();
                }

                this.batches.length = 0;
              };

              _proto.merge = function merge(subModel, passIdx, model) {
                var flatBuffers = subModel.subMesh.flatBuffers;

                if (flatBuffers.length === 0) {
                  return;
                }

                var vbSize = 0;
                var vbIdxSize = 0;
                var vbCount = flatBuffers[0].count;
                var pass = subModel.passes[passIdx];
                var hShader = SubModelPool.get(subModel.handle, SubModelView.SHADER_0 + passIdx);
                var descriptorSet = subModel.descriptorSet;
                var isBatchExist = false;

                for (var i = 0; i < this.batches.length; ++i) {
                  var batch = this.batches[i];

                  if (batch.vbs.length === flatBuffers.length && batch.mergeCount < UBOLocalBatched.BATCHING_COUNT) {
                    isBatchExist = true;

                    for (var j = 0; j < batch.vbs.length; ++j) {
                      var vb = batch.vbs[j];

                      if (vb.stride !== flatBuffers[j].stride) {
                        isBatchExist = false;
                        break;
                      }
                    }

                    if (isBatchExist) {
                      for (var _j = 0; _j < batch.vbs.length; ++_j) {
                        var flatBuff = flatBuffers[_j];
                        var batchVB = batch.vbs[_j];
                        var vbBuf = batch.vbDatas[_j];
                        vbSize = (vbCount + batch.vbCount) * flatBuff.stride;

                        if (vbSize > batchVB.size) {
                          batchVB.resize(vbSize);
                          batch.vbDatas[_j] = new Uint8Array(vbSize);

                          batch.vbDatas[_j].set(vbBuf);
                        }

                        batch.vbDatas[_j].set(flatBuff.buffer, batch.vbCount * flatBuff.stride);
                      }

                      var vbIdxBuf = batch.vbIdxData;
                      vbIdxSize = (vbCount + batch.vbCount) * 4;

                      if (vbIdxSize > batch.vbIdx.size) {
                        batch.vbIdx.resize(vbIdxSize);
                        batch.vbIdxData = new Float32Array(vbIdxSize / Float32Array.BYTES_PER_ELEMENT);
                        batch.vbIdxData.set(vbIdxBuf);
                        vbIdxBuf = batch.vbIdxData;
                      }

                      var start = batch.vbCount;
                      var end = start + vbCount;
                      var mergeCount = batch.mergeCount;

                      if (vbIdxBuf[start] !== mergeCount || vbIdxBuf[end - 1] !== mergeCount) {
                        for (var _j2 = start; _j2 < end; _j2++) {
                          vbIdxBuf[_j2] = mergeCount + 0.1;
                        }
                      }

                      Mat4.toArray(batch.uboData, model.transform.worldMatrix, UBOLocalBatched.MAT_WORLDS_OFFSET + batch.mergeCount * 16);

                      if (!batch.mergeCount) {
                        descriptorSet.bindBuffer(UBOLocalBatched.BINDING, batch.ubo);
                        descriptorSet.update();
                        batch.pass = pass;
                        batch.hShader = hShader;
                        batch.descriptorSet = descriptorSet;
                      }

                      ++batch.mergeCount;
                      batch.vbCount += vbCount;
                      batch.ia.vertexCount += vbCount;
                      return;
                    }
                  }
                }

                var vbs = [];
                var vbDatas = [];
                var totalVBs = [];

                for (var _i = 0; _i < flatBuffers.length; ++_i) {
                  var _flatBuff = flatBuffers[_i];

                  var newVB = this._device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, _flatBuff.count * _flatBuff.stride, _flatBuff.stride));

                  newVB.update(_flatBuff.buffer.buffer);
                  vbs.push(newVB);
                  vbDatas.push(new Uint8Array(newVB.size));
                  totalVBs.push(newVB);
                }

                var vbIdx = this._device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, vbCount * 4, 4));

                var vbIdxData = new Float32Array(vbCount);
                vbIdxData.fill(0);
                vbIdx.update(vbIdxData);
                totalVBs.push(vbIdx);
                var attributes = subModel.inputAssembler.attributes;
                var attrs = new Array(attributes.length + 1);

                for (var a = 0; a < attributes.length; ++a) {
                  attrs[a] = attributes[a];
                }

                attrs[attributes.length] = new Attribute('a_dyn_batch_id', Format.R32F, false, flatBuffers.length);
                var iaInfo = new InputAssemblerInfo(attrs, totalVBs);

                var ia = this._device.createInputAssembler(iaInfo);

                var ubo = this._device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, UBOLocalBatched.SIZE, UBOLocalBatched.SIZE));

                descriptorSet.bindBuffer(UBOLocalBatched.BINDING, ubo);
                descriptorSet.update();
                var uboData = new Float32Array(UBOLocalBatched.COUNT);
                Mat4.toArray(uboData, model.transform.worldMatrix, UBOLocalBatched.MAT_WORLDS_OFFSET);
                this.batches.push({
                  mergeCount: 1,
                  vbs: vbs,
                  vbDatas: vbDatas,
                  vbIdx: vbIdx,
                  vbIdxData: vbIdxData,
                  vbCount: vbCount,
                  ia: ia,
                  ubo: ubo,
                  uboData: uboData,
                  pass: pass,
                  hShader: hShader,
                  descriptorSet: descriptorSet
                });
              };

              _proto.clear = function clear() {
                for (var i = 0; i < this.batches.length; ++i) {
                  var batch = this.batches[i];
                  batch.vbCount = 0;
                  batch.mergeCount = 0;
                  batch.ia.vertexCount = 0;
                }
              };

              return BatchedBuffer;
            }();
            BatchedBuffer._buffers = new Map();

            var INITIAL_CAPACITY = 32;
            var MAX_CAPACITY = 1024;
            var InstancedBuffer = exports('InstancedBuffer', function () {
              InstancedBuffer.get = function get(pass, extraKey) {
                if (extraKey === void 0) {
                  extraKey = 0;
                }

                var buffers = InstancedBuffer._buffers;
                if (!buffers.has(pass)) buffers.set(pass, {});
                var record = buffers.get(pass);
                return record[extraKey] || (record[extraKey] = new InstancedBuffer(pass));
              };

              function InstancedBuffer(pass) {
                this.instances = [];
                this.pass = void 0;
                this.hasPendingModels = false;
                this.dynamicOffsets = [];
                this._device = void 0;
                this._device = pass.device;
                this.pass = pass;
              }

              var _proto = InstancedBuffer.prototype;

              _proto.destroy = function destroy() {
                for (var i = 0; i < this.instances.length; ++i) {
                  var instance = this.instances[i];
                  instance.vb.destroy();
                  instance.ia.destroy();
                }

                this.instances.length = 0;
              };

              _proto.merge = function merge(subModel, attrs, passIdx, hShaderImplant) {
                if (hShaderImplant === void 0) {
                  hShaderImplant = null;
                }

                var stride = attrs.buffer.length;

                if (!stride) {
                  return;
                }

                var sourceIA = subModel.inputAssembler;
                var lightingMap = subModel.descriptorSet.getTexture(UNIFORM_LIGHTMAP_TEXTURE_BINDING);
                var hShader = hShaderImplant;

                if (!hShader) {
                  hShader = SubModelPool.get(subModel.handle, SubModelView.SHADER_0 + passIdx);
                }

                var hDescriptorSet = SubModelPool.get(subModel.handle, SubModelView.DESCRIPTOR_SET);

                for (var i = 0; i < this.instances.length; ++i) {
                  var instance = this.instances[i];

                  if (instance.ia.indexBuffer !== sourceIA.indexBuffer || instance.count >= MAX_CAPACITY) {
                    continue;
                  }

                  if (instance.lightingMap !== lightingMap) {
                    continue;
                  }

                  if (instance.stride !== stride) {
                    return;
                  }

                  if (instance.count >= instance.capacity) {
                    instance.capacity <<= 1;
                    var newSize = instance.stride * instance.capacity;
                    var oldData = instance.data;
                    instance.data = new Uint8Array(newSize);
                    instance.data.set(oldData);
                    instance.vb.resize(newSize);
                  }

                  if (instance.hShader !== hShader) {
                    instance.hShader = hShader;
                  }

                  if (instance.hDescriptorSet !== hDescriptorSet) {
                    instance.hDescriptorSet = hDescriptorSet;
                  }

                  instance.data.set(attrs.buffer, instance.stride * instance.count++);
                  this.hasPendingModels = true;
                  return;
                }

                var vb = this._device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, stride * INITIAL_CAPACITY, stride));

                var data = new Uint8Array(stride * INITIAL_CAPACITY);
                var vertexBuffers = sourceIA.vertexBuffers.slice();
                var attributes = sourceIA.attributes.slice();
                var indexBuffer = sourceIA.indexBuffer;

                for (var _i = 0; _i < attrs.attributes.length; _i++) {
                  var attr = attrs.attributes[_i];
                  var newAttr = new Attribute(attr.name, attr.format, attr.isNormalized, vertexBuffers.length, true);
                  attributes.push(newAttr);
                }

                data.set(attrs.buffer);
                vertexBuffers.push(vb);
                var iaInfo = new InputAssemblerInfo(attributes, vertexBuffers, indexBuffer);

                var ia = this._device.createInputAssembler(iaInfo);

                this.instances.push({
                  count: 1,
                  capacity: INITIAL_CAPACITY,
                  vb: vb,
                  data: data,
                  ia: ia,
                  stride: stride,
                  hShader: hShader,
                  hDescriptorSet: hDescriptorSet,
                  lightingMap: lightingMap
                });
                this.hasPendingModels = true;
              };

              _proto.uploadBuffers = function uploadBuffers(cmdBuff) {
                for (var i = 0; i < this.instances.length; ++i) {
                  var instance = this.instances[i];

                  if (!instance.count) {
                    continue;
                  }

                  instance.ia.instanceCount = instance.count;
                  cmdBuff.updateBuffer(instance.vb, instance.data);
                }
              };

              _proto.clear = function clear() {
                for (var i = 0; i < this.instances.length; ++i) {
                  var instance = this.instances[i];
                  instance.count = 0;
                }

                this.hasPendingModels = false;
              };

              return InstancedBuffer;
            }());
            InstancedBuffer._buffers = new Map();

            var _lightPassPool = new Pool$1(function () {
              return {
                subModel: null,
                passIdx: -1,
                dynamicOffsets: [],
                lights: []
              };
            }, 16);

            var _vec4Array = new Float32Array(4);

            var _sphere$1 = Sphere.create(0, 0, 0, 1);

            var _dynamicOffsets = [];
            var _lightIndices = [];

            var _matShadowView = new Mat4();

            var _matShadowViewProj = new Mat4();

            function cullSphereLight(light, model) {
              return !!(model.worldBounds && !intersect.aabbWithAABB(model.worldBounds, light.aabb));
            }

            function cullSpotLight(light, model) {
              return !!(model.worldBounds && (!intersect.aabbWithAABB(model.worldBounds, light.aabb) || !intersect.aabbFrustum(model.worldBounds, light.frustum)));
            }

            var _phaseID = getPhaseID('forward-add');

            var _lightPassIndices = [];

            function getLightPassIndices(subModels, lightPassIndices) {
              lightPassIndices.length = 0;
              var hasValidLightPass = false;

              for (var j = 0; j < subModels.length; j++) {
                var passes = subModels[j].passes;
                var lightPassIndex = -1;

                for (var k = 0; k < passes.length; k++) {
                  if (passes[k].phase === _phaseID) {
                    lightPassIndex = k;
                    hasValidLightPass = true;
                    break;
                  }
                }

                lightPassIndices.push(lightPassIndex);
              }

              return hasValidLightPass;
            }

            var RenderAdditiveLightQueue = function () {
              function RenderAdditiveLightQueue(pipeline) {
                this._pipeline = void 0;
                this._device = void 0;
                this._validLights = [];
                this._lightPasses = [];
                this._shadowUBO = new Float32Array(UBOShadow.COUNT);
                this._lightBufferCount = 16;
                this._lightBufferStride = void 0;
                this._lightBufferElementCount = void 0;
                this._lightBuffer = void 0;
                this._firstLightBufferView = void 0;
                this._lightBufferData = void 0;
                this._instancedQueue = void 0;
                this._batchedQueue = void 0;
                this._lightMeterScale = 10000.0;
                this._pipeline = pipeline;
                this._device = pipeline.device;
                this._instancedQueue = new RenderInstancedQueue();
                this._batchedQueue = new RenderBatchedQueue();
                var alignment = this._device.capabilities.uboOffsetAlignment;
                this._lightBufferStride = Math.ceil(UBOForwardLight.SIZE / alignment) * alignment;
                this._lightBufferElementCount = this._lightBufferStride / Float32Array.BYTES_PER_ELEMENT;
                this._lightBuffer = this._device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, this._lightBufferStride * this._lightBufferCount, this._lightBufferStride));
                this._firstLightBufferView = this._device.createBuffer(new BufferViewInfo(this._lightBuffer, 0, UBOForwardLight.SIZE));
                this._lightBufferData = new Float32Array(this._lightBufferElementCount * this._lightBufferCount);
              }

              var _proto = RenderAdditiveLightQueue.prototype;

              _proto.clear = function clear() {
                this._instancedQueue.clear();

                this._batchedQueue.clear();

                this._validLights.length = 0;

                for (var i = 0; i < this._lightPasses.length; i++) {
                  var lp = this._lightPasses[i];
                  lp.dynamicOffsets.length = 0;
                  lp.lights.length = 0;
                }

                _lightPassPool.freeArray(this._lightPasses);

                this._lightPasses.length = 0;
              };

              _proto.destroy = function destroy() {
                var descriptorSetMap = this._pipeline.globalDSManager.descriptorSetMap;
                var keys = descriptorSetMap.keys;

                for (var i = 0; i < keys.length; i++) {
                  var key = keys[i];
                  var descriptorSet = descriptorSetMap.get(key);

                  if (descriptorSet) {
                    descriptorSet.getBuffer(UBOShadow.BINDING).destroy();
                    descriptorSet.getSampler(UNIFORM_SHADOWMAP_BINDING).destroy();
                    descriptorSet.getSampler(UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING).destroy();
                    descriptorSet.getTexture(UNIFORM_SHADOWMAP_BINDING).destroy();
                    descriptorSet.getTexture(UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING).destroy();
                    descriptorSet.destroy();
                  }

                  descriptorSetMap["delete"](key);
                }
              };

              _proto.gatherLightPasses = function gatherLightPasses(camera, cmdBuff) {
                var validLights = this._validLights;
                this.clear();

                this._gatherValidLights(camera, validLights);

                if (!validLights.length) {
                  return;
                }

                this._updateUBOs(camera, cmdBuff);

                this._updateLightDescriptorSet(camera, cmdBuff);

                var renderObjects = this._pipeline.pipelineSceneData.renderObjects;

                for (var i = 0; i < renderObjects.length; i++) {
                  var ro = renderObjects[i];
                  var model = ro.model;
                  var subModels = model.subModels;

                  if (!getLightPassIndices(subModels, _lightPassIndices)) {
                    continue;
                  }

                  _lightIndices.length = 0;

                  this._lightCulling(model, validLights);

                  if (!_lightIndices.length) {
                    continue;
                  }

                  for (var j = 0; j < subModels.length; j++) {
                    var lightPassIdx = _lightPassIndices[j];

                    if (lightPassIdx < 0) {
                      continue;
                    }

                    var subModel = subModels[j];
                    var pass = subModel.passes[lightPassIdx];
                    subModel.descriptorSet.bindBuffer(UBOForwardLight.BINDING, this._firstLightBufferView);
                    subModel.descriptorSet.update();

                    this._addRenderQueue(pass, subModel, model, lightPassIdx, validLights);
                  }
                }

                this._instancedQueue.uploadBuffers(cmdBuff);

                this._batchedQueue.uploadBuffers(cmdBuff);
              };

              _proto.recordCommandBuffer = function recordCommandBuffer(device, renderPass, cmdBuff) {
                this._instancedQueue.recordCommandBuffer(device, renderPass, cmdBuff);

                this._batchedQueue.recordCommandBuffer(device, renderPass, cmdBuff);

                var globalDSManager = this._pipeline.globalDSManager;

                for (var i = 0; i < this._lightPasses.length; i++) {
                  var _this$_lightPasses$i = this._lightPasses[i],
                      subModel = _this$_lightPasses$i.subModel,
                      passIdx = _this$_lightPasses$i.passIdx,
                      dynamicOffsets = _this$_lightPasses$i.dynamicOffsets,
                      lights = _this$_lightPasses$i.lights;
                  var shader = ShaderPool.get(SubModelPool.get(subModel.handle, SubModelView.SHADER_0 + passIdx));
                  var pass = subModel.passes[passIdx];
                  var ia = subModel.inputAssembler;
                  var pso = PipelineStateManager.getOrCreatePipelineState(device, pass, shader, renderPass, ia);
                  var matDS = DSPool.get(PassPool.get(pass.handle, PassView.DESCRIPTOR_SET));
                  var localDS = subModel.descriptorSet;
                  cmdBuff.bindPipelineState(pso);
                  cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, matDS);
                  cmdBuff.bindInputAssembler(ia);

                  for (var j = 0; j < dynamicOffsets.length; ++j) {
                    var light = lights[j];
                    var descriptorSet = globalDSManager.getOrCreateDescriptorSet(light);
                    _dynamicOffsets[0] = dynamicOffsets[j];
                    cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, descriptorSet);
                    cmdBuff.bindDescriptorSet(SetIndex.LOCAL, localDS, _dynamicOffsets);
                    cmdBuff.draw(ia);
                  }
                }
              };

              _proto._gatherValidLights = function _gatherValidLights(camera, validLights) {
                var _ref = camera.scene,
                    sphereLights = _ref.sphereLights;

                for (var i = 0; i < sphereLights.length; i++) {
                  var light = sphereLights[i];

                  if (light.baked) {
                    continue;
                  }

                  Sphere.set(_sphere$1, light.position.x, light.position.y, light.position.z, light.range);

                  if (intersect.sphereFrustum(_sphere$1, camera.frustum)) {
                    validLights.push(light);
                  }
                }

                var _ref2 = camera.scene,
                    spotLights = _ref2.spotLights;

                for (var _i = 0; _i < spotLights.length; _i++) {
                  var _light = spotLights[_i];

                  if (_light.baked) {
                    continue;
                  }

                  Sphere.set(_sphere$1, _light.position.x, _light.position.y, _light.position.z, _light.range);

                  if (intersect.sphereFrustum(_sphere$1, camera.frustum)) {
                    validLights.push(_light);
                  }
                }
              };

              _proto._lightCulling = function _lightCulling(model, validLights) {
                for (var l = 0; l < validLights.length; l++) {
                  var light = validLights[l];
                  var isCulled = false;

                  switch (light.type) {
                    case LightType.SPHERE:
                      isCulled = cullSphereLight(light, model);
                      break;

                    case LightType.SPOT:
                      isCulled = cullSpotLight(light, model);
                      break;
                  }

                  if (!isCulled) {
                    _lightIndices.push(l);
                  }
                }
              };

              _proto._addRenderQueue = function _addRenderQueue(pass, subModel, model, lightPassIdx, validLights) {
                var batchingScheme = pass.batchingScheme;

                if (batchingScheme === BatchingSchemes.INSTANCING) {
                  for (var l = 0; l < _lightIndices.length; l++) {
                    var idx = _lightIndices[l];
                    var buffer = InstancedBuffer.get(pass, idx);
                    buffer.merge(subModel, model.instancedAttributes, lightPassIdx);
                    buffer.dynamicOffsets[0] = this._lightBufferStride * idx;

                    this._instancedQueue.queue.add(buffer);
                  }
                } else if (batchingScheme === BatchingSchemes.VB_MERGING) {
                  for (var _l = 0; _l < _lightIndices.length; _l++) {
                    var _idx = _lightIndices[_l];

                    var _buffer = BatchedBuffer.get(pass, _idx);

                    _buffer.merge(subModel, lightPassIdx, model);

                    _buffer.dynamicOffsets[0] = this._lightBufferStride * _idx;

                    this._batchedQueue.queue.add(_buffer);
                  }
                } else {
                  var lp = _lightPassPool.alloc();

                  lp.subModel = subModel;
                  lp.passIdx = lightPassIdx;

                  for (var _l2 = 0; _l2 < _lightIndices.length; _l2++) {
                    var _idx2 = _lightIndices[_l2];
                    lp.lights.push(_idx2);
                    lp.dynamicOffsets.push(this._lightBufferStride * _idx2);
                  }

                  this._lightPasses.push(lp);
                }
              };

              _proto._updateLightDescriptorSet = function _updateLightDescriptorSet(camera, cmdBuff) {
                var device = this._pipeline.device;
                var sceneData = this._pipeline.pipelineSceneData;
                var shadowInfo = sceneData.shadows;
                var shadowFrameBufferMap = sceneData.shadowFrameBufferMap;
                var mainLight = camera.scene.mainLight;
                var isSupportHalfFloat = supportsHalfFloatTexture(device);
                var linear = shadowInfo.linear && isSupportHalfFloat ? 1.0 : 0.0;
                var packing = shadowInfo.packing ? 1.0 : isSupportHalfFloat ? 0.0 : 1.0;
                var globalDSManager = this._pipeline.globalDSManager;

                for (var i = 0; i < this._validLights.length; i++) {
                  var light = this._validLights[i];
                  var descriptorSet = globalDSManager.getOrCreateDescriptorSet(i);

                  if (!descriptorSet) {
                    continue;
                  }

                  switch (light.type) {
                    case LightType.SPHERE:
                      if (mainLight) {
                        updatePlanarPROJ(shadowInfo, mainLight, this._shadowUBO);
                      }

                      this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 0] = shadowInfo.size.x;
                      this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 1] = shadowInfo.size.y;
                      this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 2] = shadowInfo.pcf;
                      this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 3] = shadowInfo.bias;
                      this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 0] = 2.0;
                      this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 1] = packing;
                      this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 2] = shadowInfo.normalBias;
                      this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 3] = 0.0;
                      Color.toArray(this._shadowUBO, shadowInfo.shadowColor, UBOShadow.SHADOW_COLOR_OFFSET);
                      break;

                    case LightType.SPOT:
                      if (mainLight) {
                        updatePlanarPROJ(shadowInfo, mainLight, this._shadowUBO);
                      }

                      Mat4.toArray(this._shadowUBO, light.node.getWorldMatrix(), UBOShadow.MAT_LIGHT_VIEW_OFFSET);
                      Mat4.invert(_matShadowView, light.node.getWorldMatrix());
                      Mat4.perspective(_matShadowViewProj, light.spotAngle, light.aspect, 0.001, light.range);
                      Mat4.multiply(_matShadowViewProj, _matShadowViewProj, _matShadowView);
                      Mat4.toArray(this._shadowUBO, _matShadowViewProj, UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET);
                      this._shadowUBO[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SELF_INFO_OFFSET + 0] = 0.01;
                      this._shadowUBO[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SELF_INFO_OFFSET + 1] = light.range;
                      this._shadowUBO[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SELF_INFO_OFFSET + 2] = linear;
                      this._shadowUBO[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SELF_INFO_OFFSET + 3] = shadowInfo.selfShadow ? 1.0 : 0.0;
                      this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 0] = shadowInfo.size.x;
                      this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 1] = shadowInfo.size.y;
                      this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 2] = shadowInfo.pcf;
                      this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 3] = shadowInfo.bias;
                      this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 0] = 1.0;
                      this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 1] = packing;
                      this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 2] = shadowInfo.normalBias;
                      this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 3] = 0.0;
                      Color.toArray(this._shadowUBO, shadowInfo.shadowColor, UBOShadow.SHADOW_COLOR_OFFSET);

                      if (shadowFrameBufferMap.has(light)) {
                        var _shadowFrameBufferMap;

                        var texture = (_shadowFrameBufferMap = shadowFrameBufferMap.get(light)) === null || _shadowFrameBufferMap === void 0 ? void 0 : _shadowFrameBufferMap.colorTextures[0];

                        if (texture) {
                          descriptorSet.bindTexture(UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING, texture);
                        }
                      }

                      break;
                  }

                  descriptorSet.update();
                  cmdBuff.updateBuffer(descriptorSet.getBuffer(UBOShadow.BINDING), this._shadowUBO);
                }
              };

              _proto._updateUBOs = function _updateUBOs(camera, cmdBuff) {
                var exposure = camera.exposure;
                var sceneData = this._pipeline.pipelineSceneData;
                var isHDR = sceneData.isHDR;
                var fpScale = sceneData.fpScale;

                if (this._validLights.length > this._lightBufferCount) {
                  this._firstLightBufferView.destroy();

                  this._lightBufferCount = nextPow2$1(this._validLights.length);

                  this._lightBuffer.resize(this._lightBufferStride * this._lightBufferCount);

                  this._lightBufferData = new Float32Array(this._lightBufferElementCount * this._lightBufferCount);

                  this._firstLightBufferView.initialize(new BufferViewInfo(this._lightBuffer, 0, UBOForwardLight.SIZE));
                }

                for (var l = 0, offset = 0; l < this._validLights.length; l++, offset += this._lightBufferElementCount) {
                  var light = this._validLights[l];

                  switch (light.type) {
                    case LightType.SPHERE:
                      Vec3.toArray(_vec4Array, light.position);
                      _vec4Array[3] = 0;

                      this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_POS_OFFSET);

                      _vec4Array[0] = light.size;
                      _vec4Array[1] = light.range;
                      _vec4Array[2] = 0.0;

                      this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET);

                      Vec3.toArray(_vec4Array, light.color);

                      if (light.useColorTemperature) {
                        var tempRGB = light.colorTemperatureRGB;
                        _vec4Array[0] *= tempRGB.x;
                        _vec4Array[1] *= tempRGB.y;
                        _vec4Array[2] *= tempRGB.z;
                      }

                      if (isHDR) {
                        _vec4Array[3] = light.luminance * fpScale * this._lightMeterScale;
                      } else {
                        _vec4Array[3] = light.luminance * exposure * this._lightMeterScale;
                      }

                      this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_COLOR_OFFSET);

                      break;

                    case LightType.SPOT:
                      Vec3.toArray(_vec4Array, light.position);
                      _vec4Array[3] = 1;

                      this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_POS_OFFSET);

                      _vec4Array[0] = light.size;
                      _vec4Array[1] = light.range;
                      _vec4Array[2] = light.spotAngle;

                      this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET);

                      Vec3.toArray(_vec4Array, light.direction);

                      this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_DIR_OFFSET);

                      Vec3.toArray(_vec4Array, light.color);

                      if (light.useColorTemperature) {
                        var _tempRGB = light.colorTemperatureRGB;
                        _vec4Array[0] *= _tempRGB.x;
                        _vec4Array[1] *= _tempRGB.y;
                        _vec4Array[2] *= _tempRGB.z;
                      }

                      if (isHDR) {
                        _vec4Array[3] = light.luminance * fpScale * this._lightMeterScale;
                      } else {
                        _vec4Array[3] = light.luminance * exposure * this._lightMeterScale;
                      }

                      this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_COLOR_OFFSET);

                      break;
                  }
                }

                cmdBuff.updateBuffer(this._lightBuffer, this._lightBufferData);
              };

              return RenderAdditiveLightQueue;
            }();

            var _ab = new AABB();

            var PlanarShadowQueue = function () {
              function PlanarShadowQueue(pipeline) {
                this._pendingModels = [];
                this._instancedQueue = new RenderInstancedQueue();
                this._pipeline = void 0;
                this._pipeline = pipeline;
              }

              var _proto = PlanarShadowQueue.prototype;

              _proto.gatherShadowPasses = function gatherShadowPasses(camera, cmdBuff) {
                var pipelineSceneData = this._pipeline.pipelineSceneData;
                var pipelineUBO = this._pipeline.pipelineUBO;
                var shadows = pipelineSceneData.shadows;

                this._instancedQueue.clear();

                this._pendingModels.length = 0;

                if (!shadows.enabled || shadows.type !== ShadowType.Planar) {
                  return;
                }

                pipelineUBO.updateShadowUBO(camera);
                var scene = camera.scene;
                var frustum = camera.frustum;
                var shadowVisible = (camera.visibility & Layers.BitMask.DEFAULT) !== 0;

                if (!scene.mainLight || !shadowVisible) {
                  return;
                }

                var renderObjects = pipelineSceneData.renderObjects;
                var instancedBuffer = InstancedBuffer.get(shadows.instancingMaterial.passes[0]);

                this._instancedQueue.queue.add(instancedBuffer);

                for (var i = 0; i < renderObjects.length; i++) {
                  var model = renderObjects[i].model;

                  if (!model.enabled || !model.node || !model.castShadow) {
                    continue;
                  }

                  if (model.worldBounds) {
                    AABB.transform(_ab, model.worldBounds, shadows.matLight);

                    if (!intersect.aabbFrustum(_ab, frustum)) {
                      continue;
                    }
                  }

                  if (model.isInstancingEnabled) {
                    var subModels = model.subModels;

                    for (var m = 0; m < subModels.length; m++) {
                      var subModel = subModels[m];
                      instancedBuffer.merge(subModel, model.instancedAttributes, 0, subModel.planarInstanceShaderHandle);
                    }
                  } else {
                    this._pendingModels.push(model);
                  }
                }

                this._instancedQueue.uploadBuffers(cmdBuff);
              };

              _proto.recordCommandBuffer = function recordCommandBuffer(device, renderPass, cmdBuff) {
                var shadows = this._pipeline.pipelineSceneData.shadows;

                if (!shadows.enabled || shadows.type !== ShadowType.Planar) {
                  return;
                }

                this._instancedQueue.recordCommandBuffer(device, renderPass, cmdBuff);

                if (!this._pendingModels.length) {
                  return;
                }

                var pass = shadows.material.passes[0];
                var descriptorSet = DSPool.get(PassPool.get(pass.handle, PassView.DESCRIPTOR_SET));
                cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, descriptorSet);
                var modelCount = this._pendingModels.length;

                for (var i = 0; i < modelCount; i++) {
                  var model = this._pendingModels[i];

                  for (var j = 0; j < model.subModels.length; j++) {
                    var subModel = model.subModels[j];
                    var shader = ShaderPool.get(subModel.planarShaderHandle);
                    var ia = subModel.inputAssembler;
                    var pso = PipelineStateManager.getOrCreatePipelineState(device, pass, shader, renderPass, ia);
                    cmdBuff.bindPipelineState(pso);
                    cmdBuff.bindDescriptorSet(SetIndex.LOCAL, subModel.descriptorSet);
                    cmdBuff.bindInputAssembler(ia);
                    cmdBuff.draw(ia);
                  }
                }
              };

              return PlanarShadowQueue;
            }();

            var UIPhase = function () {
              function UIPhase() {
                this._phaseID = getPhaseID('default');
              }

              var _proto = UIPhase.prototype;

              _proto.activate = function activate(pipeline) {
                this._pipeline = pipeline;
              };

              _proto.render = function render(camera, renderPass) {
                var pipeline = this._pipeline;
                var device = pipeline.device;
                var cmdBuff = pipeline.commandBuffers[0];
                var scene = camera.scene;
                var batches = scene.batches;

                for (var i = 0; i < batches.length; i++) {
                  var batch = batches[i];
                  var visible = false;

                  if (camera.visibility & batch.visFlags) {
                    visible = true;
                  }

                  if (!visible) continue;
                  var handle = batch.handle;
                  var count = BatchPool2D.get(handle, BatchView2D.PASS_COUNT);

                  for (var j = 0; j < count; j++) {
                    var pass = batch.passes[j];
                    if (pass.phase !== this._phaseID) continue;
                    var shaderHandle = BatchPool2D.get(handle, BatchView2D.SHADER_0 + j);
                    var shader = ShaderPool.get(shaderHandle);
                    var inputAssembler = IAPool.get(batch.hInputAssembler);
                    var ds = DSPool.get(batch.hDescriptorSet);
                    var pso = PipelineStateManager.getOrCreatePipelineState(device, pass, shader, renderPass, inputAssembler);
                    cmdBuff.bindPipelineState(pso);
                    cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet);
                    cmdBuff.bindDescriptorSet(SetIndex.LOCAL, ds);
                    cmdBuff.bindInputAssembler(inputAssembler);
                    cmdBuff.draw(inputAssembler);
                  }
                }
              };

              return UIPhase;
            }();

            var _dec$m, _dec2$d, _dec3$9, _class$m, _class2$l, _descriptor$j, _class3$a, _temp$l;
            var colors = [new Color$1(0, 0, 0, 1)];
            var ForwardStage = exports('ForwardStage', (_dec$m = ccclass('ForwardStage'), _dec2$d = type([RenderQueueDesc]), _dec3$9 = displayOrder(), _dec$m(_class$m = (_class2$l = (_temp$l = _class3$a = function (_RenderStage) {
              _inheritsLoose(ForwardStage, _RenderStage);

              function ForwardStage() {
                var _this;

                _this = _RenderStage.call(this) || this;

                _initializerDefineProperty(_this, "renderQueues", _descriptor$j, _assertThisInitialized(_this));

                _this._renderQueues = [];
                _this._renderArea = new Rect$1();
                _this._batchedQueue = void 0;
                _this._instancedQueue = void 0;
                _this._phaseID = getPhaseID('default');
                _this._clearFlag = 0xffffffff;
                _this._batchedQueue = new RenderBatchedQueue();
                _this._instancedQueue = new RenderInstancedQueue();
                _this._uiPhase = new UIPhase();
                return _this;
              }

              var _proto = ForwardStage.prototype;

              _proto.initialize = function initialize(info) {
                _RenderStage.prototype.initialize.call(this, info);

                if (info.renderQueues) {
                  this.renderQueues = info.renderQueues;
                }

                return true;
              };

              _proto.activate = function activate(pipeline, flow) {
                _RenderStage.prototype.activate.call(this, pipeline, flow);

                for (var i = 0; i < this.renderQueues.length; i++) {
                  this._renderQueues[i] = convertRenderQueue(this.renderQueues[i]);
                }

                this._additiveLightQueue = new RenderAdditiveLightQueue(this._pipeline);
                this._planarQueue = new PlanarShadowQueue(this._pipeline);

                this._uiPhase.activate(pipeline);
              };

              _proto.destroy = function destroy() {};

              _proto.render = function render(camera) {
                this._instancedQueue.clear();

                this._batchedQueue.clear();

                var pipeline = this._pipeline;
                var device = pipeline.device;

                this._renderQueues.forEach(renderQueueClearFunc);

                var renderObjects = pipeline.pipelineSceneData.renderObjects;
                var m = 0;
                var p = 0;
                var k = 0;

                for (var i = 0; i < renderObjects.length; ++i) {
                  var ro = renderObjects[i];
                  var subModels = ro.model.subModels;

                  for (m = 0; m < subModels.length; ++m) {
                    var subModel = subModels[m];
                    var passes = subModel.passes;

                    for (p = 0; p < passes.length; ++p) {
                      var pass = passes[p];
                      if (pass.phase !== this._phaseID) continue;
                      var batchingScheme = pass.batchingScheme;

                      if (batchingScheme === BatchingSchemes.INSTANCING) {
                        var instancedBuffer = InstancedBuffer.get(pass);
                        instancedBuffer.merge(subModel, ro.model.instancedAttributes, p);

                        this._instancedQueue.queue.add(instancedBuffer);
                      } else if (batchingScheme === BatchingSchemes.VB_MERGING) {
                        var batchedBuffer = BatchedBuffer.get(pass);
                        batchedBuffer.merge(subModel, p, ro.model);

                        this._batchedQueue.queue.add(batchedBuffer);
                      } else {
                        for (k = 0; k < this._renderQueues.length; k++) {
                          this._renderQueues[k].insertRenderPass(ro, m, p);
                        }
                      }
                    }
                  }
                }

                this._renderQueues.forEach(renderQueueSortFunc);

                var cmdBuff = pipeline.commandBuffers[0];

                this._instancedQueue.uploadBuffers(cmdBuff);

                this._batchedQueue.uploadBuffers(cmdBuff);

                this._additiveLightQueue.gatherLightPasses(camera, cmdBuff);

                this._planarQueue.gatherShadowPasses(camera, cmdBuff);

                var sceneData = pipeline.pipelineSceneData;
                this._renderArea = pipeline.generateRenderArea(camera);

                if (camera.clearFlag & ClearFlagBit.COLOR) {
                  if (sceneData.isHDR) {
                    SRGBToLinear(colors[0], camera.clearColor);
                    var scale = sceneData.fpScale / camera.exposure;
                    colors[0].x *= scale;
                    colors[0].y *= scale;
                    colors[0].z *= scale;
                  } else {
                    colors[0].x = camera.clearColor.x;
                    colors[0].y = camera.clearColor.y;
                    colors[0].z = camera.clearColor.z;
                  }
                }

                colors[0].w = camera.clearColor.w;
                var framebuffer = camera.window.framebuffer;
                var renderPass = framebuffer.colorTextures[0] ? framebuffer.renderPass : pipeline.getRenderPass(camera.clearFlag & this._clearFlag);
                cmdBuff.beginRenderPass(renderPass, framebuffer, this._renderArea, colors, camera.clearDepth, camera.clearStencil);
                cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet);

                this._renderQueues[0].recordCommandBuffer(device, renderPass, cmdBuff);

                this._instancedQueue.recordCommandBuffer(device, renderPass, cmdBuff);

                this._batchedQueue.recordCommandBuffer(device, renderPass, cmdBuff);

                this._additiveLightQueue.recordCommandBuffer(device, renderPass, cmdBuff);

                this._planarQueue.recordCommandBuffer(device, renderPass, cmdBuff);

                this._renderQueues[1].recordCommandBuffer(device, renderPass, cmdBuff);

                this._uiPhase.render(camera, renderPass);

                cmdBuff.endRenderPass();
              };

              return ForwardStage;
            }(RenderStage), _class3$a.initInfo = {
              name: 'ForwardStage',
              priority: ForwardStagePriority.FORWARD,
              tag: 0,
              renderQueues: [{
                isTransparent: false,
                sortMode: RenderQueueSortMode.FRONT_TO_BACK,
                stages: ['default']
              }, {
                isTransparent: true,
                sortMode: RenderQueueSortMode.BACK_TO_FRONT,
                stages: ['default', 'planarShadow']
              }]
            }, _temp$l), (_descriptor$j = _applyDecoratedDescriptor(_class2$l.prototype, "renderQueues", [_dec2$d, serializable, _dec3$9], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            })), _class2$l)) || _class$m));

            var _dec$n, _class$n, _class2$m, _temp$m;
            var ForwardFlow = exports('ForwardFlow', (_dec$n = ccclass('ForwardFlow'), _dec$n(_class$n = (_temp$m = _class2$m = function (_RenderFlow) {
              _inheritsLoose(ForwardFlow, _RenderFlow);

              function ForwardFlow() {
                return _RenderFlow.apply(this, arguments) || this;
              }

              var _proto = ForwardFlow.prototype;

              _proto.initialize = function initialize(info) {
                _RenderFlow.prototype.initialize.call(this, info);

                if (this._stages.length === 0) {
                  var forwardStage = new ForwardStage();
                  forwardStage.initialize(ForwardStage.initInfo);

                  this._stages.push(forwardStage);
                }

                return true;
              };

              _proto.activate = function activate(pipeline) {
                _RenderFlow.prototype.activate.call(this, pipeline);
              };

              _proto.render = function render(camera) {
                _RenderFlow.prototype.render.call(this, camera);
              };

              _proto.destroy = function destroy() {
                _RenderFlow.prototype.destroy.call(this);
              };

              return ForwardFlow;
            }(RenderFlow), _class2$m.initInfo = {
              name: PIPELINE_FLOW_FORWARD,
              priority: ForwardFlowPriority.FORWARD,
              stages: []
            }, _temp$m)) || _class$n));

            var _phaseID$1 = getPhaseID('shadow-caster');

            var _shadowPassIndices = [];

            function getShadowPassIndex(subModels, shadowPassIndices) {
              shadowPassIndices.length = 0;
              var hasShadowPass = false;

              for (var j = 0; j < subModels.length; j++) {
                var passes = subModels[j].passes;
                var shadowPassIndex = -1;

                for (var k = 0; k < passes.length; k++) {
                  if (passes[k].phase === _phaseID$1) {
                    shadowPassIndex = k;
                    hasShadowPass = true;
                    break;
                  }
                }

                shadowPassIndices.push(shadowPassIndex);
              }

              return hasShadowPass;
            }

            var RenderShadowMapBatchedQueue = function () {
              function RenderShadowMapBatchedQueue(pipeline) {
                this._pipeline = void 0;
                this._subModelsArray = [];
                this._passArray = [];
                this._shaderArray = [];
                this._instancedQueue = void 0;
                this._batchedQueue = void 0;
                this._pipeline = pipeline;
                this._instancedQueue = new RenderInstancedQueue();
                this._batchedQueue = new RenderBatchedQueue();
              }

              var _proto = RenderShadowMapBatchedQueue.prototype;

              _proto.gatherLightPasses = function gatherLightPasses(light, cmdBuff) {
                this.clear();
                var shadowInfo = this._pipeline.pipelineSceneData.shadows;
                var shadowObjects = this._pipeline.pipelineSceneData.shadowObjects;

                if (light && shadowInfo.enabled && shadowInfo.type === ShadowType.ShadowMap) {
                  this._pipeline.pipelineUBO.updateShadowUBOLight(light);

                  for (var i = 0; i < shadowObjects.length; i++) {
                    var ro = shadowObjects[i];
                    var model = ro.model;

                    if (!getShadowPassIndex(model.subModels, _shadowPassIndices)) {
                      continue;
                    }

                    switch (light.type) {
                      case LightType.DIRECTIONAL:
                        this.add(model, cmdBuff, _shadowPassIndices);
                        break;

                      case LightType.SPOT:
                        if (model.worldBounds && (!intersect.aabbWithAABB(model.worldBounds, light.aabb) || !intersect.aabbFrustum(model.worldBounds, light.frustum))) continue;
                        this.add(model, cmdBuff, _shadowPassIndices);
                        break;
                    }
                  }
                }
              };

              _proto.clear = function clear() {
                this._subModelsArray.length = 0;
                this._shaderArray.length = 0;
                this._passArray.length = 0;

                this._instancedQueue.clear();

                this._batchedQueue.clear();
              };

              _proto.add = function add(model, cmdBuff, _shadowPassIndices) {
                var subModels = model.subModels;

                for (var j = 0; j < subModels.length; j++) {
                  var subModel = subModels[j];
                  var shadowPassIdx = _shadowPassIndices[j];
                  var pass = subModel.passes[shadowPassIdx];
                  var batchingScheme = pass.batchingScheme;

                  if (batchingScheme === BatchingSchemes.INSTANCING) {
                    var buffer = InstancedBuffer.get(pass);
                    buffer.merge(subModel, model.instancedAttributes, shadowPassIdx);

                    this._instancedQueue.queue.add(buffer);
                  } else if (pass.batchingScheme === BatchingSchemes.VB_MERGING) {
                    var _buffer = BatchedBuffer.get(pass);

                    _buffer.merge(subModel, shadowPassIdx, model);

                    this._batchedQueue.queue.add(_buffer);
                  } else {
                    var shader = ShaderPool.get(SubModelPool.get(subModel.handle, SubModelView.SHADER_0 + shadowPassIdx));

                    this._subModelsArray.push(subModel);

                    this._shaderArray.push(shader);

                    this._passArray.push(pass);
                  }
                }

                this._instancedQueue.uploadBuffers(cmdBuff);

                this._batchedQueue.uploadBuffers(cmdBuff);
              };

              _proto.recordCommandBuffer = function recordCommandBuffer(device, renderPass, cmdBuff) {
                this._instancedQueue.recordCommandBuffer(device, renderPass, cmdBuff);

                this._batchedQueue.recordCommandBuffer(device, renderPass, cmdBuff);

                for (var i = 0; i < this._subModelsArray.length; ++i) {
                  var subModel = this._subModelsArray[i];
                  var shader = this._shaderArray[i];
                  var pass = this._passArray[i];
                  var ia = subModel.inputAssembler;
                  var pso = PipelineStateManager.getOrCreatePipelineState(device, pass, shader, renderPass, ia);
                  var descriptorSet = pass.descriptorSet;
                  cmdBuff.bindPipelineState(pso);
                  cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, descriptorSet);
                  cmdBuff.bindDescriptorSet(SetIndex.LOCAL, subModel.descriptorSet);
                  cmdBuff.bindInputAssembler(ia);
                  cmdBuff.draw(ia);
                }
              };

              return RenderShadowMapBatchedQueue;
            }();

            var _dec$o, _class$o, _class2$n, _temp$n;
            var colors$1 = [new Color$1(1, 1, 1, 1)];
            var ShadowStage = exports('ShadowStage', (_dec$o = ccclass('ShadowStage'), _dec$o(_class$o = (_temp$n = _class2$n = function (_RenderStage) {
              _inheritsLoose(ShadowStage, _RenderStage);

              function ShadowStage() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _RenderStage.call.apply(_RenderStage, [this].concat(args)) || this;
                _this._shadowFrameBuffer = null;
                _this._renderArea = new Rect$1();
                _this._light = null;
                return _this;
              }

              var _proto = ShadowStage.prototype;

              _proto.setUsage = function setUsage(light, shadowFrameBuffer) {
                this._light = light;
                this._shadowFrameBuffer = shadowFrameBuffer;
              };

              _proto.destroy = function destroy() {
                this._additiveShadowQueue.clear();
              };

              _proto.clearFramebuffer = function clearFramebuffer(camera) {
                if (!this._light || !this._shadowFrameBuffer) {
                  return;
                }

                colors$1[0].w = camera.clearColor.w;
                var pipeline = this._pipeline;
                var cmdBuff = pipeline.commandBuffers[0];
                var renderPass = this._shadowFrameBuffer.renderPass;
                cmdBuff.beginRenderPass(renderPass, this._shadowFrameBuffer, this._renderArea, colors$1, camera.clearDepth, camera.clearStencil);
                cmdBuff.endRenderPass();
              };

              _proto.render = function render(camera) {
                var pipeline = this._pipeline;
                var pipelineSceneData = pipeline.pipelineSceneData;
                var shadowInfo = pipelineSceneData.shadows;
                var shadingScale = pipelineSceneData.shadingScale;
                var cmdBuff = pipeline.commandBuffers[0];

                if (!this._light || !this._shadowFrameBuffer) {
                  return;
                }

                this._additiveShadowQueue.gatherLightPasses(this._light, cmdBuff);

                var vp = camera.viewport;
                var shadowMapSize = shadowInfo.size;
                this._renderArea.x = vp.x * shadowMapSize.x;
                this._renderArea.y = vp.y * shadowMapSize.y;
                this._renderArea.width = vp.width * shadowMapSize.x * shadingScale;
                this._renderArea.height = vp.height * shadowMapSize.y * shadingScale;
                var device = pipeline.device;
                var renderPass = this._shadowFrameBuffer.renderPass;
                cmdBuff.beginRenderPass(renderPass, this._shadowFrameBuffer, this._renderArea, colors$1, camera.clearDepth, camera.clearStencil);
                cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet);

                this._additiveShadowQueue.recordCommandBuffer(device, renderPass, cmdBuff);

                cmdBuff.endRenderPass();
              };

              _proto.activate = function activate(pipeline, flow) {
                _RenderStage.prototype.activate.call(this, pipeline, flow);

                this._additiveShadowQueue = new RenderShadowMapBatchedQueue(pipeline);
              };

              return ShadowStage;
            }(RenderStage), _class2$n.initInfo = {
              name: 'ShadowStage',
              priority: ForwardStagePriority.FORWARD,
              tag: 0
            }, _temp$n)) || _class$o));

            var _dec$p, _class$p, _class2$o, _temp$o;
            var ShadowFlow = exports('ShadowFlow', (_dec$p = ccclass('ShadowFlow'), _dec$p(_class$p = (_temp$o = _class2$o = function (_RenderFlow) {
              _inheritsLoose(ShadowFlow, _RenderFlow);

              function ShadowFlow() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _RenderFlow.call.apply(_RenderFlow, [this].concat(args)) || this;
                _this._shadowRenderPass = null;
                return _this;
              }

              var _proto = ShadowFlow.prototype;

              _proto.initialize = function initialize(info) {
                _RenderFlow.prototype.initialize.call(this, info);

                if (this._stages.length === 0) {
                  var shadowMapStage = new ShadowStage();
                  shadowMapStage.initialize(ShadowStage.initInfo);

                  this._stages.push(shadowMapStage);
                }

                return true;
              };

              _proto.render = function render(camera) {
                var pipeline = this._pipeline;
                var shadowInfo = pipeline.pipelineSceneData.shadows;
                var shadowFrameBufferMap = pipeline.pipelineSceneData.shadowFrameBufferMap;
                var shadowObjects = pipeline.pipelineSceneData.shadowObjects;

                if (!shadowInfo.enabled || shadowInfo.type !== ShadowType.ShadowMap) {
                  return;
                }

                var validLights = lightCollecting(camera, shadowInfo.maxReceived);

                if (shadowObjects.length === 0) {
                  this.clearShadowMap(validLights, camera);
                  return;
                }

                for (var l = 0; l < validLights.length; l++) {
                  var light = validLights[l];

                  if (!shadowFrameBufferMap.has(light)) {
                    this._initShadowFrameBuffer(pipeline, light);
                  }

                  var shadowFrameBuffer = shadowFrameBufferMap.get(light);

                  if (shadowInfo.shadowMapDirty) {
                    this.resizeShadowMap(light, shadowInfo);
                  }

                  for (var i = 0; i < this._stages.length; i++) {
                    var shadowStage = this._stages[i];
                    shadowStage.setUsage(light, shadowFrameBuffer);
                    shadowStage.render(camera);
                  }
                }

                pipeline.pipelineUBO.updateShadowUBO(camera);
              };

              _proto.destroy = function destroy() {
                _RenderFlow.prototype.destroy.call(this);

                var shadowFrameBufferMap = this._pipeline.pipelineSceneData.shadowFrameBufferMap;
                var shadowFrameBuffers = Array.from(shadowFrameBufferMap.values());

                for (var i = 0; i < shadowFrameBuffers.length; i++) {
                  var frameBuffer = shadowFrameBuffers[i];

                  if (!frameBuffer) {
                    continue;
                  }

                  var renderTargets = frameBuffer.colorTextures;

                  for (var j = 0; j < renderTargets.length; j++) {
                    var renderTarget = renderTargets[i];

                    if (renderTarget) {
                      renderTarget.destroy();
                    }
                  }

                  renderTargets.length = 0;
                  var depth = frameBuffer.depthStencilTexture;

                  if (depth) {
                    depth.destroy();
                  }

                  frameBuffer.destroy();
                }

                shadowFrameBufferMap.clear();

                if (this._shadowRenderPass) {
                  this._shadowRenderPass.destroy();
                }
              };

              _proto._initShadowFrameBuffer = function _initShadowFrameBuffer(pipeline, light) {
                var device = pipeline.device;
                var shadows = pipeline.pipelineSceneData.shadows;
                var shadowMapSize = shadows.size;
                var shadowFrameBufferMap = pipeline.pipelineSceneData.shadowFrameBufferMap;
                var format = supportsHalfFloatTexture(device) ? shadows.packing ? Format.RGBA8 : Format.RGBA16F : Format.RGBA8;

                if (!this._shadowRenderPass) {
                  var colorAttachment = new ColorAttachment();
                  colorAttachment.format = format;
                  colorAttachment.loadOp = LoadOp.CLEAR;
                  colorAttachment.storeOp = StoreOp.STORE;
                  colorAttachment.sampleCount = 1;
                  var depthStencilAttachment = new DepthStencilAttachment();
                  depthStencilAttachment.format = device.depthStencilFormat;
                  depthStencilAttachment.depthLoadOp = LoadOp.CLEAR;
                  depthStencilAttachment.depthStoreOp = StoreOp.DISCARD;
                  depthStencilAttachment.stencilLoadOp = LoadOp.CLEAR;
                  depthStencilAttachment.stencilStoreOp = StoreOp.DISCARD;
                  depthStencilAttachment.sampleCount = 1;
                  var renderPassInfo = new RenderPassInfo([colorAttachment], depthStencilAttachment);
                  this._shadowRenderPass = device.createRenderPass(renderPassInfo);
                }

                var shadowRenderTargets = [];
                shadowRenderTargets.push(device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.COLOR_ATTACHMENT | TextureUsageBit.SAMPLED, format, shadowMapSize.x, shadowMapSize.y)));
                var depth = device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.DEPTH_STENCIL_ATTACHMENT, device.depthStencilFormat, shadowMapSize.x, shadowMapSize.y));
                var shadowFrameBuffer = device.createFramebuffer(new FramebufferInfo(this._shadowRenderPass, shadowRenderTargets, depth));
                shadowFrameBufferMap.set(light, shadowFrameBuffer);
              };

              _proto.clearShadowMap = function clearShadowMap(validLights, camera) {
                var scene = this._pipeline.pipelineSceneData;

                for (var l = 0; l < validLights.length; l++) {
                  var light = validLights[l];
                  var shadowFrameBuffer = scene.shadowFrameBufferMap.get(light);

                  if (!scene.shadowFrameBufferMap.has(light)) {
                    continue;
                  }

                  for (var i = 0; i < this._stages.length; i++) {
                    var shadowStage = this._stages[i];
                    shadowStage.setUsage(light, shadowFrameBuffer);
                    shadowStage.clearFramebuffer(camera);
                  }
                }
              };

              _proto.resizeShadowMap = function resizeShadowMap(light, shadowInfo) {
                var width = shadowInfo.size.x;
                var height = shadowInfo.size.y;
                var pipeline = this._pipeline;
                var device = pipeline.device;
                var shadowFrameBufferMap = pipeline.pipelineSceneData.shadowFrameBufferMap;
                var format = supportsHalfFloatTexture(device) ? shadowInfo.packing ? Format.RGBA8 : Format.RGBA16F : Format.RGBA8;

                if (shadowFrameBufferMap.has(light)) {
                  var frameBuffer = shadowFrameBufferMap.get(light);

                  if (!frameBuffer) {
                    return;
                  }

                  var renderTargets = [];
                  renderTargets.push(pipeline.device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.COLOR_ATTACHMENT | TextureUsageBit.SAMPLED, format, width, height)));
                  var depth = frameBuffer.depthStencilTexture;

                  if (depth) {
                    depth.resize(width, height);
                  }

                  var shadowRenderPass = frameBuffer.renderPass;
                  frameBuffer.destroy();
                  frameBuffer.initialize(new FramebufferInfo(shadowRenderPass, renderTargets, depth));
                }

                shadowInfo.shadowMapDirty = false;
              };

              return ShadowFlow;
            }(RenderFlow), _class2$o.initInfo = {
              name: PIPELINE_FLOW_SHADOW,
              priority: ForwardFlowPriority.SHADOW,
              tag: RenderFlowTag.SCENE,
              stages: []
            }, _temp$o)) || _class$p));

            var _dec$q, _dec2$e, _dec3$a, _dec4$7, _dec5$4, _class$q, _class2$p, _descriptor$k, _descriptor2$e, _temp$p;
            var _samplerInfo$1 = [Filter.POINT, Filter.POINT, Filter.NONE, Address.CLAMP, Address.CLAMP, Address.CLAMP];
            var ForwardPipeline = exports('ForwardPipeline', (_dec$q = ccclass('ForwardPipeline'), _dec2$e = type([RenderTextureConfig]), _dec3$a = displayOrder(), _dec4$7 = type([MaterialConfig]), _dec5$4 = displayOrder(), _dec$q(_class$q = (_class2$p = (_temp$p = function (_RenderPipeline) {
              _inheritsLoose(ForwardPipeline, _RenderPipeline);

              function ForwardPipeline() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _RenderPipeline.call.apply(_RenderPipeline, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "renderTextures", _descriptor$k, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "materials", _descriptor2$e, _assertThisInitialized(_this));

                _this._renderPasses = new Map();
                return _this;
              }

              var _proto = ForwardPipeline.prototype;

              _proto.initialize = function initialize(info) {
                _RenderPipeline.prototype.initialize.call(this, info);

                if (this._flows.length === 0) {
                  var shadowFlow = new ShadowFlow();
                  shadowFlow.initialize(ShadowFlow.initInfo);

                  this._flows.push(shadowFlow);

                  var forwardFlow = new ForwardFlow();
                  forwardFlow.initialize(ForwardFlow.initInfo);

                  this._flows.push(forwardFlow);
                }

                return true;
              };

              _proto.activate = function activate() {
                if (!_RenderPipeline.prototype.activate.call(this)) {
                  return false;
                }

                if (!this._activeRenderer()) {
                  errorID(2402);
                  return false;
                }

                return true;
              };

              _proto.render = function render(cameras) {
                this._commandBuffers[0].begin();

                this._pipelineUBO.updateGlobalUBO();

                for (var i = 0; i < cameras.length; i++) {
                  var camera = cameras[i];

                  if (camera.scene) {
                    sceneCulling(this, camera);

                    this._pipelineUBO.updateCameraUBO(camera);

                    for (var j = 0; j < this._flows.length; j++) {
                      this._flows[j].render(camera);
                    }
                  }
                }

                this._commandBuffers[0].end();

                this._device.flushCommands(this._commandBuffers);

                this._device.queue.submit(this._commandBuffers);
              };

              _proto.getRenderPass = function getRenderPass(clearFlags) {
                var renderPass = this._renderPasses.get(clearFlags);

                if (renderPass) {
                  return renderPass;
                }

                var device = this.device;
                var colorAttachment = new ColorAttachment();
                var depthStencilAttachment = new DepthStencilAttachment();
                colorAttachment.format = device.colorFormat;
                depthStencilAttachment.format = device.depthStencilFormat;
                depthStencilAttachment.stencilStoreOp = StoreOp.DISCARD;
                depthStencilAttachment.depthStoreOp = StoreOp.DISCARD;

                if (!(clearFlags & ClearFlagBit.COLOR)) {
                  if (clearFlags & SKYBOX_FLAG) {
                    colorAttachment.loadOp = LoadOp.DISCARD;
                  } else {
                    colorAttachment.loadOp = LoadOp.LOAD;
                    colorAttachment.beginAccesses = [AccessType.PRESENT];
                  }
                }

                if ((clearFlags & ClearFlagBit.DEPTH_STENCIL) !== ClearFlagBit.DEPTH_STENCIL) {
                  if (!(clearFlags & ClearFlagBit.DEPTH)) depthStencilAttachment.depthLoadOp = LoadOp.LOAD;
                  if (!(clearFlags & ClearFlagBit.STENCIL)) depthStencilAttachment.stencilLoadOp = LoadOp.LOAD;
                  depthStencilAttachment.beginAccesses = [AccessType.DEPTH_STENCIL_ATTACHMENT_WRITE];
                }

                var renderPassInfo = new RenderPassInfo([colorAttachment], depthStencilAttachment);
                renderPass = device.createRenderPass(renderPassInfo);

                this._renderPasses.set(clearFlags, renderPass);

                return renderPass;
              };

              _proto._activeRenderer = function _activeRenderer() {
                var device = this.device;

                this._commandBuffers.push(device.commandBuffer);

                var shadowMapSamplerHash = genSamplerHash(_samplerInfo$1);
                var shadowMapSampler = samplerLib.getSampler(device, shadowMapSamplerHash);

                this._descriptorSet.bindSampler(UNIFORM_SHADOWMAP_BINDING, shadowMapSampler);

                this._descriptorSet.bindTexture(UNIFORM_SHADOWMAP_BINDING, builtinResMgr.get('default-texture').getGFXTexture());

                this._descriptorSet.bindSampler(UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING, shadowMapSampler);

                this._descriptorSet.bindTexture(UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING, builtinResMgr.get('default-texture').getGFXTexture());

                this._descriptorSet.update();

                return true;
              };

              _proto.destroyUBOs = function destroyUBOs() {
                if (this._descriptorSet) {
                  this._descriptorSet.getBuffer(UBOGlobal.BINDING).destroy();

                  this._descriptorSet.getBuffer(UBOShadow.BINDING).destroy();

                  this._descriptorSet.getBuffer(UBOCamera.BINDING).destroy();

                  this._descriptorSet.getSampler(UNIFORM_SHADOWMAP_BINDING).destroy();

                  this._descriptorSet.getSampler(UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING).destroy();

                  this._descriptorSet.getTexture(UNIFORM_SHADOWMAP_BINDING).destroy();

                  this._descriptorSet.getTexture(UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING).destroy();
                }
              };

              _proto.destroy = function destroy() {
                this.destroyUBOs();

                var rpIter = this._renderPasses.values();

                var rpRes = rpIter.next();

                while (!rpRes.done) {
                  rpRes.value.destroy();
                  rpRes = rpIter.next();
                }

                this._commandBuffers.length = 0;
                return _RenderPipeline.prototype.destroy.call(this);
              };

              return ForwardPipeline;
            }(RenderPipeline), _temp$p), (_descriptor$k = _applyDecoratedDescriptor(_class2$p.prototype, "renderTextures", [_dec2$e, serializable, _dec3$a], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor2$e = _applyDecoratedDescriptor(_class2$p.prototype, "materials", [_dec4$7, serializable, _dec5$4], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            })), _class2$p)) || _class$q));

            var DeferredStagePriority;

            (function (DeferredStagePriority) {
              DeferredStagePriority[DeferredStagePriority["GBUFFER"] = 10] = "GBUFFER";
              DeferredStagePriority[DeferredStagePriority["LIGHTING"] = 15] = "LIGHTING";
              DeferredStagePriority[DeferredStagePriority["TRANSPARENT"] = 18] = "TRANSPARENT";
              DeferredStagePriority[DeferredStagePriority["POSTPROCESS"] = 19] = "POSTPROCESS";
              DeferredStagePriority[DeferredStagePriority["UI"] = 20] = "UI";
            })(DeferredStagePriority || (DeferredStagePriority = {}));

            var DeferredFlowPriority;

            (function (DeferredFlowPriority) {
              DeferredFlowPriority[DeferredFlowPriority["SHADOW"] = 0] = "SHADOW";
              DeferredFlowPriority[DeferredFlowPriority["GBUFFER"] = 1] = "GBUFFER";
              DeferredFlowPriority[DeferredFlowPriority["LIGHTING"] = 5] = "LIGHTING";
              DeferredFlowPriority[DeferredFlowPriority["UI"] = 10] = "UI";
            })(DeferredFlowPriority || (DeferredFlowPriority = {}));

            var _dec$r, _dec2$f, _dec3$b, _class$r, _class2$q, _descriptor$l, _class3$b, _temp$q;
            var colors$2 = [new Color$1(0, 0, 0, 0), new Color$1(0, 0, 0, 0), new Color$1(0, 0, 0, 0), new Color$1(0, 0, 0, 0)];
            var GbufferStage = exports('GbufferStage', (_dec$r = ccclass('GbufferStage'), _dec2$f = type([RenderQueueDesc]), _dec3$b = displayOrder(), _dec$r(_class$r = (_class2$q = (_temp$q = _class3$b = function (_RenderStage) {
              _inheritsLoose(GbufferStage, _RenderStage);

              function GbufferStage() {
                var _this;

                _this = _RenderStage.call(this) || this;

                _initializerDefineProperty(_this, "renderQueues", _descriptor$l, _assertThisInitialized(_this));

                _this._renderQueues = [];
                _this._renderArea = new Rect$1();
                _this._batchedQueue = void 0;
                _this._instancedQueue = void 0;
                _this._phaseID = getPhaseID('deferred');
                _this._batchedQueue = new RenderBatchedQueue();
                _this._instancedQueue = new RenderInstancedQueue();
                return _this;
              }

              var _proto = GbufferStage.prototype;

              _proto.initialize = function initialize(info) {
                _RenderStage.prototype.initialize.call(this, info);

                if (info.renderQueues) {
                  this.renderQueues = info.renderQueues;
                }

                return true;
              };

              _proto.activate = function activate(pipeline, flow) {
                _RenderStage.prototype.activate.call(this, pipeline, flow);

                for (var i = 0; i < this.renderQueues.length; i++) {
                  this._renderQueues[i] = convertRenderQueue(this.renderQueues[i]);
                }
              };

              _proto.destroy = function destroy() {};

              _proto.render = function render(camera) {
                this._instancedQueue.clear();

                this._batchedQueue.clear();

                var pipeline = this._pipeline;
                var device = pipeline.device;

                this._renderQueues.forEach(renderQueueClearFunc);

                var renderObjects = pipeline.pipelineSceneData.renderObjects;

                if (renderObjects.length === 0) {
                  return;
                }

                var m = 0;
                var p = 0;
                var k = 0;

                for (var i = 0; i < renderObjects.length; ++i) {
                  var ro = renderObjects[i];
                  var subModels = ro.model.subModels;

                  for (m = 0; m < subModels.length; ++m) {
                    var subModel = subModels[m];
                    var passes = subModel.passes;

                    for (p = 0; p < passes.length; ++p) {
                      var pass = passes[p];
                      if (pass.phase !== this._phaseID) continue;
                      var batchingScheme = pass.batchingScheme;

                      if (batchingScheme === BatchingSchemes.INSTANCING) {
                        var instancedBuffer = InstancedBuffer.get(pass);
                        instancedBuffer.merge(subModel, ro.model.instancedAttributes, p);

                        this._instancedQueue.queue.add(instancedBuffer);
                      } else if (batchingScheme === BatchingSchemes.VB_MERGING) {
                        var batchedBuffer = BatchedBuffer.get(pass);
                        batchedBuffer.merge(subModel, p, ro.model);

                        this._batchedQueue.queue.add(batchedBuffer);
                      } else {
                        for (k = 0; k < this._renderQueues.length; k++) {
                          this._renderQueues[k].insertRenderPass(ro, m, p);
                        }
                      }
                    }
                  }
                }

                this._renderQueues.forEach(renderQueueSortFunc);

                var cmdBuff = pipeline.commandBuffers[0];

                this._instancedQueue.uploadBuffers(cmdBuff);

                this._batchedQueue.uploadBuffers(cmdBuff);

                this._renderArea = pipeline.generateRenderArea(camera);
                pipeline.updateQuadVertexData(this._renderArea);

                if (camera.clearFlag & ClearFlagBit.COLOR) {
                  if (pipeline.pipelineSceneData.isHDR) {
                    SRGBToLinear(colors$2[0], camera.clearColor);
                    var scale = pipeline.pipelineSceneData.fpScale / camera.exposure;
                    colors$2[0].x *= scale;
                    colors$2[0].y *= scale;
                    colors$2[0].z *= scale;
                  } else {
                    colors$2[0].x = camera.clearColor.x;
                    colors$2[0].y = camera.clearColor.y;
                    colors$2[0].z = camera.clearColor.z;
                  }
                }

                colors$2[0].w = camera.clearColor.w;
                var deferredData = pipeline.getDeferredRenderData(camera);
                var framebuffer = deferredData.gbufferFrameBuffer;
                var renderPass = framebuffer.renderPass;
                cmdBuff.beginRenderPass(renderPass, framebuffer, this._renderArea, colors$2, camera.clearDepth, camera.clearStencil);
                cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet);

                for (var _i = 0; _i < this.renderQueues.length; _i++) {
                  this._renderQueues[_i].recordCommandBuffer(device, renderPass, cmdBuff);
                }

                this._instancedQueue.recordCommandBuffer(device, renderPass, cmdBuff);

                this._batchedQueue.recordCommandBuffer(device, renderPass, cmdBuff);

                cmdBuff.endRenderPass();
              };

              return GbufferStage;
            }(RenderStage), _class3$b.initInfo = {
              name: 'GbufferStage',
              priority: DeferredStagePriority.GBUFFER,
              tag: 0,
              renderQueues: [{
                isTransparent: false,
                sortMode: RenderQueueSortMode.FRONT_TO_BACK,
                stages: ['default']
              }, {
                isTransparent: true,
                sortMode: RenderQueueSortMode.BACK_TO_FRONT,
                stages: ['default']
              }]
            }, _temp$q), (_descriptor$l = _applyDecoratedDescriptor(_class2$q.prototype, "renderQueues", [_dec2$f, serializable, _dec3$b], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            })), _class2$q)) || _class$r));

            var _dec$s, _class$s, _class2$r, _temp$r;
            var GbufferFlow = exports('GbufferFlow', (_dec$s = ccclass('GbufferFlow'), _dec$s(_class$s = (_temp$r = _class2$r = function (_RenderFlow) {
              _inheritsLoose(GbufferFlow, _RenderFlow);

              function GbufferFlow() {
                return _RenderFlow.apply(this, arguments) || this;
              }

              var _proto = GbufferFlow.prototype;

              _proto.initialize = function initialize(info) {
                _RenderFlow.prototype.initialize.call(this, info);

                if (this._stages.length === 0) {
                  var gbufferStage = new GbufferStage();
                  gbufferStage.initialize(GbufferStage.initInfo);

                  this._stages.push(gbufferStage);
                }

                return true;
              };

              _proto.activate = function activate(pipeline) {
                _RenderFlow.prototype.activate.call(this, pipeline);
              };

              _proto.render = function render(camera) {
                _RenderFlow.prototype.render.call(this, camera);
              };

              _proto.destroy = function destroy() {
                _RenderFlow.prototype.destroy.call(this);
              };

              return GbufferFlow;
            }(RenderFlow), _class2$r.initInfo = {
              name: PIPELINE_FLOW_GBUFFER,
              priority: DeferredFlowPriority.GBUFFER,
              stages: []
            }, _temp$r)) || _class$s));

            var _dec$t, _dec2$g, _dec3$c, _dec4$8, _dec5$5, _class$t, _class2$s, _descriptor$m, _descriptor2$f, _class3$c, _temp$s;
            var colors$3 = [new Color$1(0, 0, 0, 1)];
            var LIGHTINGPASS_INDEX = 1;
            var LightingStage = exports('LightingStage', (_dec$t = ccclass('LightingStage'), _dec2$g = type(Material), _dec3$c = displayOrder(), _dec4$8 = type([RenderQueueDesc]), _dec5$5 = displayOrder(), _dec$t(_class$t = (_class2$s = (_temp$s = _class3$c = function (_RenderStage) {
              _inheritsLoose(LightingStage, _RenderStage);

              function LightingStage() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _RenderStage.call.apply(_RenderStage, [this].concat(args)) || this;
                _this._deferredLitsBufs = null;
                _this._maxDeferredLights = UBODeferredLight.LIGHTS_PER_PASS;
                _this._lightMeterScale = 10000.0;
                _this._descriptorSet = null;
                _this._renderArea = new Rect$1();

                _initializerDefineProperty(_this, "_deferredMaterial", _descriptor$m, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "renderQueues", _descriptor2$f, _assertThisInitialized(_this));

                _this._phaseID = getPhaseID('default');
                _this._defPhaseID = getPhaseID('deferred');
                _this._renderQueues = [];
                return _this;
              }

              var _proto = LightingStage.prototype;

              _proto.initialize = function initialize(info) {
                _RenderStage.prototype.initialize.call(this, info);

                return true;
              };

              _proto.gatherLights = function gatherLights(camera) {
                var pipeline = this._pipeline;
                var cmdBuff = pipeline.commandBuffers[0];
                var sphereLights = camera.scene.sphereLights;
                var spotLights = camera.scene.spotLights;

                var _sphere = Sphere.create(0, 0, 0, 1);

                var _vec4Array = new Float32Array(4);

                var exposure = camera.exposure;
                var idx = 0;
                var elementLen = Vec4.length;
                var fieldLen = elementLen * this._maxDeferredLights;

                for (var i = 0; i < sphereLights.length && idx < this._maxDeferredLights; i++, ++idx) {
                  var light = sphereLights[i];
                  Sphere.set(_sphere, light.position.x, light.position.y, light.position.z, light.range);

                  if (intersect.sphereFrustum(_sphere, camera.frustum)) {
                    Vec3.toArray(_vec4Array, light.position);
                    _vec4Array[3] = 0;

                    this._lightBufferData.set(_vec4Array, idx * elementLen);

                    Vec3.toArray(_vec4Array, light.color);

                    if (light.useColorTemperature) {
                      var tempRGB = light.colorTemperatureRGB;
                      _vec4Array[0] *= tempRGB.x;
                      _vec4Array[1] *= tempRGB.y;
                      _vec4Array[2] *= tempRGB.z;
                    }

                    if (pipeline.pipelineSceneData.isHDR) {
                      _vec4Array[3] = light.luminance * pipeline.pipelineSceneData.fpScale * this._lightMeterScale;
                    } else {
                      _vec4Array[3] = light.luminance * exposure * this._lightMeterScale;
                    }

                    this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 1);

                    _vec4Array[0] = light.size;
                    _vec4Array[1] = light.range;
                    _vec4Array[2] = 0.0;

                    this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 2);
                  }
                }

                for (var _i = 0; _i < spotLights.length && idx < this._maxDeferredLights; _i++, ++idx) {
                  var _light = spotLights[_i];
                  Sphere.set(_sphere, _light.position.x, _light.position.y, _light.position.z, _light.range);

                  if (intersect.sphereFrustum(_sphere, camera.frustum)) {
                    Vec3.toArray(_vec4Array, _light.position);
                    _vec4Array[3] = 1;

                    this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 0);

                    Vec3.toArray(_vec4Array, _light.color);

                    if (_light.useColorTemperature) {
                      var _tempRGB = _light.colorTemperatureRGB;
                      _vec4Array[0] *= _tempRGB.x;
                      _vec4Array[1] *= _tempRGB.y;
                      _vec4Array[2] *= _tempRGB.z;
                    }

                    if (pipeline.pipelineSceneData.isHDR) {
                      _vec4Array[3] = _light.luminance * pipeline.pipelineSceneData.fpScale * this._lightMeterScale;
                    } else {
                      _vec4Array[3] = _light.luminance * exposure * this._lightMeterScale;
                    }

                    this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 1);

                    _vec4Array[0] = _light.size;
                    _vec4Array[1] = _light.range;
                    _vec4Array[2] = _light.spotAngle;

                    this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 2);

                    Vec3.toArray(_vec4Array, _light.direction);

                    this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 3);
                  }
                }

                var offset = fieldLen * 3 + 3;

                this._lightBufferData.set([idx], offset);

                cmdBuff.updateBuffer(this._deferredLitsBufs, this._lightBufferData);
              };

              _proto.activate = function activate(pipeline, flow) {
                _RenderStage.prototype.activate.call(this, pipeline, flow);

                var device = pipeline.device;

                for (var i = 0; i < this.renderQueues.length; i++) {
                  this._renderQueues[i] = convertRenderQueue(this.renderQueues[i]);
                }

                var totalSize = Float32Array.BYTES_PER_ELEMENT * 4 * 4 * this._maxDeferredLights;
                totalSize = Math.ceil(totalSize / device.capabilities.uboOffsetAlignment) * device.capabilities.uboOffsetAlignment;
                this._deferredLitsBufs = device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, totalSize, device.capabilities.uboOffsetAlignment));
                var deferredLitsBufView = device.createBuffer(new BufferViewInfo(this._deferredLitsBufs, 0, totalSize));
                this._lightBufferData = new Float32Array(totalSize / Float32Array.BYTES_PER_ELEMENT);
                var layoutInfo = new DescriptorSetLayoutInfo(localDescriptorSetLayout.bindings);
                this._descriptorSetLayout = device.createDescriptorSetLayout(layoutInfo);
                this._descriptorSet = device.createDescriptorSet(new DescriptorSetInfo(this._descriptorSetLayout));

                this._descriptorSet.bindBuffer(UBOForwardLight.BINDING, deferredLitsBufView);

                this._planarQueue = new PlanarShadowQueue(this._pipeline);
              };

              _proto.destroy = function destroy() {
                this._deferredLitsBufs.destroy();

                this._deferredLitsBufs = null;
                this._descriptorSet = null;
              };

              _proto.render = function render(camera) {
                var pipeline = this._pipeline;
                var device = pipeline.device;
                var cmdBuff = pipeline.commandBuffers[0];
                var renderObjects = pipeline.pipelineSceneData.renderObjects;

                if (renderObjects.length === 0) {
                  return;
                }

                this.gatherLights(camera);

                this._descriptorSet.update();

                this._planarQueue.gatherShadowPasses(camera, cmdBuff);

                var dynamicOffsets = [0];
                cmdBuff.bindDescriptorSet(SetIndex.LOCAL, this._descriptorSet, dynamicOffsets);
                this._renderArea = pipeline.generateRenderArea(camera);

                if (camera.clearFlag & ClearFlagBit.COLOR) {
                  if (pipeline.pipelineSceneData.isHDR) {
                    SRGBToLinear(colors$3[0], camera.clearColor);
                    var scale = pipeline.pipelineSceneData.fpScale / camera.exposure;
                    colors$3[0].x *= scale;
                    colors$3[0].y *= scale;
                    colors$3[0].z *= scale;
                  } else {
                    colors$3[0].x = camera.clearColor.x;
                    colors$3[0].y = camera.clearColor.y;
                    colors$3[0].z = camera.clearColor.z;
                  }
                }

                colors$3[0].w = 0;
                var deferredData = pipeline.getDeferredRenderData(camera);
                var framebuffer = deferredData.lightingFrameBuffer;
                var renderPass = framebuffer.renderPass;
                cmdBuff.beginRenderPass(renderPass, framebuffer, this._renderArea, colors$3, camera.clearDepth, camera.clearStencil);
                cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet);
                var pass;
                var shader;
                var builinDeferred = builtinResMgr.get('builtin-deferred-material');

                if (builinDeferred) {
                  pass = builinDeferred.passes[0];
                  shader = ShaderPool.get(pass.getShaderVariant());
                } else {
                  pass = this._deferredMaterial.passes[LIGHTINGPASS_INDEX];
                  shader = ShaderPool.get(this._deferredMaterial.passes[LIGHTINGPASS_INDEX].getShaderVariant());
                }

                var inputAssembler = pipeline.quadIAOffscreen;
                var pso = null;

                if (pass != null && shader != null && inputAssembler != null) {
                  pso = PipelineStateManager.getOrCreatePipelineState(device, pass, shader, renderPass, inputAssembler);
                }

                if (pso != null) {
                  cmdBuff.bindPipelineState(pso);
                  cmdBuff.bindInputAssembler(inputAssembler);
                  cmdBuff.draw(inputAssembler);
                }

                this._renderQueues.forEach(renderQueueClearFunc);

                var m = 0;
                var p = 0;
                var k = 0;

                for (var i = 0; i < renderObjects.length; ++i) {
                  var ro = renderObjects[i];
                  var subModels = ro.model.subModels;

                  for (m = 0; m < subModels.length; ++m) {
                    var subModel = subModels[m];
                    var passes = subModel.passes;

                    for (p = 0; p < passes.length; ++p) {
                      var _pass = passes[p];
                      if (_pass.phase !== this._phaseID && _pass.phase !== this._defPhaseID) continue;

                      for (k = 0; k < this._renderQueues.length; k++) {
                        this._renderQueues[k].insertRenderPass(ro, m, p);
                      }
                    }
                  }
                }

                this._renderQueues.forEach(renderQueueSortFunc);

                for (var _i2 = 0; _i2 < this._renderQueues.length; _i2++) {
                  this._renderQueues[_i2].recordCommandBuffer(device, renderPass, cmdBuff);
                }

                this._planarQueue.recordCommandBuffer(device, renderPass, cmdBuff);

                cmdBuff.endRenderPass();
              };

              _createClass(LightingStage, [{
                key: "material",
                set: function set(val) {
                  if (this._deferredMaterial === val) {
                    return;
                  }

                  this._deferredMaterial = val;
                }
              }]);

              return LightingStage;
            }(RenderStage), _class3$c.initInfo = {
              name: 'LightingStage',
              priority: DeferredStagePriority.LIGHTING,
              tag: 0
            }, _temp$s), (_descriptor$m = _applyDecoratedDescriptor(_class2$s.prototype, "_deferredMaterial", [_dec2$g, serializable, _dec3$c], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor2$f = _applyDecoratedDescriptor(_class2$s.prototype, "renderQueues", [_dec4$8, serializable, _dec5$5], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            })), _class2$s)) || _class$t));

            var _dec$u, _class$u, _class2$t, _temp$t;
            var LightingFlow = exports('LightingFlow', (_dec$u = ccclass('LightingFlow'), _dec$u(_class$u = (_temp$t = _class2$t = function (_RenderFlow) {
              _inheritsLoose(LightingFlow, _RenderFlow);

              function LightingFlow() {
                return _RenderFlow.apply(this, arguments) || this;
              }

              var _proto = LightingFlow.prototype;

              _proto.initialize = function initialize(info) {
                _RenderFlow.prototype.initialize.call(this, info);

                if (this._stages.length === 0) {
                  var lightingStage = new LightingStage();
                  lightingStage.initialize(LightingStage.initInfo);

                  this._stages.push(lightingStage);
                }

                return true;
              };

              _proto.activate = function activate(pipeline) {
                _RenderFlow.prototype.activate.call(this, pipeline);
              };

              _proto.render = function render(camera) {
                _RenderFlow.prototype.render.call(this, camera);
              };

              _proto.destroy = function destroy() {
                _RenderFlow.prototype.destroy.call(this);
              };

              return LightingFlow;
            }(RenderFlow), _class2$t.initInfo = {
              name: PIPELINE_FLOW_LIGHTING,
              priority: DeferredFlowPriority.LIGHTING,
              stages: []
            }, _temp$t)) || _class$u));

            var _dec$v, _dec2$h, _dec3$d, _dec4$9, _dec5$6, _class$v, _class2$u, _descriptor$n, _descriptor2$g, _temp$u;
            var _samplerInfo$2 = [Filter.POINT, Filter.POINT, Filter.NONE, Address.CLAMP, Address.CLAMP, Address.CLAMP];
            var samplerHash = genSamplerHash(_samplerInfo$2);

            var InputAssemblerData = function InputAssemblerData() {
              this.quadIB = null;
              this.quadVB = null;
              this.quadIA = null;
            };

            var DeferredRenderData = function DeferredRenderData() {
              this.gbufferFrameBuffer = null;
              this.gbufferRenderTargets = [];
              this.lightingFrameBuffer = null;
              this.lightingRenderTargets = [];
              this.depthTex = null;
            };
            var DeferredPipeline = exports('DeferredPipeline', (_dec$v = ccclass('DeferredPipeline'), _dec2$h = type([RenderTextureConfig]), _dec3$d = displayOrder(), _dec4$9 = type([MaterialConfig]), _dec5$6 = displayOrder(), _dec$v(_class$v = (_class2$u = (_temp$u = function (_RenderPipeline) {
              _inheritsLoose(DeferredPipeline, _RenderPipeline);

              function DeferredPipeline() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _RenderPipeline.call.apply(_RenderPipeline, [this].concat(args)) || this;
                _this._quadIB = null;
                _this._quadVBOnscreen = null;
                _this._quadVBOffscreen = null;
                _this._quadIAOnscreen = null;
                _this._quadIAOffscreen = null;
                _this._deferredRenderData = null;
                _this._gbufferRenderPass = null;
                _this._lightingRenderPass = null;
                _this._width = 0;
                _this._height = 0;
                _this._lastUsedRenderArea = new Rect$1();

                _initializerDefineProperty(_this, "renderTextures", _descriptor$n, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "materials", _descriptor2$g, _assertThisInitialized(_this));

                _this._renderPasses = new Map();
                return _this;
              }

              var _proto = DeferredPipeline.prototype;

              _proto.initialize = function initialize(info) {
                _RenderPipeline.prototype.initialize.call(this, info);

                if (this._flows.length === 0) {
                  var shadowFlow = new ShadowFlow();
                  shadowFlow.initialize(ShadowFlow.initInfo);

                  this._flows.push(shadowFlow);

                  var gbufferFlow = new GbufferFlow();
                  gbufferFlow.initialize(GbufferFlow.initInfo);

                  this._flows.push(gbufferFlow);

                  var lightingFlow = new LightingFlow();
                  lightingFlow.initialize(LightingFlow.initInfo);

                  this._flows.push(lightingFlow);
                }

                return true;
              };

              _proto.activate = function activate() {
                this._macros.CC_PIPELINE_TYPE = 1;

                if (!_RenderPipeline.prototype.activate.call(this)) {
                  return false;
                }

                if (!this._activeRenderer()) {
                  errorID(2402);
                  return false;
                }

                return true;
              };

              _proto.render = function render(cameras) {
                if (cameras.length === 0) {
                  return;
                }

                this._commandBuffers[0].begin();

                this._pipelineUBO.updateGlobalUBO();

                for (var i = 0; i < cameras.length; i++) {
                  var camera = cameras[i];

                  if (camera.scene) {
                    sceneCulling(this, camera);

                    this._pipelineUBO.updateCameraUBO(camera);

                    for (var j = 0; j < this._flows.length; j++) {
                      this._flows[j].render(camera);
                    }
                  }
                }

                this._commandBuffers[0].end();

                this._device.queue.submit(this._commandBuffers);
              };

              _proto.getRenderPass = function getRenderPass(clearFlags) {
                var renderPass = this._renderPasses.get(clearFlags);

                if (renderPass) {
                  return renderPass;
                }

                var device = this.device;
                var colorAttachment = new ColorAttachment();
                var depthStencilAttachment = new DepthStencilAttachment();
                colorAttachment.format = device.colorFormat;
                depthStencilAttachment.format = device.depthStencilFormat;
                depthStencilAttachment.stencilStoreOp = StoreOp.DISCARD;
                depthStencilAttachment.depthStoreOp = StoreOp.DISCARD;

                if (!(clearFlags & ClearFlagBit.COLOR)) {
                  if (clearFlags & SKYBOX_FLAG) {
                    colorAttachment.loadOp = LoadOp.DISCARD;
                  } else {
                    colorAttachment.loadOp = LoadOp.LOAD;
                    colorAttachment.beginAccesses = [AccessType.PRESENT];
                  }
                }

                if ((clearFlags & ClearFlagBit.DEPTH_STENCIL) !== ClearFlagBit.DEPTH_STENCIL) {
                  if (!(clearFlags & ClearFlagBit.DEPTH)) depthStencilAttachment.depthLoadOp = LoadOp.LOAD;
                  if (!(clearFlags & ClearFlagBit.STENCIL)) depthStencilAttachment.stencilLoadOp = LoadOp.LOAD;
                  depthStencilAttachment.beginAccesses = [AccessType.DEPTH_STENCIL_ATTACHMENT_WRITE];
                }

                var renderPassInfo = new RenderPassInfo([colorAttachment], depthStencilAttachment);
                renderPass = device.createRenderPass(renderPassInfo);

                this._renderPasses.set(clearFlags, renderPass);

                return renderPass;
              };

              _proto.getDeferredRenderData = function getDeferredRenderData(camera) {
                if (!this._deferredRenderData) {
                  this._generateDeferredRenderData();
                }

                return this._deferredRenderData;
              };

              _proto._activeRenderer = function _activeRenderer() {
                var device = this.device;

                this._commandBuffers.push(device.commandBuffer);

                var sampler = samplerLib.getSampler(device, samplerHash);

                this._descriptorSet.bindSampler(UNIFORM_SHADOWMAP_BINDING, sampler);

                this._descriptorSet.bindTexture(UNIFORM_SHADOWMAP_BINDING, builtinResMgr.get('default-texture').getGFXTexture());

                this._descriptorSet.bindSampler(UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING, sampler);

                this._descriptorSet.bindTexture(UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING, builtinResMgr.get('default-texture').getGFXTexture());

                this._descriptorSet.update();

                var inputAssemblerDataOffscreen = new InputAssemblerData();
                inputAssemblerDataOffscreen = this.createQuadInputAssembler(SurfaceTransform.IDENTITY);

                if (!inputAssemblerDataOffscreen.quadIB || !inputAssemblerDataOffscreen.quadVB || !inputAssemblerDataOffscreen.quadIA) {
                  return false;
                }

                this._quadIB = inputAssemblerDataOffscreen.quadIB;
                this._quadVBOffscreen = inputAssemblerDataOffscreen.quadVB;
                this._quadIAOffscreen = inputAssemblerDataOffscreen.quadIA;
                var inputAssemblerDataOnscreen = this.createQuadInputAssembler(device.surfaceTransform);

                if (!inputAssemblerDataOnscreen.quadIB || !inputAssemblerDataOnscreen.quadVB || !inputAssemblerDataOnscreen.quadIA) {
                  return false;
                }

                this._quadVBOnscreen = inputAssemblerDataOnscreen.quadVB;
                this._quadIAOnscreen = inputAssemblerDataOnscreen.quadIA;

                if (!this._gbufferRenderPass) {
                  var colorAttachment0 = new ColorAttachment();
                  colorAttachment0.format = Format.RGBA16F;
                  colorAttachment0.loadOp = LoadOp.CLEAR;
                  colorAttachment0.storeOp = StoreOp.STORE;
                  var colorAttachment1 = new ColorAttachment();
                  colorAttachment1.format = Format.RGBA16F;
                  colorAttachment1.loadOp = LoadOp.CLEAR;
                  colorAttachment1.storeOp = StoreOp.STORE;
                  var colorAttachment2 = new ColorAttachment();
                  colorAttachment2.format = Format.RGBA16F;
                  colorAttachment2.loadOp = LoadOp.CLEAR;
                  colorAttachment2.storeOp = StoreOp.STORE;
                  var colorAttachment3 = new ColorAttachment();
                  colorAttachment3.format = Format.RGBA16F;
                  colorAttachment3.loadOp = LoadOp.CLEAR;
                  colorAttachment3.storeOp = StoreOp.STORE;
                  var depthStencilAttachment = new DepthStencilAttachment();
                  depthStencilAttachment.format = device.depthStencilFormat;
                  depthStencilAttachment.depthLoadOp = LoadOp.CLEAR;
                  depthStencilAttachment.depthStoreOp = StoreOp.STORE;
                  depthStencilAttachment.stencilLoadOp = LoadOp.CLEAR;
                  depthStencilAttachment.stencilStoreOp = StoreOp.STORE;
                  var renderPassInfo = new RenderPassInfo([colorAttachment0, colorAttachment1, colorAttachment2, colorAttachment3], depthStencilAttachment);
                  this._gbufferRenderPass = device.createRenderPass(renderPassInfo);
                }

                if (!this._lightingRenderPass) {
                  var colorAttachment = new ColorAttachment();
                  colorAttachment.format = Format.RGBA16F;
                  colorAttachment.loadOp = LoadOp.CLEAR;
                  colorAttachment.storeOp = StoreOp.STORE;
                  colorAttachment.endAccesses = [AccessType.COLOR_ATTACHMENT_WRITE];

                  var _depthStencilAttachment = new DepthStencilAttachment();

                  _depthStencilAttachment.format = device.depthStencilFormat;
                  _depthStencilAttachment.depthLoadOp = LoadOp.LOAD;
                  _depthStencilAttachment.depthStoreOp = StoreOp.DISCARD;
                  _depthStencilAttachment.stencilLoadOp = LoadOp.LOAD;
                  _depthStencilAttachment.stencilStoreOp = StoreOp.DISCARD;
                  _depthStencilAttachment.beginAccesses = [AccessType.DEPTH_STENCIL_ATTACHMENT_WRITE];
                  _depthStencilAttachment.endAccesses = [AccessType.DEPTH_STENCIL_ATTACHMENT_WRITE];

                  var _renderPassInfo = new RenderPassInfo([colorAttachment], _depthStencilAttachment);

                  this._lightingRenderPass = device.createRenderPass(_renderPassInfo);
                }

                this._width = device.width;
                this._height = device.height;

                this._generateDeferredRenderData();

                if (device.surfaceTransform === SurfaceTransform.IDENTITY || device.surfaceTransform === SurfaceTransform.ROTATE_180) {
                  this._width = device.width;
                  this._height = device.height;
                } else {
                  this._width = device.height;
                  this._height = device.width;
                }

                return true;
              };

              _proto.destroyUBOs = function destroyUBOs() {
                if (this._descriptorSet) {
                  this._descriptorSet.getBuffer(UBOGlobal.BINDING).destroy();

                  this._descriptorSet.getBuffer(UBOShadow.BINDING).destroy();

                  this._descriptorSet.getBuffer(UBOCamera.BINDING).destroy();

                  this._descriptorSet.getSampler(UNIFORM_SHADOWMAP_BINDING).destroy();

                  this._descriptorSet.getSampler(UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING).destroy();

                  this._descriptorSet.getTexture(UNIFORM_SHADOWMAP_BINDING).destroy();

                  this._descriptorSet.getTexture(UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING).destroy();
                }
              };

              _proto.destroyDeferredData = function destroyDeferredData() {
                var deferredData = this._deferredRenderData;

                if (deferredData) {
                  if (deferredData.gbufferFrameBuffer) deferredData.gbufferFrameBuffer.destroy();
                  if (deferredData.lightingFrameBuffer) deferredData.lightingFrameBuffer.destroy();
                  if (deferredData.depthTex) deferredData.depthTex.destroy();

                  for (var i = 0; i < deferredData.gbufferRenderTargets.length; i++) {
                    deferredData.gbufferRenderTargets[i].destroy();
                  }

                  deferredData.gbufferRenderTargets.length = 0;

                  for (var _i = 0; _i < deferredData.lightingRenderTargets.length; _i++) {
                    deferredData.lightingRenderTargets[_i].destroy();
                  }

                  deferredData.lightingRenderTargets.length = 0;
                }

                this._deferredRenderData = null;
              };

              _proto.destroy = function destroy() {
                this.destroyUBOs();
                this.destroyQuadInputAssembler();
                this.destroyDeferredData();

                var rpIter = this._renderPasses.values();

                var rpRes = rpIter.next();

                while (!rpRes.done) {
                  rpRes.value.destroy();
                  rpRes = rpIter.next();
                }

                this._commandBuffers.length = 0;
                return _RenderPipeline.prototype.destroy.call(this);
              };

              _proto.resize = function resize(width, height) {
                if (this._width === width && this._height === height) {
                  return;
                }

                this._width = width;
                this._height = height;
                this.destroyDeferredData();

                this._generateDeferredRenderData();
              };

              _proto.createQuadInputAssembler = function createQuadInputAssembler(surfaceTransform) {
                var inputAssemblerData = new InputAssemblerData();
                var vbStride = Float32Array.BYTES_PER_ELEMENT * 4;
                var vbSize = vbStride * 4;

                var quadVB = this._device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, vbSize, vbStride));

                if (!quadVB) {
                  return inputAssemblerData;
                }

                var ibStride = Uint8Array.BYTES_PER_ELEMENT;
                var ibSize = ibStride * 6;

                var quadIB = this._device.createBuffer(new BufferInfo(BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, ibSize, ibStride));

                if (!quadIB) {
                  return inputAssemblerData;
                }

                var indices = new Uint8Array(6);
                indices[0] = 0;
                indices[1] = 1;
                indices[2] = 2;
                indices[3] = 1;
                indices[4] = 3;
                indices[5] = 2;
                quadIB.update(indices);
                var attributes = new Array(2);
                attributes[0] = new Attribute('a_position', Format.RG32F);
                attributes[1] = new Attribute('a_texCoord', Format.RG32F);

                var quadIA = this._device.createInputAssembler(new InputAssemblerInfo(attributes, [quadVB], quadIB));

                inputAssemblerData.quadIB = quadIB;
                inputAssemblerData.quadVB = quadVB;
                inputAssemblerData.quadIA = quadIA;
                return inputAssemblerData;
              };

              _proto.updateQuadVertexData = function updateQuadVertexData(renderArea) {
                if (this._lastUsedRenderArea === renderArea) {
                  return;
                }

                this._lastUsedRenderArea = renderArea;
                var offData = this.genQuadVertexData(SurfaceTransform.IDENTITY, renderArea);

                this._quadVBOffscreen.update(offData);

                var onData = this.genQuadVertexData(this.device.surfaceTransform, renderArea);

                this._quadVBOnscreen.update(onData);
              };

              _proto.genQuadVertexData = function genQuadVertexData(surfaceTransform, renderArea) {
                var vbData = new Float32Array(4 * 4);
                var minX = renderArea.x / this.device.width;
                var maxX = (renderArea.x + renderArea.width) / this.device.width;
                var minY = renderArea.y / this.device.height;
                var maxY = (renderArea.y + renderArea.height) / this.device.height;

                if (this.device.capabilities.screenSpaceSignY > 0) {
                  var temp = maxY;
                  maxY = minY;
                  minY = temp;
                }

                var n = 0;

                switch (surfaceTransform) {
                  case SurfaceTransform.IDENTITY:
                    n = 0;
                    vbData[n++] = -1.0;
                    vbData[n++] = -1.0;
                    vbData[n++] = minX;
                    vbData[n++] = maxY;
                    vbData[n++] = 1.0;
                    vbData[n++] = -1.0;
                    vbData[n++] = maxX;
                    vbData[n++] = maxY;
                    vbData[n++] = -1.0;
                    vbData[n++] = 1.0;
                    vbData[n++] = minX;
                    vbData[n++] = minY;
                    vbData[n++] = 1.0;
                    vbData[n++] = 1.0;
                    vbData[n++] = maxX;
                    vbData[n++] = minY;
                    break;

                  case SurfaceTransform.ROTATE_90:
                    n = 0;
                    vbData[n++] = -1.0;
                    vbData[n++] = -1.0;
                    vbData[n++] = maxX;
                    vbData[n++] = maxY;
                    vbData[n++] = 1.0;
                    vbData[n++] = -1.0;
                    vbData[n++] = maxX;
                    vbData[n++] = minY;
                    vbData[n++] = -1.0;
                    vbData[n++] = 1.0;
                    vbData[n++] = minX;
                    vbData[n++] = maxY;
                    vbData[n++] = 1.0;
                    vbData[n++] = 1.0;
                    vbData[n++] = minX;
                    vbData[n++] = minY;
                    break;

                  case SurfaceTransform.ROTATE_180:
                    n = 0;
                    vbData[n++] = -1.0;
                    vbData[n++] = -1.0;
                    vbData[n++] = minX;
                    vbData[n++] = minY;
                    vbData[n++] = 1.0;
                    vbData[n++] = -1.0;
                    vbData[n++] = maxX;
                    vbData[n++] = minY;
                    vbData[n++] = -1.0;
                    vbData[n++] = 1.0;
                    vbData[n++] = minX;
                    vbData[n++] = maxY;
                    vbData[n++] = 1.0;
                    vbData[n++] = 1.0;
                    vbData[n++] = maxX;
                    vbData[n++] = maxY;
                    break;

                  case SurfaceTransform.ROTATE_270:
                    n = 0;
                    vbData[n++] = -1.0;
                    vbData[n++] = -1.0;
                    vbData[n++] = minX;
                    vbData[n++] = minY;
                    vbData[n++] = 1.0;
                    vbData[n++] = -1.0;
                    vbData[n++] = minX;
                    vbData[n++] = maxY;
                    vbData[n++] = -1.0;
                    vbData[n++] = 1.0;
                    vbData[n++] = maxX;
                    vbData[n++] = minY;
                    vbData[n++] = 1.0;
                    vbData[n++] = 1.0;
                    vbData[n++] = maxX;
                    vbData[n++] = maxY;
                    break;
                }

                return vbData;
              };

              _proto.destroyQuadInputAssembler = function destroyQuadInputAssembler() {
                if (this._quadIB) {
                  this._quadIB.destroy();

                  this._quadIB = null;
                }

                if (this._quadVBOnscreen) {
                  this._quadVBOnscreen.destroy();

                  this._quadVBOnscreen = null;
                }

                if (this._quadVBOffscreen) {
                  this._quadVBOffscreen.destroy();

                  this._quadVBOffscreen = null;
                }

                if (this._quadIAOnscreen) {
                  this._quadIAOnscreen.destroy();

                  this._quadIAOnscreen = null;
                }

                if (this._quadIAOffscreen) {
                  this._quadIAOffscreen.destroy();

                  this._quadIAOffscreen = null;
                }
              };

              _proto._generateDeferredRenderData = function _generateDeferredRenderData() {
                var device = this.device;
                var data = this._deferredRenderData = new DeferredRenderData();
                data.gbufferRenderTargets.push(device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.COLOR_ATTACHMENT | TextureUsageBit.SAMPLED, Format.RGBA16F, this._width, this._height)));
                data.gbufferRenderTargets.push(device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.COLOR_ATTACHMENT | TextureUsageBit.SAMPLED, Format.RGBA16F, this._width, this._height)));
                data.gbufferRenderTargets.push(device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.COLOR_ATTACHMENT | TextureUsageBit.SAMPLED, Format.RGBA16F, this._width, this._height)));
                data.gbufferRenderTargets.push(device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.COLOR_ATTACHMENT | TextureUsageBit.SAMPLED, Format.RGBA16F, this._width, this._height)));
                data.depthTex = device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.DEPTH_STENCIL_ATTACHMENT, device.depthStencilFormat, this._width, this._height));
                data.gbufferFrameBuffer = device.createFramebuffer(new FramebufferInfo(this._gbufferRenderPass, data.gbufferRenderTargets, data.depthTex));
                data.lightingRenderTargets.push(device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.COLOR_ATTACHMENT | TextureUsageBit.SAMPLED, Format.RGBA16F, this._width, this._height)));
                data.lightingFrameBuffer = device.createFramebuffer(new FramebufferInfo(this._lightingRenderPass, data.lightingRenderTargets, data.depthTex));

                this._descriptorSet.bindTexture(UNIFORM_GBUFFER_ALBEDOMAP_BINDING, data.gbufferFrameBuffer.colorTextures[0]);

                this._descriptorSet.bindTexture(UNIFORM_GBUFFER_POSITIONMAP_BINDING, data.gbufferFrameBuffer.colorTextures[1]);

                this._descriptorSet.bindTexture(UNIFORM_GBUFFER_NORMALMAP_BINDING, data.gbufferFrameBuffer.colorTextures[2]);

                this._descriptorSet.bindTexture(UNIFORM_GBUFFER_EMISSIVEMAP_BINDING, data.gbufferFrameBuffer.colorTextures[3]);

                this._descriptorSet.bindTexture(UNIFORM_LIGHTING_RESULTMAP_BINDING, data.lightingFrameBuffer.colorTextures[0]);

                var sampler = samplerLib.getSampler(device, samplerHash);

                this._descriptorSet.bindSampler(UNIFORM_GBUFFER_ALBEDOMAP_BINDING, sampler);

                this._descriptorSet.bindSampler(UNIFORM_GBUFFER_POSITIONMAP_BINDING, sampler);

                this._descriptorSet.bindSampler(UNIFORM_GBUFFER_NORMALMAP_BINDING, sampler);

                this._descriptorSet.bindSampler(UNIFORM_GBUFFER_EMISSIVEMAP_BINDING, sampler);

                this._descriptorSet.bindSampler(UNIFORM_LIGHTING_RESULTMAP_BINDING, sampler);
              };

              _createClass(DeferredPipeline, [{
                key: "quadIAOnscreen",
                get: function get() {
                  return this._quadIAOnscreen;
                }
              }, {
                key: "quadIAOffscreen",
                get: function get() {
                  return this._quadIAOffscreen;
                }
              }]);

              return DeferredPipeline;
            }(RenderPipeline), _temp$u), (_descriptor$n = _applyDecoratedDescriptor(_class2$u.prototype, "renderTextures", [_dec2$h, serializable, _dec3$d], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor2$g = _applyDecoratedDescriptor(_class2$u.prototype, "materials", [_dec4$9, serializable, _dec5$6], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            })), _class2$u)) || _class$v));

            var _dec$w, _dec2$i, _dec3$e, _class$w, _class2$v, _descriptor$o, _class3$d, _temp$v;
            var colors$4 = [new Color$1(0, 0, 0, 1)];
            var POSTPROCESSPASS_INDEX = 0;
            var PostprocessStage = exports('PostprocessStage', (_dec$w = ccclass('PostprocessStage'), _dec2$i = type(Material), _dec3$e = displayOrder(), _dec$w(_class$w = (_class2$v = (_temp$v = _class3$d = function (_RenderStage) {
              _inheritsLoose(PostprocessStage, _RenderStage);

              function PostprocessStage() {
                var _this;

                _this = _RenderStage.call(this) || this;

                _initializerDefineProperty(_this, "_postprocessMaterial", _descriptor$o, _assertThisInitialized(_this));

                _this._renderArea = new Rect$1();
                _this._uiPhase = void 0;
                _this._uiPhase = new UIPhase();
                return _this;
              }

              var _proto = PostprocessStage.prototype;

              _proto.initialize = function initialize(info) {
                _RenderStage.prototype.initialize.call(this, info);

                return true;
              };

              _proto.activate = function activate(pipeline, flow) {
                _RenderStage.prototype.activate.call(this, pipeline, flow);

                this._uiPhase.activate(pipeline);
              };

              _proto.destroy = function destroy() {};

              _proto.render = function render(camera) {
                var pipeline = this._pipeline;
                var device = pipeline.device;
                var cmdBuff = pipeline.commandBuffers[0];
                pipeline.pipelineUBO.updateCameraUBO(camera);
                var vp = camera.viewport;
                this._renderArea.x = vp.x * camera.width;
                this._renderArea.y = vp.y * camera.height;
                this._renderArea.width = vp.width * camera.width * pipeline.pipelineSceneData.shadingScale;
                this._renderArea.height = vp.height * camera.height * pipeline.pipelineSceneData.shadingScale;
                var framebuffer = camera.window.framebuffer;
                var renderPass = framebuffer.colorTextures[0] ? framebuffer.renderPass : pipeline.getRenderPass(camera.clearFlag);

                if (camera.clearFlag & ClearFlagBit.COLOR) {
                  colors$4[0].x = camera.clearColor.x;
                  colors$4[0].y = camera.clearColor.y;
                  colors$4[0].z = camera.clearColor.z;
                }

                colors$4[0].w = camera.clearColor.w;
                cmdBuff.beginRenderPass(renderPass, framebuffer, this._renderArea, colors$4, camera.clearDepth, camera.clearStencil);
                cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet);
                var pass;
                var shader;
                var builtinPostProcess = builtinResMgr.get('builtin-post-process-material');

                if (builtinPostProcess) {
                  pass = builtinPostProcess.passes[0];
                  shader = ShaderPool.get(pass.getShaderVariant());
                } else {
                  pass = this._postprocessMaterial.passes[POSTPROCESSPASS_INDEX];
                  shader = ShaderPool.get(this._postprocessMaterial.passes[POSTPROCESSPASS_INDEX].getShaderVariant());
                }

                var inputAssembler = camera.window.hasOffScreenAttachments ? pipeline.quadIAOffscreen : pipeline.quadIAOnscreen;
                var pso = null;

                if (pass != null && shader != null && inputAssembler != null) {
                  pso = PipelineStateManager.getOrCreatePipelineState(device, pass, shader, renderPass, inputAssembler);
                }

                var renderObjects = pipeline.pipelineSceneData.renderObjects;

                if (pso != null && renderObjects.length > 0) {
                  cmdBuff.bindPipelineState(pso);
                  cmdBuff.bindInputAssembler(inputAssembler);
                  cmdBuff.draw(inputAssembler);
                }

                this._uiPhase.render(camera, renderPass);

                cmdBuff.endRenderPass();
              };

              _createClass(PostprocessStage, [{
                key: "material",
                set: function set(val) {
                  if (this._postprocessMaterial === val) {
                    return;
                  }

                  this._postprocessMaterial = val;
                }
              }]);

              return PostprocessStage;
            }(RenderStage), _class3$d.initInfo = {
              name: 'PostprocessStage',
              priority: DeferredStagePriority.POSTPROCESS,
              tag: 0
            }, _temp$v), (_descriptor$o = _applyDecoratedDescriptor(_class2$v.prototype, "_postprocessMaterial", [_dec2$i, serializable, _dec3$e], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            })), _class2$v)) || _class$w));

            function createDefaultPipeline() {
              var rppl = new ForwardPipeline();
              rppl.initialize({
                flows: []
              });
              return rppl;
            }

            var Game = exports('Game', function (_EventTarget) {
              _inheritsLoose(Game, _EventTarget);

              function Game() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _EventTarget.call.apply(_EventTarget, [this].concat(args)) || this;
                _this.frame = null;
                _this.container = null;
                _this.canvas = null;
                _this.renderType = -1;
                _this.eventTargetOn = _EventTarget.prototype.on;
                _this.eventTargetOnce = _EventTarget.prototype.once;
                _this.config = {};
                _this.onStart = null;
                _this.collisionMatrix = [];
                _this.groupList = [];
                _this._persistRootNodes = {};
                _this._paused = true;
                _this._configLoaded = false;
                _this._isCloning = false;
                _this._inited = false;
                _this._engineInited = false;
                _this._rendererInitialized = false;
                _this._gfxDevice = null;
                _this._intervalId = null;
                return _this;
              }

              var _proto = Game.prototype;

              _proto.setFrameRate = function setFrameRate(frameRate) {
                var config = this.config;

                if (typeof frameRate !== 'number') {
                  frameRate = parseInt(frameRate, 10);

                  if (Number.isNaN(frameRate)) {
                    frameRate = 60;
                  }
                }

                config.frameRate = frameRate;
                this._paused = true;

                this._setAnimFrame();

                this._runMainLoop();
              };

              _proto.getFrameRate = function getFrameRate() {
                return this.config.frameRate || 0;
              };

              _proto.step = function step() {
                legacyCC.director.mainLoop();
              };

              _proto.pause = function pause() {
                if (this._paused) {
                  return;
                }

                this._paused = true;

                if (this._intervalId) {
                  window.cAF(this._intervalId);
                  this._intervalId = 0;
                }
              };

              _proto.resume = function resume() {
                if (!this._paused) {
                  return;
                }

                this._runMainLoop();
              };

              _proto.isPaused = function isPaused() {
                return this._paused;
              };

              _proto.restart = function restart() {
                var _this2 = this;

                var afterDrawPromise = new Promise(function (resolve) {
                  return legacyCC.director.once(legacyCC.Director.EVENT_AFTER_DRAW, function () {
                    return resolve();
                  });
                });
                return afterDrawPromise.then(function () {
                  for (var id in _this2._persistRootNodes) {
                    _this2.removePersistRootNode(_this2._persistRootNodes[id]);
                  }

                  legacyCC.director.getScene().destroy();

                  legacyCC.Object._deferredDestroy();

                  legacyCC.director.reset();

                  _this2.pause();

                  return _this2._setRenderPipelineNShowSplash().then(function () {
                    _this2.resume();

                    _this2._safeEmit(Game.EVENT_RESTART);
                  });
                });
              };

              _proto.end = function end() {
                if (this._gfxDevice) {
                  this._gfxDevice.destroy();

                  this._gfxDevice = null;
                }

                window.close();
              };

              _proto.on = function on(type, callback, target, once) {
                if (this._engineInited && type === Game.EVENT_ENGINE_INITED || this._inited && type === Game.EVENT_GAME_INITED || this._rendererInitialized && type === Game.EVENT_RENDERER_INITED) {
                  callback.call(target);
                }

                return this.eventTargetOn(type, callback, target, once);
              };

              _proto.once = function once(type, callback, target) {
                if (this._engineInited && type === Game.EVENT_ENGINE_INITED) {
                  return callback.call(target);
                }

                return this.eventTargetOnce(type, callback, target);
              };

              _proto.init = function init(config) {
                var _this3 = this;

                this._initConfig(config);

                if (this.config.assetOptions) {
                  legacyCC.assetManager.init(this.config.assetOptions);
                }

                return this._initEngine().then(function () {
                  {
                    _this3._initEvents();
                  }

                  if (legacyCC.director.root.dataPoolManager) {
                    legacyCC.director.root.dataPoolManager.jointTexturePool.registerCustomTextureLayouts(config.customJointTextureLayouts);
                  }

                  return _this3._engineInited;
                });
              };

              _proto.run = function run(configOrCallback, onStart) {
                var _this4 = this;

                var initPromise;

                if (typeof configOrCallback !== 'function' && configOrCallback) {
                  initPromise = this.init(configOrCallback);
                  this.onStart = onStart !== null && onStart !== void 0 ? onStart : null;
                } else {
                  this.onStart = configOrCallback !== null && configOrCallback !== void 0 ? configOrCallback : null;
                }

                return Promise.resolve(initPromise).then(function () {
                  if ( game.config.registerSystemEvent) {
                    inputManager.registerSystemEvent();
                  }

                  return _this4._setRenderPipelineNShowSplash();
                });
              };

              _proto.addPersistRootNode = function addPersistRootNode(node) {
                if (!legacyCC.Node.isNode(node) || !node.uuid) {
                  warnID(3800);
                  return;
                }

                var id = node.uuid;

                if (!this._persistRootNodes[id]) {
                  var scene = legacyCC.director._scene;

                  if (legacyCC.isValid(scene)) {
                    if (!node.parent) {
                      node.parent = scene;
                    } else if (!(node.parent instanceof legacyCC.Scene)) {
                      warnID(3801);
                      return;
                    } else if (node.parent !== scene) {
                      warnID(3802);
                      return;
                    } else {
                      node._originalSceneId = scene.uuid;
                    }
                  }

                  this._persistRootNodes[id] = node;
                  node._persistNode = true;

                  legacyCC.assetManager._releaseManager._addPersistNodeRef(node);
                }
              };

              _proto.removePersistRootNode = function removePersistRootNode(node) {
                var id = node.uuid || '';

                if (node === this._persistRootNodes[id]) {
                  delete this._persistRootNodes[id];
                  node._persistNode = false;
                  node._originalSceneId = '';

                  legacyCC.assetManager._releaseManager._removePersistNodeRef(node);
                }
              };

              _proto.isPersistRootNode = function isPersistRootNode(node) {
                return !!node._persistNode;
              };

              _proto._initEngine = function _initEngine() {
                var _this5 = this;

                this._initDevice();

                return Promise.resolve(legacyCC.director._init()).then(function () {
                  log("Cocos Creator v" + engineVersion);

                  _this5.emit(Game.EVENT_ENGINE_INITED);

                  _this5._engineInited = true;
                  legacyCC.internal.dynamicAtlasManager.enabled = !macro.CLEANUP_IMAGE_CACHE;
                });
              };

              _proto._setAnimFrame = function _setAnimFrame() {
                this._lastTime = performance.now();
                var frameRate = this.config.frameRate;
                this._frameTime = 1000 / frameRate;

                {
                  if (this._intervalId) {
                    window.cAF(this._intervalId);
                    this._intervalId = 0;
                  }

                  var rAF = window.requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame;

                  if (frameRate !== 60 && frameRate !== 30) {
                    window.rAF = rAF ? this._stTimeWithRAF : this._stTime;
                    window.cAF = this._ctTime;
                  } else {
                    window.rAF = rAF || this._stTime;
                    window.cAF = window.cancelAnimationFrame || window.cancelRequestAnimationFrame || window.msCancelRequestAnimationFrame || window.mozCancelRequestAnimationFrame || window.oCancelRequestAnimationFrame || window.webkitCancelRequestAnimationFrame || window.msCancelAnimationFrame || window.mozCancelAnimationFrame || window.webkitCancelAnimationFrame || window.ocancelAnimationFrame || this._ctTime;
                  }
                }
              };

              _proto._stTimeWithRAF = function _stTimeWithRAF(callback) {
                var currTime = performance.now();
                var elapseTime = Math.max(0, currTime - game._lastTime);
                var timeToCall = Math.max(0, game._frameTime - elapseTime);
                var id = window.setTimeout(function () {
                  window.requestAnimationFrame(callback);
                }, timeToCall);
                game._lastTime = currTime + timeToCall;
                return id;
              };

              _proto._stTime = function _stTime(callback) {
                var currTime = performance.now();
                var elapseTime = Math.max(0, currTime - game._lastTime);
                var timeToCall = Math.max(0, game._frameTime - elapseTime);
                var id = window.setTimeout(callback, timeToCall);
                game._lastTime = currTime + timeToCall;
                return id;
              };

              _proto._ctTime = function _ctTime(id) {
                window.clearTimeout(id);
              };

              _proto._runMainLoop = function _runMainLoop() {
                var _this6 = this;

                if (!this._inited || EDITOR ) {
                  return;
                }

                var config = this.config;
                var director = legacyCC.director;
                var frameRate = config.frameRate;
                setDisplayStats(!!config.showFPS);
                director.startAnimation();

                var _callback2;

                if ( frameRate === 30) {
                  var skip = true;

                  _callback2 = function callback(time) {
                    _this6._intervalId = window.rAF(_callback2);
                    skip = !skip;

                    if (skip) {
                      return;
                    }

                    director.mainLoop(time);
                  };
                } else {
                  _callback2 = function _callback(time) {
                    _this6._intervalId = window.rAF(_callback2);
                    director.mainLoop(time);
                  };
                }

                if (this._intervalId) {
                  window.cAF(this._intervalId);
                  this._intervalId = 0;
                }

                this._intervalId = window.rAF(_callback2);
                this._paused = false;
              };

              _proto._initConfig = function _initConfig(config) {
                if (typeof config.debugMode !== 'number') {
                  config.debugMode = DebugMode.NONE;
                }

                config.exposeClassName = !!config.exposeClassName;

                if (typeof config.frameRate !== 'number') {
                  config.frameRate = 60;
                }

                var renderMode = config.renderMode;

                if (typeof renderMode !== 'number' || renderMode > 2 || renderMode < 0) {
                  config.renderMode = 0;
                }

                if (typeof config.registerSystemEvent !== 'boolean') {
                  config.registerSystemEvent = true;
                }

                config.showFPS = !!config.showFPS;
                this.collisionMatrix = config.collisionMatrix || [];
                this.groupList = config.groupList || [];

                _resetDebugSetting(config.debugMode);

                this.config = config;
                this._configLoaded = true;

                this._setAnimFrame();
              };

              _proto._determineRenderType = function _determineRenderType() {
                var config = this.config;
                var userRenderMode = parseInt(config.renderMode, 10);
                this.renderType = Game.RENDER_TYPE_CANVAS;
                var supportRender = false;

                if (userRenderMode === 0) {
                  if (legacyCC.sys.capabilities.opengl) {
                    this.renderType = Game.RENDER_TYPE_WEBGL;
                    supportRender = true;
                  } else if (legacyCC.sys.capabilities.canvas) {
                    this.renderType = Game.RENDER_TYPE_CANVAS;
                    supportRender = true;
                  }
                } else if (userRenderMode === 1 && legacyCC.sys.capabilities.canvas) {
                  this.renderType = Game.RENDER_TYPE_CANVAS;
                  supportRender = true;
                } else if (userRenderMode === 2 && legacyCC.sys.capabilities.opengl) {
                  this.renderType = Game.RENDER_TYPE_WEBGL;
                  supportRender = true;
                }

                if (!supportRender) {
                  throw new Error(getError(3820, userRenderMode));
                }
              };

              _proto._initDevice = function _initDevice() {
                if (this._rendererInitialized) {
                  return;
                }

                this.canvas = this.config.adapter.canvas;
                this.frame = this.config.adapter.frame;
                this.container = this.config.adapter.container;

                this._determineRenderType();

                if (this.renderType === Game.RENDER_TYPE_WEBGL) {
                  var ctors = [];

                  {
                    var useWebGL2 = !!window.WebGL2RenderingContext;
                    var userAgent = window.navigator.userAgent.toLowerCase();

                    if (userAgent.indexOf('safari') !== -1 && userAgent.indexOf('chrome') === -1 || system.browserType === BrowserType.UC) {
                        useWebGL2 = false;
                      }

                    if (useWebGL2 && legacyCC.WebGL2Device) {
                      ctors.push(legacyCC.WebGL2Device);
                    }

                    if (legacyCC.WebGLDevice) {
                      ctors.push(legacyCC.WebGLDevice);
                    }

                    var opts = new DeviceInfo(this.canvas,  macro.ENABLE_WEBGL_ANTIALIAS, false, window.devicePixelRatio, sys.windowPixelResolution.width, sys.windowPixelResolution.height, bindingMappingInfo);

                    for (var i = 0; i < ctors.length; i++) {
                      this._gfxDevice = new ctors[i]();

                      if (this._gfxDevice.initialize(opts)) {
                        break;
                      }
                    }
                  }
                }

                if (!this._gfxDevice) {
                  error('can not support canvas rendering in 3D');
                  this.renderType = Game.RENDER_TYPE_CANVAS;
                  return;
                }

                this.canvas.oncontextmenu = function () {
                  return false;
                };
              };

              _proto._initEvents = function _initEvents() {
                system.onShow(this._onShow.bind(this));
                system.onHide(this._onHide.bind(this));
              };

              _proto._onHide = function _onHide() {
                this.emit(Game.EVENT_HIDE);
                this.pause();
              };

              _proto._onShow = function _onShow() {
                this.emit(Game.EVENT_SHOW);
                this.resume();
              };

              _proto._setRenderPipelineNShowSplash = function _setRenderPipelineNShowSplash() {
                var _this7 = this;

                return Promise.resolve(this._setupRenderPipeline()).then(function () {
                  return Promise.resolve(_this7._showSplashScreen()).then(function () {
                    _this7._inited = true;

                    _this7._setAnimFrame();

                    _this7._runMainLoop();

                    _this7._safeEmit(Game.EVENT_GAME_INITED);

                    if (_this7.onStart) {
                      _this7.onStart();
                    }
                  });
                });
              };

              _proto._setupRenderPipeline = function _setupRenderPipeline() {
                var _this8 = this;

                var renderPipeline = this.config.renderPipeline;

                if (!renderPipeline) {
                  return this._setRenderPipeline();
                }

                return new Promise(function (resolve, reject) {
                  legacyCC.assetManager.loadAny(renderPipeline, function (err, asset) {
                    return err || !(asset instanceof RenderPipeline) ? reject(err) : resolve(asset);
                  });
                }).then(function (asset) {
                  _this8._setRenderPipeline(asset);
                })["catch"](function (reason) {
                  warn(reason);
                  warn("Failed load render pipeline: " + renderPipeline + ", engine failed to initialize, will fallback to default pipeline");

                  _this8._setRenderPipeline();
                });
              };

              _proto._showSplashScreen = function _showSplashScreen() {
                if ( legacyCC.internal.SplashScreen) {
                  var splashScreen = legacyCC.internal.SplashScreen.instance;
                  splashScreen.main(legacyCC.director.root);
                  return new Promise(function (resolve) {
                    splashScreen.setOnFinish(function () {
                      return resolve();
                    });
                    splashScreen.loadFinish = true;
                  });
                }

                return null;
              };

              _proto._setRenderPipeline = function _setRenderPipeline(rppl) {
                if (!legacyCC.director.root.setRenderPipeline(rppl)) {
                  this._setRenderPipeline();
                }

                this._rendererInitialized = true;

                this._safeEmit(Game.EVENT_RENDERER_INITED);
              };

              _proto._safeEmit = function _safeEmit(event) {
                {
                  this.emit(event);
                }
              };

              _createClass(Game, [{
                key: "inited",
                get: function get() {
                  return this._inited;
                }
              }, {
                key: "frameTime",
                get: function get() {
                  return this._frameTime;
                }
              }]);

              return Game;
            }(EventTarget));
            Game.EVENT_HIDE = 'game_on_hide';
            Game.EVENT_SHOW = 'game_on_show';
            Game.EVENT_LOW_MEMORY = 'game_on_low_memory';
            Game.EVENT_GAME_INITED = 'game_inited';
            Game.EVENT_ENGINE_INITED = 'engine_inited';
            Game.EVENT_RENDERER_INITED = 'renderer_inited';
            Game.EVENT_RESTART = 'game_on_restart';
            Game.RENDER_TYPE_CANVAS = 0;
            Game.RENDER_TYPE_WEBGL = 1;
            Game.RENDER_TYPE_OPENGL = 2;
            legacyCC.Game = Game;
            var game = exports('game', legacyCC.game = new Game());

            var 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: function init(visibleRect_) {
                var w = this.width = visibleRect_.width;
                var h = this.height = visibleRect_.height;
                var l = visibleRect_.x;
                var b = visibleRect_.y;
                var t = b + h;
                var r = l + w;
                this.topLeft.x = l;
                this.topLeft.y = t;
                this.topRight.x = r;
                this.topRight.y = t;
                this.top.x = l + w / 2;
                this.top.y = t;
                this.bottomLeft.x = l;
                this.bottomLeft.y = b;
                this.bottomRight.x = r;
                this.bottomRight.y = b;
                this.bottom.x = l + w / 2;
                this.bottom.y = b;
                this.center.x = l + w / 2;
                this.center.y = b + h / 2;
                this.left.x = l;
                this.left.y = b + h / 2;
                this.right.x = r;
                this.right.y = b + h / 2;
              }
            };
            legacyCC.visibleRect = visibleRect;

            var BrowserGetter = function () {
              function BrowserGetter() {
                this.html = void 0;
                this.meta = {
                  width: 'device-width'
                };
                this.adaptationType = legacyCC.sys.browserType;
              }

              var _proto = BrowserGetter.prototype;

              _proto.init = function init() {
                {
                  this.html = document.getElementsByTagName('html')[0];
                }
              };

              _proto.availWidth = function availWidth(frame) {
                if (legacyCC.sys.isMobile || !frame || frame === this.html) {
                  return window.innerWidth;
                } else {
                  return frame.clientWidth;
                }
              };

              _proto.availHeight = function availHeight(frame) {
                if (legacyCC.sys.isMobile || !frame || frame === this.html) {
                  return window.innerHeight;
                } else {
                  return frame.clientHeight;
                }
              };

              return BrowserGetter;
            }();

            var __BrowserGetter = new BrowserGetter();

            if (system.os === OS.IOS) {
              __BrowserGetter.adaptationType = BrowserType.SAFARI;
            }

            switch (__BrowserGetter.adaptationType) {
              case BrowserType.SAFARI:
                {
                  __BrowserGetter.meta['minimal-ui'] = 'true';

                  __BrowserGetter.availWidth = function (frame) {
                    return frame.clientWidth;
                  };

                  __BrowserGetter.availHeight = function (frame) {
                    return frame.clientHeight;
                  };

                  break;
                }

              case BrowserType.SOUGOU:
                {
                  __BrowserGetter.availWidth = function (frame) {
                    return frame.clientWidth;
                  };

                  __BrowserGetter.availHeight = function (frame) {
                    return frame.clientHeight;
                  };

                  break;
                }

              case BrowserType.UC:
                {
                  __BrowserGetter.availWidth = function (frame) {
                    return frame.clientWidth;
                  };

                  __BrowserGetter.availHeight = function (frame) {
                    return frame.clientHeight;
                  };

                  break;
                }
            }

            var View = exports('View', function (_EventTarget) {
              _inheritsLoose(View, _EventTarget);

              function View() {
                var _this;

                _this = _EventTarget.call(this) || this;
                _this._resizeWithBrowserSize = void 0;
                _this._designResolutionSize = void 0;
                _this._originalDesignResolutionSize = void 0;
                _this._frameSize = void 0;
                _this._scaleX = void 0;
                _this._scaleY = void 0;
                _this._viewportRect = void 0;
                _this._visibleRect = void 0;
                _this._autoFullScreen = void 0;
                _this._devicePixelRatio = void 0;
                _this._maxPixelRatio = void 0;
                _this._retinaEnabled = void 0;
                _this._resizeCallback = void 0;
                _this._resizing = void 0;
                _this._orientationChanging = void 0;
                _this._isRotated = void 0;
                _this._orientation = void 0;
                _this._isAdjustViewport = void 0;
                _this._resolutionPolicy = void 0;
                _this._rpExactFit = void 0;
                _this._rpShowAll = void 0;
                _this._rpNoBorder = void 0;
                _this._rpFixedHeight = void 0;
                _this._rpFixedWidth = void 0;
                var _strategyer = ContainerStrategy;
                var _strategy = ContentStrategy;
                _this._frameSize = new Size(0, 0);
                _this._designResolutionSize = new Size(0, 0);
                _this._originalDesignResolutionSize = new Size(0, 0);
                _this._scaleX = 1;
                _this._scaleY = 1;
                _this._viewportRect = new Rect(0, 0, 0, 0);
                _this._visibleRect = new Rect(0, 0, 0, 0);
                _this._autoFullScreen = false;
                _this._devicePixelRatio = 1;

                {
                  _this._maxPixelRatio = 2;
                }

                _this._retinaEnabled = false;
                _this._resizeCallback = null;
                _this._resizing = false;
                _this._resizeWithBrowserSize = false;
                _this._orientationChanging = true;
                _this._isRotated = false;
                _this._orientation = legacyCC.macro.ORIENTATION_AUTO;
                _this._isAdjustViewport = true;
                _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;
                legacyCC.game.once(legacyCC.Game.EVENT_ENGINE_INITED, _this.init, _assertThisInitialized(_this));
                return _this;
              }

              var _proto2 = View.prototype;

              _proto2.init = function init() {
                __BrowserGetter.init();

                this._initFrameSize();

                var w = legacyCC.game.canvas.width;
                var h = legacyCC.game.canvas.height;
                this._designResolutionSize.width = w;
                this._designResolutionSize.height = h;
                this._originalDesignResolutionSize.width = w;
                this._originalDesignResolutionSize.height = h;
                this._viewportRect.width = w;
                this._viewportRect.height = h;
                this._visibleRect.width = w;
                this._visibleRect.height = h;
                legacyCC.winSize.width = this._visibleRect.width;
                legacyCC.winSize.height = this._visibleRect.height;

                if (legacyCC.visibleRect) {
                  legacyCC.visibleRect.init(this._visibleRect);
                }
              };

              _proto2.resizeWithBrowserSize = function resizeWithBrowserSize(enabled) {
                if (enabled) {
                  if (!this._resizeWithBrowserSize) {
                    this._resizeWithBrowserSize = true;
                    system.onViewResize(this._resizeEvent);
                    system.onOrientationChange(this._orientationChange);
                  }
                } else if (this._resizeWithBrowserSize) {
                  this._resizeWithBrowserSize = false;
                  system.offViewResize(this._resizeEvent);
                  system.offOrientationChange(this._orientationChange);
                }
              };

              _proto2.setResizeCallback = function setResizeCallback(callback) {
                if (typeof callback === 'function' || callback == null) {
                  this._resizeCallback = callback;
                }
              };

              _proto2.setOrientation = function setOrientation(orientation) {
                orientation &= legacyCC.macro.ORIENTATION_AUTO;

                if (orientation && this._orientation !== orientation) {
                  this._orientation = orientation;
                }
              };

              _proto2.adjustViewportMeta = function adjustViewportMeta(enabled) {
                this._isAdjustViewport = enabled;
              };

              _proto2.enableRetina = function enableRetina(enabled) {
                this._retinaEnabled = !!enabled;
              };

              _proto2.isRetinaEnabled = function isRetinaEnabled() {
                return this._retinaEnabled;
              };

              _proto2.enableAutoFullScreen = function enableAutoFullScreen(enabled) {
                if (enabled && enabled !== this._autoFullScreen && legacyCC.sys.isMobile && system.browserType !== BrowserType.WECHAT) {
                  this._autoFullScreen = true;
                  legacyCC.screen.autoFullScreen(legacyCC.game.frame);
                } else {
                  this._autoFullScreen = false;
                }
              };

              _proto2.isAutoFullScreenEnabled = function isAutoFullScreenEnabled() {
                return this._autoFullScreen;
              };

              _proto2.setCanvasSize = function setCanvasSize(width, height) {
                var canvas = legacyCC.game.canvas;
                var container = legacyCC.game.container;
                this._devicePixelRatio = window.devicePixelRatio;
                canvas.width = sys.windowPixelResolution.width;
                canvas.height = sys.windowPixelResolution.height;
                canvas.style.width = width + "px";
                canvas.style.height = height + "px";
                container.style.width = width + "px";
                container.style.height = height + "px";

                this._resizeEvent();
              };

              _proto2.getCanvasSize = function getCanvasSize() {
                return new Size(legacyCC.game.canvas.width, legacyCC.game.canvas.height);
              };

              _proto2.getFrameSize = function getFrameSize() {
                return new Size(this._frameSize.width, this._frameSize.height);
              };

              _proto2.setFrameSize = function setFrameSize(width, height) {
                this._frameSize.width = width;
                this._frameSize.height = height;
                legacyCC.game.frame.style.width = width + "px";
                legacyCC.game.frame.style.height = height + "px";

                this._resizeEvent();
              };

              _proto2.getVisibleSize = function getVisibleSize() {
                return new Size(this._visibleRect.width, this._visibleRect.height);
              };

              _proto2.getVisibleSizeInPixel = function getVisibleSizeInPixel() {
                return new Size(this._visibleRect.width * this._scaleX, this._visibleRect.height * this._scaleY);
              };

              _proto2.getVisibleOrigin = function getVisibleOrigin() {
                return new Vec2(this._visibleRect.x, this._visibleRect.y);
              };

              _proto2.getVisibleOriginInPixel = function getVisibleOriginInPixel() {
                return new Vec2(this._visibleRect.x * this._scaleX, this._visibleRect.y * this._scaleY);
              };

              _proto2.getResolutionPolicy = function getResolutionPolicy() {
                return this._resolutionPolicy;
              };

              _proto2.setResolutionPolicy = function setResolutionPolicy(resolutionPolicy) {
                if (resolutionPolicy instanceof ResolutionPolicy) {
                  this._resolutionPolicy = resolutionPolicy;
                } else {
                  var _locPolicy = ResolutionPolicy;

                  if (resolutionPolicy === _locPolicy.EXACT_FIT) {
                    this._resolutionPolicy = this._rpExactFit;
                  }

                  if (resolutionPolicy === _locPolicy.SHOW_ALL) {
                    this._resolutionPolicy = this._rpShowAll;
                  }

                  if (resolutionPolicy === _locPolicy.NO_BORDER) {
                    this._resolutionPolicy = this._rpNoBorder;
                  }

                  if (resolutionPolicy === _locPolicy.FIXED_HEIGHT) {
                    this._resolutionPolicy = this._rpFixedHeight;
                  }

                  if (resolutionPolicy === _locPolicy.FIXED_WIDTH) {
                    this._resolutionPolicy = this._rpFixedWidth;
                  }
                }
              };

              _proto2.setDesignResolutionSize = function setDesignResolutionSize(width, height, resolutionPolicy) {
                if (!(width > 0 && height > 0)) {
                  errorID(2200);
                  return;
                }

                this.setResolutionPolicy(resolutionPolicy);
                var policy = this._resolutionPolicy;

                if (policy) {
                  policy.preApply(this);
                }

                if (legacyCC.sys.isMobile) {
                  this._adjustViewportMeta();
                }

                this._orientationChanging = true;

                if (!this._resizing) {
                  this._initFrameSize();
                }

                if (!policy) {
                  logID(2201);
                  return;
                }

                this._originalDesignResolutionSize.width = this._designResolutionSize.width = width;
                this._originalDesignResolutionSize.height = this._designResolutionSize.height = height;
                var result = policy.apply(this, this._designResolutionSize);

                if (result.scale && result.scale.length === 2) {
                  this._scaleX = result.scale[0];
                  this._scaleY = result.scale[1];
                }

                if (result.viewport) {
                  var vp = this._viewportRect;
                  var vb = this._visibleRect;
                  var rv = result.viewport;
                  vp.x = rv.x;
                  vp.y = rv.y;
                  vp.width = rv.width;
                  vp.height = rv.height;
                  vb.x = 0;
                  vb.y = 0;
                  vb.width = rv.width / this._scaleX;
                  vb.height = rv.height / this._scaleY;
                }

                policy.postApply(this);
                legacyCC.winSize.width = this._visibleRect.width;
                legacyCC.winSize.height = this._visibleRect.height;

                if (visibleRect) {
                  visibleRect.init(this._visibleRect);
                }

                this.emit('design-resolution-changed');
              };

              _proto2.getDesignResolutionSize = function getDesignResolutionSize() {
                return new Size(this._designResolutionSize.width, this._designResolutionSize.height);
              };

              _proto2.setRealPixelResolution = function setRealPixelResolution(width, height, resolutionPolicy) {
                {
                  this._setViewportMeta({
                    width: width
                  }, true);

                  document.documentElement.style.width = width + "px";
                  document.body.style.width = width + "px";
                  document.body.style.left = '0px';
                  document.body.style.top = '0px';
                }

                this.setDesignResolutionSize(width, height, resolutionPolicy);
              };

              _proto2.getViewportRect = function getViewportRect() {
                return this._viewportRect;
              };

              _proto2.getScaleX = function getScaleX() {
                return this._scaleX;
              };

              _proto2.getScaleY = function getScaleY() {
                return this._scaleY;
              };

              _proto2.getDevicePixelRatio = function getDevicePixelRatio() {
                return this._devicePixelRatio;
              };

              _proto2.convertToLocationInView = function convertToLocationInView(tx, ty, relatedPos, out) {
                var result = out || new Vec2();
                var x = this._devicePixelRatio * (tx - relatedPos.left);
                var y = this._devicePixelRatio * (relatedPos.top + relatedPos.height - ty);

                if (this._isRotated) {
                  result.x = legacyCC.game.canvas.width - y;
                  result.y = x;
                } else {
                  result.x = x;
                  result.y = y;
                }

                if (legacyCC.GAME_VIEW) {
                  result.x /= legacyCC.gameView.canvas.width / legacyCC.game.canvas.width;
                  result.y /= legacyCC.gameView.canvas.height / legacyCC.game.canvas.height;
                }

                return result;
              };

              _proto2._convertPointWithScale = function _convertPointWithScale(point) {
                var viewport = this._viewportRect;
                point.x = (point.x - viewport.x) / this._scaleX;
                point.y = (point.y - viewport.y) / this._scaleY;
              };

              _proto2._resizeEvent = function _resizeEvent() {
                var _view = legacyCC.view;
                var prevFrameW = _view._frameSize.width;
                var prevFrameH = _view._frameSize.height;
                var prevRotated = _view._isRotated;

                if (legacyCC.sys.isMobile) {
                  var containerStyle = legacyCC.game.container.style;
                  var margin = containerStyle.margin;
                  containerStyle.margin = '0';
                  containerStyle.display = 'none';

                  _view._initFrameSize();

                  containerStyle.margin = margin;
                  containerStyle.display = 'block';
                } else {
                  _view._initFrameSize();
                }

                if ( !_view._orientationChanging && _view._isRotated === prevRotated && _view._frameSize.width === prevFrameW && _view._frameSize.height === prevFrameH) {
                  return;
                }

                var width = _view._originalDesignResolutionSize.width;
                var height = _view._originalDesignResolutionSize.height;
                _view._resizing = true;

                if (width > 0) {
                  _view.setDesignResolutionSize(width, height, _view._resolutionPolicy);
                }

                _view._resizing = false;

                _view.emit('canvas-resize');

                if (_view._resizeCallback) {
                  _view._resizeCallback.call();
                }
              };

              _proto2._orientationChange = function _orientationChange() {
                legacyCC.view._orientationChanging = true;

                legacyCC.view._resizeEvent();
              };

              _proto2._initFrameSize = function _initFrameSize() {
                var locFrameSize = this._frameSize;

                var w = __BrowserGetter.availWidth(legacyCC.game.frame);

                var h = __BrowserGetter.availHeight(legacyCC.game.frame);

                var isLandscape = w >= h;

                if ( !legacyCC.sys.isMobile || isLandscape && this._orientation & legacyCC.macro.ORIENTATION_LANDSCAPE || !isLandscape && this._orientation & legacyCC.macro.ORIENTATION_PORTRAIT) {
                  locFrameSize.width = w;
                  locFrameSize.height = h;
                  legacyCC.game.container.style['-webkit-transform'] = 'rotate(0deg)';
                  legacyCC.game.container.style.transform = 'rotate(0deg)';
                  this._isRotated = false;
                } else {
                  locFrameSize.width = h;
                  locFrameSize.height = w;
                  legacyCC.game.container.style['-webkit-transform'] = 'rotate(90deg)';
                  legacyCC.game.container.style.transform = 'rotate(90deg)';
                  legacyCC.game.container.style['-webkit-transform-origin'] = '0px 0px 0px';
                  legacyCC.game.container.style.transformOrigin = '0px 0px 0px';
                  this._isRotated = true;
                  legacyCC.game.canvas.style['-webkit-transform'] = 'translateZ(0px)';
                  legacyCC.game.canvas.style.transform = 'translateZ(0px)';
                }

                if (this._orientationChanging) {
                  setTimeout(function () {
                    legacyCC.view._orientationChanging = false;
                  }, 1000);
                }
              };

              _proto2._adjustSizeKeepCanvasSize = function _adjustSizeKeepCanvasSize() {
                var designWidth = this._originalDesignResolutionSize.width;
                var designHeight = this._originalDesignResolutionSize.height;

                if (designWidth > 0) {
                  this.setDesignResolutionSize(designWidth, designHeight, this._resolutionPolicy);
                }
              };

              _proto2._setViewportMeta = function _setViewportMeta(metas, overwrite) {
                var vp = document.getElementById('cocosMetaElement');

                if (vp && overwrite) {
                  document.head.removeChild(vp);
                }

                var elems = document.getElementsByName('viewport');
                var currentVP = elems ? elems[0] : null;
                var content;
                var key;
                var pattern;
                content = currentVP ? currentVP.content : '';
                vp = vp || document.createElement('meta');
                vp.id = 'cocosMetaElement';
                vp.name = 'viewport';
                vp.content = '';

                for (key in metas) {
                  if (content.indexOf(key) === -1) {
                    content += "," + key + "=" + metas[key];
                  } else if (overwrite) {
                    pattern = new RegExp(key + "s*=s*[^,]+");
                    content = content.replace(pattern, key + "=" + metas[key]);
                  }
                }

                if (/^,/.test(content)) {
                  content = content.substr(1);
                }

                vp.content = content;

                if (currentVP) {
                  currentVP.content = content;
                }

                document.head.appendChild(vp);
              };

              _proto2._adjustViewportMeta = function _adjustViewportMeta() {
                if (this._isAdjustViewport && !JSB && !RUNTIME_BASED && !MINIGAME) {
                  this._setViewportMeta(__BrowserGetter.meta, false);

                  this._isAdjustViewport = false;
                }
              };

              _proto2._convertMouseToLocation = function _convertMouseToLocation(in_out_point, relatedPos) {
                in_out_point.x = this._devicePixelRatio * (in_out_point.x - relatedPos.left);
                in_out_point.y = this._devicePixelRatio * (relatedPos.top + relatedPos.height - in_out_point.y);

                if (legacyCC.GAME_VIEW) {
                  in_out_point.x /= legacyCC.gameView.canvas.width / legacyCC.game.canvas.width;
                  in_out_point.y /= legacyCC.gameView.canvas.height / legacyCC.game.canvas.height;
                }
              };

              _proto2._convertTouchWidthScale = function _convertTouchWidthScale(selTouch) {
                var viewport = this._viewportRect;
                var scaleX = this._scaleX;
                var scaleY = this._scaleY;
                selTouch._point.x = (selTouch._point.x - viewport.x) / scaleX;
                selTouch._point.y = (selTouch._point.y - viewport.y) / scaleY;
                selTouch._prevPoint.x = (selTouch._prevPoint.x - viewport.x) / scaleX;
                selTouch._prevPoint.y = (selTouch._prevPoint.y - viewport.y) / scaleY;
              };

              _proto2._convertTouchesWithScale = function _convertTouchesWithScale(touches) {
                var viewport = this._viewportRect;
                var scaleX = this._scaleX;
                var scaleY = this._scaleY;
                var selPoint;
                var selPrePoint;

                for (var i = 0; i < touches.length; i++) {
                  var selTouch = touches[i];
                  selPoint = selTouch._point;
                  selPrePoint = selTouch._prevPoint;
                  selPoint.x = (selPoint.x - viewport.x) / scaleX;
                  selPoint.y = (selPoint.y - viewport.y) / scaleY;
                  selPrePoint.x = (selPrePoint.x - viewport.x) / scaleX;
                  selPrePoint.y = (selPrePoint.y - viewport.y) / scaleY;
                }
              };

              return View;
            }(EventTarget));
            View.instance = void 0;

            var ContainerStrategy = function () {
              function ContainerStrategy() {
                this.name = 'ContainerStrategy';
              }

              var _proto3 = ContainerStrategy.prototype;

              _proto3.preApply = function preApply(_view) {};

              _proto3.apply = function apply(_view, designedResolution) {};

              _proto3.postApply = function postApply(_view) {};

              _proto3._setupContainer = function _setupContainer(_view, w, h) {
                var locCanvas = legacyCC.game.canvas;
                var locContainer = legacyCC.game.container;

                if (system.os === OS.ANDROID || system.os === OS.OHOS) {
                  document.body.style.width = (_view._isRotated ? h : w) + "px";
                  document.body.style.height = (_view._isRotated ? w : h) + "px";
                }

                locContainer.style.width = locCanvas.style.width = w + "px";
                locContainer.style.height = locCanvas.style.height = h + "px";
                _view._devicePixelRatio = 1;

                if (_view.isRetinaEnabled()) {
                  _view._devicePixelRatio = Math.min(_view._maxPixelRatio, window.devicePixelRatio || 1);
                }

                {
                  locCanvas.width = w * _view._devicePixelRatio;
                  locCanvas.height = h * _view._devicePixelRatio;
                }
              };

              _proto3._fixContainer = function _fixContainer() {
                document.body.insertBefore(legacyCC.game.container, document.body.firstChild);
                var bs = document.body.style;
                bs.width = window.innerWidth + "px";
                bs.height = window.innerHeight + "px";
                bs.overflow = 'hidden';
                var contStyle = legacyCC.game.container.style;
                contStyle.position = 'fixed';
                contStyle.left = contStyle.top = '0px';
                document.body.scrollTop = 0;
              };

              return ContainerStrategy;
            }();

            ContainerStrategy.EQUAL_TO_FRAME = void 0;
            ContainerStrategy.PROPORTION_TO_FRAME = void 0;

            var ContentStrategy = function () {
              function ContentStrategy() {
                this.name = 'ContentStrategy';
                this._result = void 0;
                this._result = {
                  scale: [1, 1],
                  viewport: null
                };
              }

              var _proto4 = ContentStrategy.prototype;

              _proto4.preApply = function preApply(_view) {};

              _proto4.apply = function apply(_view, designedResolution) {
                return {
                  scale: [1, 1]
                };
              };

              _proto4.postApply = function postApply(_view) {};

              _proto4._buildResult = function _buildResult(containerW, containerH, contentW, contentH, scaleX, scaleY) {
                if (Math.abs(containerW - contentW) < 2) {
                  contentW = containerW;
                }

                if (Math.abs(containerH - contentH) < 2) {
                  contentH = containerH;
                }

                var viewport = new Rect(Math.round((containerW - contentW) / 2), Math.round((containerH - contentH) / 2), contentW, contentH);
                this._result.scale = [scaleX, scaleY];
                this._result.viewport = viewport;
                return this._result;
              };

              return ContentStrategy;
            }();

            ContentStrategy.EXACT_FIT = void 0;
            ContentStrategy.SHOW_ALL = void 0;
            ContentStrategy.NO_BORDER = void 0;
            ContentStrategy.FIXED_HEIGHT = void 0;
            ContentStrategy.FIXED_WIDTH = void 0;

            (function () {
              var EqualToFrame = function (_ContainerStrategy) {
                _inheritsLoose(EqualToFrame, _ContainerStrategy);

                function EqualToFrame() {
                  var _this2;

                  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                    args[_key] = arguments[_key];
                  }

                  _this2 = _ContainerStrategy.call.apply(_ContainerStrategy, [this].concat(args)) || this;
                  _this2.name = 'EqualToFrame';
                  return _this2;
                }

                var _proto5 = EqualToFrame.prototype;

                _proto5.apply = function apply(_view) {
                  var frameH = _view._frameSize.height;
                  var containerStyle = legacyCC.game.container.style;

                  this._setupContainer(_view, _view._frameSize.width, _view._frameSize.height);

                  if (_view._isRotated) {
                    containerStyle.margin = "0 0 0 " + frameH + "px";
                  } else {
                    containerStyle.margin = '0px';
                  }

                  containerStyle.padding = '0px';
                };

                return EqualToFrame;
              }(ContainerStrategy);

              var ProportionalToFrame = function (_ContainerStrategy2) {
                _inheritsLoose(ProportionalToFrame, _ContainerStrategy2);

                function ProportionalToFrame() {
                  var _this3;

                  for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
                    args[_key2] = arguments[_key2];
                  }

                  _this3 = _ContainerStrategy2.call.apply(_ContainerStrategy2, [this].concat(args)) || this;
                  _this3.name = 'ProportionalToFrame';
                  return _this3;
                }

                var _proto6 = ProportionalToFrame.prototype;

                _proto6.apply = function apply(_view, designedResolution) {
                  var frameW = _view._frameSize.width;
                  var frameH = _view._frameSize.height;
                  var containerStyle = legacyCC.game.container.style;
                  var designW = designedResolution.width;
                  var designH = designedResolution.height;
                  var scaleX = frameW / designW;
                  var scaleY = frameH / designH;
                  var containerW;
                  var containerH;

                  if (scaleX < scaleY) {
                    containerW = frameW;
                    containerH = designH * scaleX;
                  } else {
                    containerW = designW * scaleY;
                    containerH = frameH;
                  }

                  var offx = Math.round((frameW - containerW) / 2);
                  var offy = Math.round((frameH - containerH) / 2);
                  containerW = frameW - 2 * offx;
                  containerH = frameH - 2 * offy;

                  this._setupContainer(_view, containerW, containerH);

                  {
                    if (_view._isRotated) {
                      containerStyle.margin = "0 0 0 " + frameH + "px";
                    } else {
                      containerStyle.margin = '0px';
                    }

                    containerStyle.paddingLeft = offx + "px";
                    containerStyle.paddingRight = offx + "px";
                    containerStyle.paddingTop = offy + "px";
                    containerStyle.paddingBottom = offy + "px";
                  }
                };

                return ProportionalToFrame;
              }(ContainerStrategy);

              var _global = typeof window === 'undefined' ? global : window;

              var globalAdapter = _global.__globalAdapter;

              if (globalAdapter) {
                if (globalAdapter.adaptContainerStrategy) {
                  globalAdapter.adaptContainerStrategy(ContainerStrategy.prototype);
                }

                if (globalAdapter.adaptView) {
                  globalAdapter.adaptView(View.prototype);
                }
              }

              ContainerStrategy.EQUAL_TO_FRAME = new EqualToFrame();
              ContainerStrategy.PROPORTION_TO_FRAME = new ProportionalToFrame();

              var ExactFit = function (_ContentStrategy) {
                _inheritsLoose(ExactFit, _ContentStrategy);

                function ExactFit() {
                  var _this4;

                  for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
                    args[_key3] = arguments[_key3];
                  }

                  _this4 = _ContentStrategy.call.apply(_ContentStrategy, [this].concat(args)) || this;
                  _this4.name = 'ExactFit';
                  return _this4;
                }

                var _proto7 = ExactFit.prototype;

                _proto7.apply = function apply(_view, designedResolution) {
                  var containerW = legacyCC.game.canvas.width;
                  var containerH = legacyCC.game.canvas.height;
                  var scaleX = containerW / designedResolution.width;
                  var scaleY = containerH / designedResolution.height;
                  return this._buildResult(containerW, containerH, containerW, containerH, scaleX, scaleY);
                };

                return ExactFit;
              }(ContentStrategy);

              var ShowAll = function (_ContentStrategy2) {
                _inheritsLoose(ShowAll, _ContentStrategy2);

                function ShowAll() {
                  var _this5;

                  for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
                    args[_key4] = arguments[_key4];
                  }

                  _this5 = _ContentStrategy2.call.apply(_ContentStrategy2, [this].concat(args)) || this;
                  _this5.name = 'ShowAll';
                  return _this5;
                }

                var _proto8 = ShowAll.prototype;

                _proto8.apply = function apply(_view, designedResolution) {
                  var containerW = legacyCC.game.canvas.width;
                  var containerH = legacyCC.game.canvas.height;
                  var designW = designedResolution.width;
                  var designH = designedResolution.height;
                  var scaleX = containerW / designW;
                  var scaleY = containerH / designH;
                  var scale = 0;
                  var contentW;
                  var contentH;

                  if (scaleX < scaleY) {
                    scale = scaleX;
                    contentW = containerW;
                    contentH = designH * scale;
                  } else {
                    scale = scaleY;
                    contentW = designW * scale;
                    contentH = containerH;
                  }

                  return this._buildResult(containerW, containerH, contentW, contentH, scale, scale);
                };

                return ShowAll;
              }(ContentStrategy);

              var NoBorder = function (_ContentStrategy3) {
                _inheritsLoose(NoBorder, _ContentStrategy3);

                function NoBorder() {
                  var _this6;

                  for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
                    args[_key5] = arguments[_key5];
                  }

                  _this6 = _ContentStrategy3.call.apply(_ContentStrategy3, [this].concat(args)) || this;
                  _this6.name = 'NoBorder';
                  return _this6;
                }

                var _proto9 = NoBorder.prototype;

                _proto9.apply = function apply(_view, designedResolution) {
                  var containerW = legacyCC.game.canvas.width;
                  var containerH = legacyCC.game.canvas.height;
                  var designW = designedResolution.width;
                  var designH = designedResolution.height;
                  var scaleX = containerW / designW;
                  var scaleY = containerH / designH;
                  var scale;
                  var contentW;
                  var contentH;

                  if (scaleX < scaleY) {
                    scale = scaleY;
                    contentW = designW * scale;
                    contentH = containerH;
                  } else {
                    scale = scaleX;
                    contentW = containerW;
                    contentH = designH * scale;
                  }

                  return this._buildResult(containerW, containerH, contentW, contentH, scale, scale);
                };

                return NoBorder;
              }(ContentStrategy);

              var FixedHeight = function (_ContentStrategy4) {
                _inheritsLoose(FixedHeight, _ContentStrategy4);

                function FixedHeight() {
                  var _this7;

                  for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
                    args[_key6] = arguments[_key6];
                  }

                  _this7 = _ContentStrategy4.call.apply(_ContentStrategy4, [this].concat(args)) || this;
                  _this7.name = 'FixedHeight';
                  return _this7;
                }

                var _proto10 = FixedHeight.prototype;

                _proto10.apply = function apply(_view, designedResolution) {
                  var containerW = legacyCC.game.canvas.width;
                  var containerH = legacyCC.game.canvas.height;
                  var designH = designedResolution.height;
                  var scale = containerH / designH;
                  var contentW = containerW;
                  var contentH = containerH;
                  return this._buildResult(containerW, containerH, contentW, contentH, scale, scale);
                };

                return FixedHeight;
              }(ContentStrategy);

              var FixedWidth = function (_ContentStrategy5) {
                _inheritsLoose(FixedWidth, _ContentStrategy5);

                function FixedWidth() {
                  var _this8;

                  for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
                    args[_key7] = arguments[_key7];
                  }

                  _this8 = _ContentStrategy5.call.apply(_ContentStrategy5, [this].concat(args)) || this;
                  _this8.name = 'FixedWidth';
                  return _this8;
                }

                var _proto11 = FixedWidth.prototype;

                _proto11.apply = function apply(_view, designedResolution) {
                  var containerW = legacyCC.game.canvas.width;
                  var containerH = legacyCC.game.canvas.height;
                  var designW = designedResolution.width;
                  var scale = containerW / designW;
                  var contentW = containerW;
                  var contentH = containerH;
                  return this._buildResult(containerW, containerH, contentW, contentH, scale, scale);
                };

                return FixedWidth;
              }(ContentStrategy);

              ContentStrategy.EXACT_FIT = new ExactFit();
              ContentStrategy.SHOW_ALL = new ShowAll();
              ContentStrategy.NO_BORDER = new NoBorder();
              ContentStrategy.FIXED_HEIGHT = new FixedHeight();
              ContentStrategy.FIXED_WIDTH = new FixedWidth();
            })();

            var ResolutionPolicy = exports('ResolutionPolicy', function () {
              function ResolutionPolicy(containerStg, contentStg) {
                this.name = 'ResolutionPolicy';
                this._containerStrategy = void 0;
                this._contentStrategy = void 0;
                this._containerStrategy = null;
                this._contentStrategy = null;
                this.setContainerStrategy(containerStg);
                this.setContentStrategy(contentStg);
              }

              var _proto12 = ResolutionPolicy.prototype;

              _proto12.preApply = function preApply(_view) {
                this._containerStrategy.preApply(_view);

                this._contentStrategy.preApply(_view);
              };

              _proto12.apply = function apply(_view, designedResolution) {
                this._containerStrategy.apply(_view, designedResolution);

                return this._contentStrategy.apply(_view, designedResolution);
              };

              _proto12.postApply = function postApply(_view) {
                this._containerStrategy.postApply(_view);

                this._contentStrategy.postApply(_view);
              };

              _proto12.setContainerStrategy = function setContainerStrategy(containerStg) {
                if (containerStg instanceof ContainerStrategy) {
                  this._containerStrategy = containerStg;
                }
              };

              _proto12.setContentStrategy = function setContentStrategy(contentStg) {
                if (contentStg instanceof ContentStrategy) {
                  this._contentStrategy = contentStg;
                }
              };

              _createClass(ResolutionPolicy, [{
                key: "canvasSize",
                get: function get() {
                  return new Vec2(legacyCC.game.canvas.width, legacyCC.game.canvas.height);
                }
              }]);

              return ResolutionPolicy;
            }());
            ResolutionPolicy.EXACT_FIT = 0;
            ResolutionPolicy.NO_BORDER = 1;
            ResolutionPolicy.SHOW_ALL = 2;
            ResolutionPolicy.FIXED_HEIGHT = 3;
            ResolutionPolicy.FIXED_WIDTH = 4;
            ResolutionPolicy.UNKNOWN = 5;
            ResolutionPolicy.ContainerStrategy = ContainerStrategy;
            ResolutionPolicy.ContentStrategy = ContentStrategy;
            legacyCC.ResolutionPolicy = ResolutionPolicy;
            var view = exports('view', View.instance = legacyCC.view = new View());
            legacyCC.winSize = new Size();

            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'
            }]);
            replaceProperty(EventMouse, 'EventMouse', ['DOWN', 'UP', 'MOVE'].map(function (item) {
              return {
                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'
            }]);
            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'
            }]);
            replaceProperty(sys, 'sys', ['UNKNOWN', 'ENGLISH', 'CHINESE', 'FRENCH', 'ITALIAN', 'GERMAN', 'SPANISH', 'DUTCH', 'RUSSIAN', 'KOREAN', 'JAPANESE', 'HUNGARIAN', 'PORTUGUESE', 'ARABIC', 'NORWEGIAN', 'POLISH', 'TURKISH', 'UKRAINIAN', 'ROMANIAN', 'BULGARIAN'].map(function (item) {
              return {
                name: "LANGUAGE_" + item,
                newName: item,
                target: sys.Language,
                targetName: 'sys.Language'
              };
            }));
            replaceProperty(sys, 'sys', ['UNKNOWN', 'IOS', 'ANDROID', 'WINDOWS', 'LINUX', 'OSX'].map(function (item) {
              return {
                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(function (item) {
              return {
                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(function (item) {
              return {
                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(function (item) {
              return {
                name: item
              };
            }));

            var screen = exports('screen', {
              _supportsFullScreen: false,
              _onfullscreenchange: null,
              _onfullscreenerror: null,
              _preOnFullScreenError: null,
              _preOnTouch: null,
              _touchEvent: '',
              _fn: null,
              _fnMap: [['requestFullscreen', 'exitFullscreen', 'fullscreenchange', 'fullscreenEnabled', 'fullscreenElement'], ['requestFullScreen', 'exitFullScreen', 'fullScreenchange', 'fullScreenEnabled', 'fullScreenElement'], ['webkitRequestFullScreen', 'webkitCancelFullScreen', 'webkitfullscreenchange', 'webkitIsFullScreen', 'webkitCurrentFullScreenElement'], ['mozRequestFullScreen', 'mozCancelFullScreen', 'mozfullscreenchange', 'mozFullScreen', 'mozFullScreenElement'], ['msRequestFullscreen', 'msExitFullscreen', 'MSFullscreenChange', 'msFullscreenEnabled', 'msFullscreenElement']],
              init: function init() {
                this._fn = {};
                var i;
                var l;
                var val;
                var map = this._fnMap;
                var valL;

                for (i = 0, l = map.length; i < l; i++) {
                  val = map[i];

                  if (val && typeof document[val[1]] !== 'undefined') {
                    for (i = 0, valL = val.length; i < valL; i++) {
                      this._fn[map[0][i]] = val[i];
                    }

                    break;
                  }
                }

                this._supportsFullScreen = this._fn.requestFullscreen !== undefined;
                this._touchEvent = 'ontouchstart' in window ? 'touchstart' : 'mousedown';
              },

              get supportsFullScreen() {
                return this._supportsFullScreen;
              },

              fullScreen: function fullScreen() {
                if (!this._supportsFullScreen) {
                  return false;
                } else if (document[this._fn.fullscreenElement] === undefined || document[this._fn.fullscreenElement] === null) {
                  return false;
                } else {
                  return true;
                }
              },
              requestFullScreen: function requestFullScreen(element, onFullScreenChange, onFullScreenError) {
                if (!this._supportsFullScreen) {
                  return;
                }

                element = element || document.documentElement;

                if (onFullScreenChange) {
                  var eventName = this._fn.fullscreenchange;

                  if (this._onfullscreenchange) {
                    document.removeEventListener(eventName, this._onfullscreenchange);
                  }

                  this._onfullscreenchange = onFullScreenChange;
                  document.addEventListener(eventName, onFullScreenChange, false);
                }

                if (onFullScreenError) {
                  var _eventName = this._fn.fullscreenerror;

                  if (this._onfullscreenerror) {
                    document.removeEventListener(_eventName, this._onfullscreenerror);
                  }

                  this._onfullscreenerror = onFullScreenError;
                  document.addEventListener(_eventName, onFullScreenError, {
                    once: true
                  });
                }

                var requestPromise = element[this._fn.requestFullscreen]();

                if (window.Promise && requestPromise instanceof Promise) {
                  requestPromise["catch"](function (err) {});
                }

                return requestPromise;
              },
              exitFullScreen: function exitFullScreen() {
                var requestPromise;

                if (this.fullScreen()) {
                  requestPromise = document[this._fn.exitFullscreen]();
                  requestPromise["catch"](function (err) {});
                }

                return requestPromise;
              },
              autoFullScreen: function autoFullScreen(element, onFullScreenChange) {
                element = element || document.body;

                this._ensureFullScreen(element, onFullScreenChange);

                this.requestFullScreen(element, onFullScreenChange);
              },
              disableAutoFullScreen: function disableAutoFullScreen(element) {
                if (this._preOnTouch) {
                  var touchTarget = legacyCC.game.canvas || element;
                  var touchEventName = this._touchEvent;
                  touchTarget.removeEventListener(touchEventName, this._preOnTouch);
                  this._preOnTouch = null;
                }
              },
              _ensureFullScreen: function _ensureFullScreen(element, onFullScreenChange) {
                var _this = this;

                var touchTarget = legacyCC.game.canvas || element;
                var fullScreenErrorEventName = this._fn.fullscreenerror;
                var touchEventName = this._touchEvent;

                var onFullScreenError = function onFullScreenError() {
                  _this._preOnFullScreenError = null;

                  var onTouch = function onTouch() {
                    _this._preOnTouch = null;

                    _this.requestFullScreen(element, onFullScreenChange);
                  };

                  if (_this._preOnTouch) {
                    touchTarget.removeEventListener(touchEventName, _this._preOnTouch);
                  }

                  _this._preOnTouch = onTouch;
                  touchTarget.addEventListener(touchEventName, _this._preOnTouch, {
                    once: true
                  });
                };

                if (this._preOnFullScreenError) {
                  element.removeEventListener(fullScreenErrorEventName, this._preOnFullScreenError);
                }

                this._preOnFullScreenError = onFullScreenError;
                element.addEventListener(fullScreenErrorEventName, onFullScreenError, {
                  once: true
                });
              }
            });
            screen.init();
            legacyCC.screen = screen;

            var _dsInfo$1 = new DescriptorSetInfo(null);

            var MAX_PASS_COUNT = 8;
            var SubModel = function () {
              function SubModel() {
                this._device = null;
                this._passes = null;
                this._subMesh = null;
                this._patches = null;
                this._handle = NULL_HANDLE;
                this._priority = RenderPriority.DEFAULT;
                this._inputAssembler = null;
                this._descriptorSet = null;
              }

              var _proto = SubModel.prototype;

              _proto.initialize = function initialize(subMesh, passes, patches) {
                if (patches === void 0) {
                  patches = null;
                }

                this._device = legacyCC.director.root.device;
                this._subMesh = subMesh;
                this._patches = patches;
                this._passes = passes;
                this._handle = SubModelPool.alloc();

                this._flushPassInfo();

                if (passes[0].batchingScheme === BatchingSchemes.VB_MERGING) {
                  this._subMesh.genFlatBuffers();
                }

                _dsInfo$1.layout = passes[0].localSetLayout;
                var dsHandle = DSPool.alloc(this._device, _dsInfo$1);
                var iaHandle = IAPool.alloc(this._device, subMesh.iaInfo);
                SubModelPool.set(this._handle, SubModelView.PRIORITY, RenderPriority.DEFAULT);
                SubModelPool.set(this._handle, SubModelView.INPUT_ASSEMBLER, iaHandle);
                SubModelPool.set(this._handle, SubModelView.DESCRIPTOR_SET, dsHandle);
                SubModelPool.set(this._handle, SubModelView.SUB_MESH, subMesh.handle);
                this._inputAssembler = IAPool.get(iaHandle);
                this._descriptorSet = DSPool.get(dsHandle);
              };

              _proto.initPlanarShadowShader = function initPlanarShadowShader() {
                var pipeline = legacyCC.director.root.pipeline;
                var shadowInfo = pipeline.pipelineSceneData.shadows;
                var shaderHandle = shadowInfo.getPlanarShader(this._patches);
                SubModelPool.set(this._handle, SubModelView.PLANAR_SHADER, shaderHandle);
              };

              _proto.initPlanarShadowInstanceShader = function initPlanarShadowInstanceShader() {
                var pipeline = legacyCC.director.root.pipeline;
                var shadowInfo = pipeline.pipelineSceneData.shadows;
                var shaderHandle = shadowInfo.getPlanarInstanceShader(this._patches);
                SubModelPool.set(this._handle, SubModelView.PLANAR_INSTANCE_SHADER, shaderHandle);
              };

              _proto.destroy = function destroy() {
                DSPool.free(SubModelPool.get(this._handle, SubModelView.DESCRIPTOR_SET));
                IAPool.free(SubModelPool.get(this._handle, SubModelView.INPUT_ASSEMBLER));
                SubModelPool.free(this._handle);
                this._descriptorSet = null;
                this._inputAssembler = null;
                this._priority = RenderPriority.DEFAULT;
                this._handle = NULL_HANDLE;
                this._patches = null;
                this._subMesh = null;
                this._passes = null;
              };

              _proto.update = function update() {
                for (var i = 0; i < this._passes.length; ++i) {
                  var pass = this._passes[i];
                  pass.update();
                }

                this._descriptorSet.update();
              };

              _proto.onPipelineStateChanged = function onPipelineStateChanged() {
                var passes = this._passes;

                if (!passes) {
                  return;
                }

                for (var i = 0; i < passes.length; i++) {
                  var pass = passes[i];
                  pass.beginChangeStatesSilently();
                  pass.tryCompile();
                  pass.endChangeStatesSilently();
                }

                this._flushPassInfo();
              };

              _proto.onMacroPatchesStateChanged = function onMacroPatchesStateChanged(patches) {
                this._patches = patches;
                var passes = this._passes;

                if (!passes) {
                  return;
                }

                for (var i = 0; i < passes.length; i++) {
                  var pass = passes[i];
                  pass.beginChangeStatesSilently();
                  pass.tryCompile();
                  pass.endChangeStatesSilently();
                }

                this._flushPassInfo();
              };

              _proto._flushPassInfo = function _flushPassInfo() {
                var passes = this._passes;

                if (!passes) {
                  return;
                }

                SubModelPool.set(this._handle, SubModelView.PASS_COUNT, passes.length);
                var passOffset = SubModelView.PASS_0;
                var shaderOffset = SubModelView.SHADER_0;

                for (var i = 0; i < passes.length; i++, passOffset++, shaderOffset++) {
                  SubModelPool.set(this._handle, passOffset, passes[i].handle);
                  SubModelPool.set(this._handle, shaderOffset, passes[i].getShaderVariant(this._patches));
                }
              };

              _createClass(SubModel, [{
                key: "passes",
                get: function get() {
                  return this._passes;
                },
                set: function set(passes) {
                  var passLengh = passes.length;

                  if (passLengh > MAX_PASS_COUNT) {
                    errorID(12004, MAX_PASS_COUNT);
                    return;
                  }

                  this._passes = passes;

                  this._flushPassInfo();

                  if (this._descriptorSet) {
                    DSPool.free(SubModelPool.get(this._handle, SubModelView.DESCRIPTOR_SET));
                    _dsInfo$1.layout = passes[0].localSetLayout;
                    var dsHandle = DSPool.alloc(this._device, _dsInfo$1);
                    SubModelPool.set(this._handle, SubModelView.DESCRIPTOR_SET, dsHandle);
                    this._descriptorSet = DSPool.get(dsHandle);
                  }
                }
              }, {
                key: "subMesh",
                get: function get() {
                  return this._subMesh;
                },
                set: function set(subMesh) {
                  this._subMesh = subMesh;

                  this._inputAssembler.destroy();

                  this._inputAssembler.initialize(subMesh.iaInfo);

                  if (this._passes[0].batchingScheme === BatchingSchemes.VB_MERGING) {
                    this._subMesh.genFlatBuffers();
                  }

                  SubModelPool.set(this._handle, SubModelView.SUB_MESH, subMesh.handle);
                }
              }, {
                key: "priority",
                get: function get() {
                  return this._priority;
                },
                set: function set(val) {
                  this._priority = val;
                  SubModelPool.set(this._handle, SubModelView.PRIORITY, val);
                }
              }, {
                key: "handle",
                get: function get() {
                  return this._handle;
                }
              }, {
                key: "inputAssembler",
                get: function get() {
                  return this._inputAssembler;
                }
              }, {
                key: "descriptorSet",
                get: function get() {
                  return this._descriptorSet;
                }
              }, {
                key: "patches",
                get: function get() {
                  return this._patches;
                }
              }, {
                key: "planarShaderHandle",
                get: function get() {
                  return SubModelPool.get(this._handle, SubModelView.PLANAR_SHADER);
                }
              }, {
                key: "planarInstanceShaderHandle",
                get: function get() {
                  return SubModelPool.get(this._handle, SubModelView.PLANAR_INSTANCE_SHADER);
                }
              }]);

              return SubModel;
            }();

            var AttrPool = new ObjectPool(PoolType.ATTRIBUTE, function (_, obj) {
              return obj || new Attribute();
            });
            var m4_1$1 = new Mat4();

            var _subModelPool = new Pool$1(function () {
              return new SubModel();
            }, 32);

            var shadowMapPatches = [{
              name: 'CC_RECEIVE_SHADOW',
              value: true
            }];
            var ModelType;

            (function (ModelType) {
              ModelType[ModelType["DEFAULT"] = 0] = "DEFAULT";
              ModelType[ModelType["SKINNING"] = 1] = "SKINNING";
              ModelType[ModelType["BAKED_SKINNING"] = 2] = "BAKED_SKINNING";
              ModelType[ModelType["BATCH_2D"] = 3] = "BATCH_2D";
              ModelType[ModelType["PARTICLE_BATCH"] = 4] = "PARTICLE_BATCH";
              ModelType[ModelType["LINE"] = 5] = "LINE";
            })(ModelType || (ModelType = {}));

            function uploadMat4AsVec4x3(mat, v1, v2, v3) {
              v1[0] = mat.m00;
              v1[1] = mat.m01;
              v1[2] = mat.m02;
              v1[3] = mat.m12;
              v2[0] = mat.m04;
              v2[1] = mat.m05;
              v2[2] = mat.m06;
              v2[3] = mat.m13;
              v3[0] = mat.m08;
              v3[1] = mat.m09;
              v3[2] = mat.m10;
              v3[3] = mat.m14;
            }

            var lightmapSamplerHash = genSamplerHash([Filter.LINEAR, Filter.LINEAR, Filter.NONE, Address.CLAMP, Address.CLAMP, Address.CLAMP]);
            var lightmapSamplerWithMipHash = genSamplerHash([Filter.LINEAR, Filter.LINEAR, Filter.LINEAR, Address.CLAMP, Address.CLAMP, Address.CLAMP]);
            var Model = function () {
              function Model() {
                this.type = ModelType.DEFAULT;
                this.scene = null;
                this.isDynamicBatching = false;
                this.instancedAttributes = {
                  buffer: null,
                  views: [],
                  attributes: []
                };
                this._enabled = true;
                this._worldBounds = null;
                this._modelBounds = null;
                this._subModels = [];
                this._node = null;
                this._transform = null;
                this._visFlags = Layers.Enum.NONE;
                this._device = void 0;
                this._inited = false;
                this._descriptorSetCount = 1;
                this._updateStamp = -1;
                this._transformUpdated = true;
                this._handle = NULL_HANDLE;
                this._hWorldBounds = NULL_HANDLE;
                this._localData = new Float32Array(UBOLocal.COUNT);
                this._localBuffer = null;
                this._instMatWorldIdx = -1;
                this._lightmap = null;
                this._lightmapUVParam = new Vec4();
                this._device = legacyCC.director.root.device;
              }

              var _proto = Model.prototype;

              _proto.initialize = function initialize() {
                if (!this._inited) {
                  this._handle = ModelPool.alloc();
                  var hSubModelArray = SubModelArrayPool.alloc();
                  var hInstancedAttrArray = AttributeArrayPool.alloc();
                  ModelPool.set(this._handle, ModelView.INSTANCED_ATTR_ARRAY, hInstancedAttrArray);
                  ModelPool.set(this._handle, ModelView.SUB_MODEL_ARRAY, hSubModelArray);
                  ModelPool.set(this._handle, ModelView.VIS_FLAGS, Layers.Enum.NONE);
                  ModelPool.set(this._handle, ModelView.ENABLED, 1);
                  ModelPool.set(this._handle, ModelView.RECEIVE_SHADOW, 1);
                  ModelPool.set(this._handle, ModelView.CAST_SHADOW, 0);
                  this._inited = true;
                }
              };

              _proto.destroy = function destroy() {
                var subModels = this._subModels;

                for (var i = 0; i < subModels.length; i++) {
                  var subModel = this._subModels[i];
                  subModel.destroy();

                  _subModelPool.free(subModel);
                }

                if (this._localBuffer) {
                  this._localBuffer.destroy();

                  this._localBuffer = null;
                }

                this._worldBounds = null;
                this._modelBounds = null;
                this._subModels.length = 0;
                this._inited = false;
                this._transformUpdated = true;
                this._transform = null;
                this._node = null;
                this.isDynamicBatching = false;

                if (this._handle) {
                  var hSubModelArray = ModelPool.get(this._handle, ModelView.SUB_MODEL_ARRAY);
                  if (hSubModelArray) SubModelArrayPool.free(hSubModelArray);
                  var hOldBuffer = ModelPool.get(this._handle, ModelView.INSTANCED_BUFFER);
                  if (hOldBuffer) RawBufferPool.free(hOldBuffer);
                  var hAttrArray = ModelPool.get(this._handle, ModelView.INSTANCED_ATTR_ARRAY);
                  if (hAttrArray) freeHandleArray(hAttrArray, AttributeArrayPool, AttrPool);
                  ModelPool.free(this._handle);
                  this._handle = NULL_HANDLE;
                }

                if (this._hWorldBounds) {
                  AABBPool.free(this._hWorldBounds);
                  this._hWorldBounds = NULL_HANDLE;
                }
              };

              _proto.attachToScene = function attachToScene(scene) {
                this.scene = scene;
              };

              _proto.detachFromScene = function detachFromScene() {
                this.scene = null;
              };

              _proto.updateTransform = function updateTransform(stamp) {
                var node = this.transform;

                if (node.hasChangedFlags || node._dirtyFlags) {
                  node.updateWorldTransform();
                  this._transformUpdated = true;
                  var worldBounds = this._worldBounds;

                  if (this._modelBounds && worldBounds) {
                    this._modelBounds.transform(node._mat, node._pos, node._rot, node._scale, worldBounds);

                    AABBPool.setVec3(this._hWorldBounds, AABBView.CENTER, worldBounds.center);
                    AABBPool.setVec3(this._hWorldBounds, AABBView.HALF_EXTENSION, worldBounds.halfExtents);
                  }
                }
              };

              _proto.updateWorldBound = function updateWorldBound() {
                var node = this.transform;

                if (node !== null) {
                  node.updateWorldTransform();
                  this._transformUpdated = true;
                  var worldBounds = this._worldBounds;

                  if (this._modelBounds && worldBounds) {
                    this._modelBounds.transform(node._mat, node._pos, node._rot, node._scale, worldBounds);

                    AABBPool.setVec3(this._hWorldBounds, AABBView.CENTER, worldBounds.center);
                    AABBPool.setVec3(this._hWorldBounds, AABBView.HALF_EXTENSION, worldBounds.halfExtents);
                  }
                }
              };

              _proto.updateUBOs = function updateUBOs(stamp) {
                var subModels = this._subModels;

                for (var i = 0; i < subModels.length; i++) {
                  subModels[i].update();
                }

                this._updateStamp = stamp;

                if (!this._transformUpdated) {
                  return;
                }

                this._transformUpdated = false;
                var worldMatrix = this.transform._mat;
                var idx = this._instMatWorldIdx;

                if (idx >= 0) {
                  var attrs = this.instancedAttributes.views;
                  uploadMat4AsVec4x3(worldMatrix, attrs[idx], attrs[idx + 1], attrs[idx + 2]);
                } else if (this._localBuffer) {
                  Mat4.toArray(this._localData, worldMatrix, UBOLocal.MAT_WORLD_OFFSET);
                  Mat4.inverseTranspose(m4_1$1, worldMatrix);
                  Mat4.toArray(this._localData, m4_1$1, UBOLocal.MAT_WORLD_IT_OFFSET);

                  this._localBuffer.update(this._localData);
                }
              };

              _proto.createBoundingShape = function createBoundingShape(minPos, maxPos) {
                if (!minPos || !maxPos) {
                  return;
                }

                this._modelBounds = AABB.fromPoints(AABB.create(), minPos, maxPos);
                this._worldBounds = AABB.clone(this._modelBounds);

                if (this._hWorldBounds === NULL_HANDLE) {
                  this._hWorldBounds = AABBPool.alloc();
                  ModelPool.set(this._handle, ModelView.WORLD_BOUNDS, this._hWorldBounds);
                }

                AABBPool.setVec3(this._hWorldBounds, AABBView.CENTER, this._worldBounds.center);
                AABBPool.setVec3(this._hWorldBounds, AABBView.HALF_EXTENSION, this._worldBounds.halfExtents);
              };

              _proto.initSubModel = function initSubModel(idx, subMeshData, mat) {
                this.initialize();
                var isNewSubModel = false;

                if (this._subModels[idx] == null) {
                  this._subModels[idx] = _subModelPool.alloc();
                  isNewSubModel = true;
                } else {
                  this._subModels[idx].destroy();
                }

                this._subModels[idx].initialize(subMeshData, mat.passes, this.getMacroPatches(idx));

                this._subModels[idx].initPlanarShadowShader();

                this._subModels[idx].initPlanarShadowInstanceShader();

                this._updateAttributesAndBinding(idx);

                if (isNewSubModel) {
                  var hSubModelArray = ModelPool.get(this._handle, ModelView.SUB_MODEL_ARRAY);
                  SubModelArrayPool.assign(hSubModelArray, idx, this._subModels[idx].handle);
                }
              };

              _proto.setSubModelMesh = function setSubModelMesh(idx, subMesh) {
                if (!this._subModels[idx]) {
                  return;
                }

                this._subModels[idx].subMesh = subMesh;
              };

              _proto.setSubModelMaterial = function setSubModelMaterial(idx, mat) {
                if (!this._subModels[idx]) {
                  return;
                }

                this._subModels[idx].passes = mat.passes;

                this._updateAttributesAndBinding(idx);
              };

              _proto.onGlobalPipelineStateChanged = function onGlobalPipelineStateChanged() {
                var subModels = this._subModels;

                for (var i = 0; i < subModels.length; i++) {
                  subModels[i].onPipelineStateChanged();
                }
              };

              _proto.onMacroPatchesStateChanged = function onMacroPatchesStateChanged() {
                var subModels = this._subModels;

                for (var i = 0; i < subModels.length; i++) {
                  subModels[i].onMacroPatchesStateChanged(this.getMacroPatches(i));
                }
              };

              _proto.updateLightingmap = function updateLightingmap(texture, uvParam) {
                Vec4.toArray(this._localData, uvParam, UBOLocal.LIGHTINGMAP_UVPARAM);
                this._lightmap = texture;
                this._lightmapUVParam = uvParam;

                if (texture === null) {
                  texture = builtinResMgr.get('empty-texture');
                }

                var gfxTexture = texture.getGFXTexture();

                if (gfxTexture) {
                  var sampler = samplerLib.getSampler(this._device, texture.mipmaps.length > 1 ? lightmapSamplerWithMipHash : lightmapSamplerHash);
                  var subModels = this._subModels;

                  for (var i = 0; i < subModels.length; i++) {
                    var descriptorSet = subModels[i].descriptorSet;
                    descriptorSet.bindTexture(UNIFORM_LIGHTMAP_TEXTURE_BINDING, gfxTexture);
                    descriptorSet.bindSampler(UNIFORM_LIGHTMAP_TEXTURE_BINDING, sampler);
                    descriptorSet.update();
                  }
                }
              };

              _proto.getMacroPatches = function getMacroPatches(subModelIndex) {
                return this.receiveShadow ? shadowMapPatches : null;
              };

              _proto._updateAttributesAndBinding = function _updateAttributesAndBinding(subModelIndex) {
                var subModel = this._subModels[subModelIndex];

                if (!subModel) {
                  return;
                }

                this._initLocalDescriptors(subModelIndex);

                this._updateLocalDescriptors(subModelIndex, subModel.descriptorSet);

                var shader = ShaderPool.get(SubModelPool.get(subModel.handle, SubModelView.SHADER_0));

                this._updateInstancedAttributes(shader.attributes, subModel.passes[0]);
              };

              _proto._getInstancedAttributeIndex = function _getInstancedAttributeIndex(name) {
                var attributes = this.instancedAttributes.attributes;

                for (var i = 0; i < attributes.length; i++) {
                  if (attributes[i].name === name) {
                    return i;
                  }
                }

                return -1;
              };

              _proto._updateInstancedAttributes = function _updateInstancedAttributes(attributes, pass) {
                if (!pass.device.hasFeature(Feature.INSTANCED_ARRAYS)) {
                  return;
                }

                var hOldBuffer = ModelPool.get(this._handle, ModelView.INSTANCED_BUFFER);
                if (hOldBuffer) RawBufferPool.free(hOldBuffer);
                var hAttrArray = ModelPool.get(this._handle, ModelView.INSTANCED_ATTR_ARRAY);
                if (hAttrArray) freeHandleArray(hAttrArray, AttributeArrayPool, AttrPool, false);
                var size = 0;

                for (var j = 0; j < attributes.length; j++) {
                  var attribute = attributes[j];

                  if (!attribute.isInstanced) {
                    continue;
                  }

                  size += FormatInfos[attribute.format].size;
                }

                var hBuffer = RawBufferPool.alloc(size);
                var buffer = RawBufferPool.getBuffer(hBuffer);
                ModelPool.set(this._handle, ModelView.INSTANCED_BUFFER, hBuffer);
                var attrs = this.instancedAttributes;
                attrs.buffer = new Uint8Array(buffer);
                attrs.views.length = attrs.attributes.length = 0;
                var offset = 0;

                for (var _j = 0; _j < attributes.length; _j++) {
                  var _attribute = attributes[_j];

                  if (!_attribute.isInstanced) {
                    continue;
                  }

                  var hAttr = AttrPool.alloc();
                  var attr = AttrPool.get(hAttr);
                  attr.format = _attribute.format;
                  attr.name = _attribute.name;
                  attr.isNormalized = _attribute.isNormalized;
                  attr.location = _attribute.location;
                  attrs.attributes.push(attr);
                  AttributeArrayPool.push(hAttrArray, hAttr);
                  var info = FormatInfos[_attribute.format];
                  attrs.views.push(new (getTypedArrayConstructor(info))(buffer, offset, info.count));
                  offset += info.size;
                }

                if (pass.batchingScheme === BatchingSchemes.INSTANCING) {
                  InstancedBuffer.get(pass).destroy();
                }

                this._instMatWorldIdx = this._getInstancedAttributeIndex(INST_MAT_WORLD);
                this._transformUpdated = true;
              };

              _proto._initLocalDescriptors = function _initLocalDescriptors(subModelIndex) {
                if (!this._localBuffer) {
                  this._localBuffer = this._device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, UBOLocal.SIZE, UBOLocal.SIZE));
                }
              };

              _proto._updateLocalDescriptors = function _updateLocalDescriptors(subModelIndex, descriptorSet) {
                if (this._localBuffer) descriptorSet.bindBuffer(UBOLocal.BINDING, this._localBuffer);
              };

              _createClass(Model, [{
                key: "subModels",
                get: function get() {
                  return this._subModels;
                }
              }, {
                key: "inited",
                get: function get() {
                  return this._inited;
                }
              }, {
                key: "worldBounds",
                get: function get() {
                  return this._worldBounds;
                }
              }, {
                key: "modelBounds",
                get: function get() {
                  return this._modelBounds;
                }
              }, {
                key: "localBuffer",
                get: function get() {
                  return this._localBuffer;
                }
              }, {
                key: "updateStamp",
                get: function get() {
                  return this._updateStamp;
                }
              }, {
                key: "isInstancingEnabled",
                get: function get() {
                  return this._instMatWorldIdx >= 0;
                }
              }, {
                key: "receiveShadow",
                get: function get() {
                  if (ModelPool.get(this._handle, ModelView.RECEIVE_SHADOW)) {
                    return true;
                  }

                  return false;
                },
                set: function set(val) {
                  ModelPool.set(this._handle, ModelView.RECEIVE_SHADOW, val ? 1 : 0);
                  this.onMacroPatchesStateChanged();
                }
              }, {
                key: "castShadow",
                get: function get() {
                  if (ModelPool.get(this._handle, ModelView.CAST_SHADOW)) {
                    return true;
                  }

                  return false;
                },
                set: function set(val) {
                  ModelPool.set(this._handle, ModelView.CAST_SHADOW, val ? 1 : 0);
                }
              }, {
                key: "handle",
                get: function get() {
                  return this._handle;
                }
              }, {
                key: "node",
                get: function get() {
                  return this._node;
                },
                set: function set(n) {
                  this._node = n;
                  ModelPool.set(this._handle, ModelView.NODE, n.handle);
                }
              }, {
                key: "transform",
                get: function get() {
                  return this._transform;
                },
                set: function set(n) {
                  this._transform = n;
                  ModelPool.set(this._handle, ModelView.TRANSFORM, n.handle);
                }
              }, {
                key: "visFlags",
                get: function get() {
                  return this._visFlags;
                },
                set: function set(val) {
                  this._visFlags = val;
                  ModelPool.set(this._handle, ModelView.VIS_FLAGS, val);
                }
              }, {
                key: "enabled",
                get: function get() {
                  return this._enabled;
                },
                set: function set(val) {
                  this._enabled = val;
                  ModelPool.set(this._handle, ModelView.ENABLED, val ? 1 : 0);
                }
              }]);

              return Model;
            }();

            var SphereLight = function (_Light) {
              _inheritsLoose(SphereLight, _Light);

              function SphereLight() {
                var _this;

                _this = _Light.call(this) || this;
                _this._needUpdate = false;
                _this._pos = void 0;
                _this._aabb = void 0;
                _this._hAABB = NULL_HANDLE;
                _this._aabb = AABB.create();
                _this._pos = new Vec3();
                return _this;
              }

              var _proto = SphereLight.prototype;

              _proto.initialize = function initialize() {
                _Light.prototype.initialize.call(this);

                this._hAABB = AABBPool.alloc();
                var size = 0.15;
                LightPool.set(this._handle, LightView.TYPE, LightType.SPHERE);
                LightPool.set(this._handle, LightView.SIZE, size);
                LightPool.set(this._handle, LightView.RANGE, 1.0);
                LightPool.set(this._handle, LightView.AABB, this._hAABB);
                LightPool.set(this._handle, LightView.ILLUMINANCE, 1700 / nt2lm(size));
              };

              _proto.update = function update() {
                if (this._node && (this._node.hasChangedFlags || this._needUpdate)) {
                  this._node.getWorldPosition(this._pos);

                  var range = LightPool.get(this._handle, LightView.RANGE);
                  AABB.set(this._aabb, this._pos.x, this._pos.y, this._pos.z, range, range, range);
                  this._needUpdate = false;
                  LightPool.setVec3(this._handle, LightView.POSITION, this._pos);
                  AABBPool.setVec3(this._hAABB, AABBView.CENTER, this._aabb.center);
                  AABBPool.setVec3(this._hAABB, AABBView.HALF_EXTENSION, this._aabb.halfExtents);
                }
              };

              _proto.destroy = function destroy() {
                if (this._hAABB) {
                  AABBPool.free(this._hAABB);
                  this._hAABB = NULL_HANDLE;
                }

                return _Light.prototype.destroy.call(this);
              };

              _createClass(SphereLight, [{
                key: "position",
                get: function get() {
                  return this._pos;
                }
              }, {
                key: "size",
                get: function get() {
                  return LightPool.get(this._handle, LightView.SIZE);
                },
                set: function set(size) {
                  LightPool.set(this._handle, LightView.SIZE, size);
                }
              }, {
                key: "range",
                get: function get() {
                  return LightPool.get(this._handle, LightView.RANGE);
                },
                set: function set(range) {
                  LightPool.set(this._handle, LightView.RANGE, range);
                  this._needUpdate = true;
                }
              }, {
                key: "luminance",
                get: function get() {
                  return LightPool.get(this._handle, LightView.ILLUMINANCE);
                },
                set: function set(lum) {
                  LightPool.set(this._handle, LightView.ILLUMINANCE, lum);
                }
              }, {
                key: "aabb",
                get: function get() {
                  return this._aabb;
                }
              }]);

              return SphereLight;
            }(Light);

            var _forward$1 = new Vec3(0, 0, -1);

            var _qt = new Quat();

            var _matView = new Mat4();

            var _matProj = new Mat4();

            var _matViewProj = new Mat4();

            var _matViewProjInv = new Mat4();

            var SpotLight = function (_Light) {
              _inheritsLoose(SpotLight, _Light);

              function SpotLight() {
                var _this;

                _this = _Light.call(this) || this;
                _this._dir = new Vec3(1.0, -1.0, -1.0);
                _this._range = 5.0;
                _this._spotAngle = Math.cos(Math.PI / 6);
                _this._pos = void 0;
                _this._aabb = void 0;
                _this._frustum = void 0;
                _this._angle = 0;
                _this._needUpdate = false;
                _this._hAABB = NULL_HANDLE;
                _this._hFrustum = NULL_HANDLE;
                _this._aabb = AABB.create();
                _this._frustum = Frustum.create();
                _this._pos = new Vec3();
                return _this;
              }

              var _proto = SpotLight.prototype;

              _proto.initialize = function initialize() {
                _Light.prototype.initialize.call(this);

                this._hAABB = AABBPool.alloc();
                this._hFrustum = FrustumPool.alloc();
                var size = 0.15;
                LightPool.set(this._handle, LightView.TYPE, LightType.SPOT);
                LightPool.set(this._handle, LightView.SIZE, size);
                LightPool.set(this._handle, LightView.AABB, this._hAABB);
                LightPool.set(this._handle, LightView.ILLUMINANCE, 1700 / nt2lm(size));
                LightPool.set(this._handle, LightView.RANGE, Math.cos(Math.PI / 6));
                LightPool.set(this._handle, LightView.ASPECT, 1.0);
                LightPool.setVec3(this._handle, LightView.DIRECTION, this._dir);
                LightPool.set(this._handle, LightView.FRUSTUM, this._hFrustum);
              };

              _proto.update = function update() {
                if (this._node && (this._node.hasChangedFlags || this._needUpdate)) {
                  this._node.getWorldPosition(this._pos);

                  Vec3.transformQuat(this._dir, _forward$1, this._node.getWorldRotation(_qt));
                  Vec3.normalize(this._dir, this._dir);
                  LightPool.setVec3(this._handle, LightView.DIRECTION, this._dir);
                  AABB.set(this._aabb, this._pos.x, this._pos.y, this._pos.z, this._range, this._range, this._range);

                  this._node.getWorldRT(_matView);

                  Mat4.invert(_matView, _matView);
                  Mat4.perspective(_matProj, this._angle, 1.0, 0.001, this._range);
                  Mat4.multiply(_matViewProj, _matProj, _matView);

                  this._frustum.update(_matViewProj, _matViewProjInv);

                  this._needUpdate = false;
                  LightPool.setVec3(this._handle, LightView.POSITION, this._pos);
                  AABBPool.setVec3(this._hAABB, AABBView.CENTER, this._aabb.center);
                  AABBPool.setVec3(this._hAABB, AABBView.HALF_EXTENSION, this._aabb.halfExtents);
                  recordFrustumToSharedMemory(this._hFrustum, this._frustum);
                }
              };

              _proto.destroy = function destroy() {
                if (this._hAABB) {
                  AABBPool.free(this._hAABB);
                  this._hAABB = NULL_HANDLE;
                }

                if (this._hFrustum) {
                  FrustumPool.free(this._hFrustum);
                  this._hFrustum = NULL_HANDLE;
                }

                return _Light.prototype.destroy.call(this);
              };

              _createClass(SpotLight, [{
                key: "position",
                get: function get() {
                  return this._pos;
                }
              }, {
                key: "size",
                get: function get() {
                  return LightPool.get(this._handle, LightView.SIZE);
                },
                set: function set(size) {
                  LightPool.set(this._handle, LightView.SIZE, size);
                }
              }, {
                key: "range",
                get: function get() {
                  return LightPool.get(this._handle, LightView.RANGE);
                },
                set: function set(range) {
                  this._range = range;
                  LightPool.set(this._handle, LightView.RANGE, range);
                  this._needUpdate = true;
                }
              }, {
                key: "luminance",
                get: function get() {
                  return LightPool.get(this._handle, LightView.ILLUMINANCE);
                },
                set: function set(lum) {
                  LightPool.set(this._handle, LightView.ILLUMINANCE, lum);
                }
              }, {
                key: "direction",
                get: function get() {
                  return this._dir;
                }
              }, {
                key: "spotAngle",
                get: function get() {
                  return LightPool.get(this._handle, LightView.SPOT_ANGLE);
                },
                set: function set(val) {
                  this._angle = val;
                  LightPool.set(this._handle, LightView.SPOT_ANGLE, Math.cos(val * 0.5));
                  this._needUpdate = true;
                }
              }, {
                key: "aspect",
                get: function get() {
                  return LightPool.get(this._handle, LightView.ASPECT);
                },
                set: function set(val) {
                  LightPool.set(this._handle, LightView.ASPECT, val);
                  this._needUpdate = true;
                }
              }, {
                key: "aabb",
                get: function get() {
                  return this._aabb;
                }
              }, {
                key: "frustum",
                get: function get() {
                  return this._frustum;
                }
              }]);

              return SpotLight;
            }(Light);

            var index$2 = /*#__PURE__*/Object.freeze({
                __proto__: null,
                Ambient: Ambient,
                get CameraFOVAxis () { return CameraFOVAxis; },
                get CameraProjection () { return CameraProjection; },
                get CameraAperture () { return CameraAperture; },
                get CameraISO () { return CameraISO; },
                get CameraShutter () { return CameraShutter; },
                SKYBOX_FLAG: SKYBOX_FLAG,
                Camera: Camera,
                CameraVisFlags: CameraVisFlags,
                VisibilityFlags: VisibilityFlags,
                DirectionalLight: DirectionalLight,
                ColorTemperatureToRGB: ColorTemperatureToRGB,
                get LightType () { return LightType; },
                nt2lm: nt2lm,
                Light: Light,
                get ModelType () { return ModelType; },
                Model: Model,
                ShadowType: ShadowType,
                PCFType: PCFType,
                Shadows: Shadows,
                RenderScene: RenderScene,
                Skybox: Skybox,
                SphereLight: SphereLight,
                SpotLight: SpotLight,
                SubModel: SubModel
            });

            function createIA(device, data) {
              if (!data.positions) {
                console.error('The data must have positions field');
                return null;
              }

              var verts = [];
              var vcount = data.positions.length / 3;

              for (var i = 0; i < vcount; ++i) {
                verts.push(data.positions[3 * i], data.positions[3 * i + 1], data.positions[3 * i + 2]);

                if (data.normals) {
                  verts.push(data.normals[3 * i], data.normals[3 * i + 1], data.normals[3 * i + 2]);
                }

                if (data.uvs) {
                  verts.push(data.uvs[2 * i], data.uvs[2 * i + 1]);
                }

                if (data.colors) {
                  verts.push(data.colors[3 * i], data.colors[3 * i + 1], data.colors[3 * i + 2]);
                }
              }

              var vfmt = [];
              vfmt.push(new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F));

              if (data.normals) {
                vfmt.push(new Attribute(AttributeName.ATTR_NORMAL, Format.RGB32F));
              }

              if (data.uvs) {
                vfmt.push(new Attribute(AttributeName.ATTR_TEX_COORD, Format.RG32F));
              }

              if (data.colors) {
                vfmt.push(new Attribute(AttributeName.ATTR_COLOR, Format.RGB32F));
              }

              var vb = device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, verts.length * 4, verts.length * 4 / vcount));
              vb.update(new Float32Array(verts));
              var ib = null;

              if (data.indices) {
                ib = device.createBuffer(new BufferInfo(BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, data.indices.length * 2, 2));
                ib.update(new Uint16Array(data.indices));
              }

              return device.createInputAssembler(new InputAssemblerInfo(vfmt, [vb], ib));
            }

            var RenderQueue$1;

            (function (RenderQueue) {
              RenderQueue[RenderQueue["OPAQUE"] = 0] = "OPAQUE";
              RenderQueue[RenderQueue["TRANSPARENT"] = 1] = "TRANSPARENT";
              RenderQueue[RenderQueue["OVERLAY"] = 2] = "OVERLAY";
            })(RenderQueue$1 || (RenderQueue$1 = {}));

            var PassStage;

            (function (PassStage) {
              PassStage[PassStage["DEFAULT"] = 1] = "DEFAULT";
              PassStage[PassStage["FORWARD"] = 2] = "FORWARD";
              PassStage[PassStage["SHADOWCAST"] = 4] = "SHADOWCAST";
            })(PassStage || (PassStage = {}));

            function nearestPOT(num) {
              --num;
              num |= num >> 16;
              num |= num >> 8;
              num |= num >> 4;
              num |= num >> 2;
              num |= num >> 1;
              ++num;
              return num;
            }

            function roundUp(n, alignment) {
              return Math.ceil(n / alignment) * alignment;
            }

            var TextureBufferPool = function () {
              function TextureBufferPool(device) {
                this._device = void 0;
                this._format = Format.UNKNOWN;
                this._formatSize = 0;
                this._chunks = [];
                this._chunkCount = 0;
                this._handles = [];
                this._region0 = new BufferTextureCopy();
                this._region1 = new BufferTextureCopy();
                this._region2 = new BufferTextureCopy();
                this._roundUpFn = null;
                this._bufferViewCtor = Uint8Array;
                this._channels = 4;
                this._alignment = 1;
                this._device = device;
              }

              var _proto = TextureBufferPool.prototype;

              _proto.initialize = function initialize(info) {
                var formatInfo = FormatInfos[info.format];
                this._format = info.format;
                this._formatSize = formatInfo.size;
                this._channels = formatInfo.count;
                this._bufferViewCtor = getTypedArrayConstructor(formatInfo);
                this._roundUpFn = info.roundUpFn || null;
                this._alignment = info.alignment || 1;

                if (info.inOrderFree) {
                  this.alloc = this._McDonaldAlloc;
                }
              };

              _proto.destroy = function destroy() {
                for (var i = 0; i < this._chunkCount; ++i) {
                  var chunk = this._chunks[i];
                  chunk.texture.destroy();
                }

                this._chunks.length = 0;
                this._handles.length = 0;
              };

              _proto.alloc = function alloc(size, chunkIdx) {
                size = roundUp(size, this._alignment);
                var index = -1;
                var start = -1;

                if (chunkIdx !== undefined) {
                  index = chunkIdx;
                  start = this._findAvailableSpace(size, index);
                }

                if (start < 0) {
                  for (var i = 0; i < this._chunkCount; ++i) {
                    index = i;
                    start = this._findAvailableSpace(size, index);

                    if (start >= 0) {
                      break;
                    }
                  }
                }

                if (start >= 0) {
                  var chunk = this._chunks[index];
                  chunk.start += size;
                  var handle = {
                    chunkIdx: index,
                    start: start,
                    end: start + size,
                    texture: chunk.texture
                  };

                  this._handles.push(handle);

                  return handle;
                }

                var targetSize = Math.sqrt(size / this._formatSize);
                var texLength = this._roundUpFn && this._roundUpFn(targetSize, this._formatSize) || Math.max(1024, nearestPOT(targetSize));

                var newChunk = this._chunks[this.createChunk(texLength)];

                newChunk.start += size;
                var texHandle = {
                  chunkIdx: this._chunkCount - 1,
                  start: 0,
                  end: size,
                  texture: newChunk.texture
                };

                this._handles.push(texHandle);

                return texHandle;
              };

              _proto.free = function free(handle) {
                for (var i = 0; i < this._handles.length; ++i) {
                  if (this._handles[i] === handle) {
                    this._chunks[handle.chunkIdx].end = handle.end;

                    this._handles.splice(i, 1);

                    return;
                  }
                }
              };

              _proto.createChunk = function createChunk(length) {
                var texSize = length * length * this._formatSize;
                console.info("TextureBufferPool: Allocate chunk " + this._chunkCount + ", size: " + texSize + ", format: " + this._format);

                var texture = this._device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.SAMPLED | TextureUsageBit.TRANSFER_DST, this._format, length, length, TextureFlagBit.IMMUTABLE));

                var chunk = {
                  texture: texture,
                  size: texSize,
                  start: 0,
                  end: texSize
                };
                this._chunks[this._chunkCount] = chunk;
                return this._chunkCount++;
              };

              _proto.update = function update(handle, buffer) {
                var buffers = [];
                var regions = [];
                var start = handle.start / this._formatSize;
                var remainSize = buffer.byteLength / this._formatSize;
                var offsetX = start % handle.texture.width;
                var offsetY = Math.floor(start / handle.texture.width);
                var copySize = Math.min(handle.texture.width - offsetX, remainSize);
                var begin = 0;

                if (offsetX > 0) {
                  this._region0.texOffset.x = offsetX;
                  this._region0.texOffset.y = offsetY;
                  this._region0.texExtent.width = copySize;
                  this._region0.texExtent.height = 1;
                  buffers.push(new this._bufferViewCtor(buffer, begin * this._formatSize, copySize * this._channels));
                  regions.push(this._region0);
                  offsetX = 0;
                  offsetY += 1;
                  remainSize -= copySize;
                  begin += copySize;
                }

                if (remainSize > 0) {
                  this._region1.texOffset.x = offsetX;
                  this._region1.texOffset.y = offsetY;

                  if (remainSize > handle.texture.width) {
                    this._region1.texExtent.width = handle.texture.width;
                    this._region1.texExtent.height = Math.floor(remainSize / handle.texture.width);
                    copySize = this._region1.texExtent.width * this._region1.texExtent.height;
                  } else {
                    copySize = remainSize;
                    this._region1.texExtent.width = copySize;
                    this._region1.texExtent.height = 1;
                  }

                  buffers.push(new this._bufferViewCtor(buffer, begin * this._formatSize, copySize * this._channels));
                  regions.push(this._region1);
                  offsetX = 0;
                  offsetY += this._region1.texExtent.height;
                  remainSize -= copySize;
                  begin += copySize;
                }

                if (remainSize > 0) {
                  this._region2.texOffset.x = offsetX;
                  this._region2.texOffset.y = offsetY;
                  this._region2.texExtent.width = remainSize;
                  this._region2.texExtent.height = 1;
                  buffers.push(new this._bufferViewCtor(buffer, begin * this._formatSize, remainSize * this._channels));
                  regions.push(this._region2);
                }

                this._device.copyBuffersToTexture(buffers, handle.texture, regions);
              };

              _proto._findAvailableSpace = function _findAvailableSpace(size, chunkIdx) {
                var chunk = this._chunks[chunkIdx];
                var isFound = false;
                var start = chunk.start;

                if (start + size <= chunk.size) {
                  isFound = true;
                } else {
                  start = 0;

                  var handles = this._handles.filter(function (h) {
                    return h.chunkIdx === chunkIdx;
                  }).sort(function (a, b) {
                    return a.start - b.start;
                  });

                  for (var i = 0; i < handles.length; i++) {
                    var handle = handles[i];

                    if (start + size <= handle.start) {
                      isFound = true;
                      break;
                    }

                    start = handle.end;
                  }

                  if (!isFound && start + size <= chunk.size) {
                    isFound = true;
                  }
                }

                return isFound ? start : -1;
              };

              _proto._McDonaldAlloc = function _McDonaldAlloc(size) {
                size = roundUp(size, this._alignment);

                for (var i = 0; i < this._chunkCount; ++i) {
                  var chunk = this._chunks[i];
                  var isFound = false;
                  var start = chunk.start;

                  if (start + size <= chunk.end) {
                    isFound = true;
                  } else if (start > chunk.end) {
                    if (start + size <= chunk.size) {
                      isFound = true;
                    } else if (size <= chunk.end) {
                      chunk.start = start = 0;
                      isFound = true;
                    }
                  } else if (start === chunk.end) {
                    chunk.start = start = 0;
                    chunk.end = chunk.size;

                    if (size <= chunk.end) {
                      isFound = true;
                    }
                  }

                  if (isFound) {
                    chunk.start += size;
                    var handle = {
                      chunkIdx: i,
                      start: start,
                      end: start + size,
                      texture: chunk.texture
                    };

                    this._handles.push(handle);

                    return handle;
                  }
                }

                var targetSize = Math.sqrt(size / this._formatSize);
                var texLength = this._roundUpFn && this._roundUpFn(targetSize, this._formatSize) || Math.max(1024, nearestPOT(targetSize));

                var newChunk = this._chunks[this.createChunk(texLength)];

                newChunk.start += size;
                var texHandle = {
                  chunkIdx: this._chunkCount,
                  start: 0,
                  end: size,
                  texture: newChunk.texture
                };

                this._handles.push(texHandle);

                return texHandle;
              };

              return TextureBufferPool;
            }();

            var addStage = config.addStage;

            var renderer = /*#__PURE__*/Object.freeze({
                __proto__: null,
                addStage: addStage,
                scene: index$2,
                createIA: createIA,
                get RenderQueue () { return RenderQueue$1; },
                get PassStage () { return PassStage; },
                get PropertyType () { return PropertyType; },
                genHandle: genHandle,
                getPropertyTypeFromHandle: getPropertyTypeFromHandle,
                getTypeFromHandle: getTypeFromHandle,
                getSetIndexFromHandle: getSetIndexFromHandle,
                getBindingFromHandle: getBindingFromHandle,
                getOffsetFromHandle: getOffsetFromHandle,
                customizeType: customizeType,
                type2reader: type2reader,
                type2writer: type2writer,
                getDefaultFromType: getDefaultFromType,
                overrideMacros: overrideMacros,
                get BatchingSchemes () { return BatchingSchemes; },
                Pass: Pass,
                getDeviceShaderVersion: getDeviceShaderVersion,
                programLib: programLib,
                get SamplerInfoIndex () { return SamplerInfoIndex; },
                defaultSamplerHash: defaultSamplerHash,
                genSamplerHash: genSamplerHash,
                samplerLib: samplerLib,
                nearestPOT: nearestPOT,
                TextureBufferPool: TextureBufferPool,
                MaterialInstance: MaterialInstance,
                PassInstance: PassInstance,
                ObjectPool: ObjectPool,
                freeHandleArray: freeHandleArray,
                get PoolType () { return PoolType; },
                NULL_HANDLE: NULL_HANDLE,
                ShaderPool: ShaderPool,
                DSPool: DSPool,
                IAPool: IAPool,
                PipelineLayoutPool: PipelineLayoutPool,
                FramebufferPool: FramebufferPool,
                SubModelArrayPool: SubModelArrayPool,
                ModelArrayPool: ModelArrayPool,
                AttributeArrayPool: AttributeArrayPool,
                FlatBufferArrayPool: FlatBufferArrayPool,
                LightArrayPool: LightArrayPool,
                BlendTargetArrayPool: BlendTargetArrayPool,
                UIBatchArrayPool: UIBatchArrayPool,
                RawBufferPool: RawBufferPool,
                RawObjectPool: RawObjectPool,
                get PassView () { return PassView; },
                PassPool: PassPool,
                get SubModelView () { return SubModelView; },
                SubModelPool: SubModelPool,
                get ModelView () { return ModelView; },
                ModelPool: ModelPool,
                get BatchView2D () { return BatchView2D; },
                BatchPool2D: BatchPool2D,
                get AABBView () { return AABBView; },
                AABBPool: AABBPool,
                get SceneView () { return SceneView; },
                ScenePool: ScenePool,
                get CameraView () { return CameraView; },
                CameraPool: CameraPool,
                get NodeView () { return NodeView; },
                NodePool: NodePool,
                get RootView () { return RootView; },
                RootPool: RootPool,
                get RenderWindowView () { return RenderWindowView; },
                RenderWindowPool: RenderWindowPool,
                get FrustumView () { return FrustumView; },
                FrustumPool: FrustumPool,
                get AmbientView () { return AmbientView; },
                AmbientPool: AmbientPool,
                get SkyboxView () { return SkyboxView; },
                SkyboxPool: SkyboxPool,
                get FogView () { return FogView; },
                FogPool: FogPool,
                get ShadowsView () { return ShadowsView; },
                ShadowsPool: ShadowsPool,
                get PipelineSceneDataView () { return PipelineSceneDataView; },
                PipelineSceneDataPool: PipelineSceneDataPool,
                get LightView () { return LightView; },
                LightPool: LightPool,
                get SphereView () { return SphereView; },
                SpherePool: SpherePool,
                get FlatBufferView () { return FlatBufferView; },
                FlatBufferPool: FlatBufferPool,
                get SubMeshView () { return SubMeshView; },
                SubMeshPool: SubMeshPool,
                get RasterizerStateView () { return RasterizerStateView; },
                RasterizerStatePool: RasterizerStatePool,
                get DepthStencilStateView () { return DepthStencilStateView; },
                DepthStencilStatePool: DepthStencilStatePool,
                get BlendTargetView () { return BlendTargetView; },
                BlendTargetPool: BlendTargetPool,
                get BlendStateView () { return BlendStateView; },
                BlendStatePool: BlendStatePool
            });
            exports('renderer', renderer);

            function constant() {
              return 0;
            }
            function linear(k) {
              return k;
            }
            function quadIn(k) {
              return k * k;
            }
            function quadOut(k) {
              return k * (2 - k);
            }
            function quadInOut(k) {
              k *= 2;

              if (k < 1) {
                return 0.5 * k * k;
              }

              return -0.5 * (--k * (k - 2) - 1);
            }
            function cubicIn(k) {
              return k * k * k;
            }
            function cubicOut(k) {
              return --k * k * k + 1;
            }
            function cubicInOut(k) {
              k *= 2;

              if (k < 1) {
                return 0.5 * k * k * k;
              }

              return 0.5 * ((k -= 2) * k * k + 2);
            }
            function quartIn(k) {
              return k * k * k * k;
            }
            function quartOut(k) {
              return 1 - --k * k * k * k;
            }
            function quartInOut(k) {
              k *= 2;

              if (k < 1) {
                return 0.5 * k * k * k * k;
              }

              return -0.5 * ((k -= 2) * k * k * k - 2);
            }
            function quintIn(k) {
              return k * k * k * k * k;
            }
            function quintOut(k) {
              return --k * k * k * k * k + 1;
            }
            function quintInOut(k) {
              k *= 2;

              if (k < 1) {
                return 0.5 * k * k * k * k * k;
              }

              return 0.5 * ((k -= 2) * k * k * k * k + 2);
            }
            function sineIn(k) {
              if (k === 1) {
                return 1;
              }

              return 1 - Math.cos(k * Math.PI / 2);
            }
            function sineOut(k) {
              return Math.sin(k * Math.PI / 2);
            }
            function sineInOut(k) {
              return 0.5 * (1 - Math.cos(Math.PI * k));
            }
            function expoIn(k) {
              return k === 0 ? 0 : Math.pow(1024, k - 1);
            }
            function expoOut(k) {
              return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
            }
            function expoInOut(k) {
              if (k === 0) {
                return 0;
              }

              if (k === 1) {
                return 1;
              }

              k *= 2;

              if (k < 1) {
                return 0.5 * Math.pow(1024, k - 1);
              }

              return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
            }
            function circIn(k) {
              return 1 - Math.sqrt(1 - k * k);
            }
            function circOut(k) {
              return Math.sqrt(1 - --k * k);
            }
            function circInOut(k) {
              k *= 2;

              if (k < 1) {
                return -0.5 * (Math.sqrt(1 - k * k) - 1);
              }

              return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
            }
            function elasticIn(k) {
              var s;
              var a = 0.1;
              var p = 0.4;

              if (k === 0) {
                return 0;
              }

              if (k === 1) {
                return 1;
              }

              if (!a || a < 1) {
                a = 1;
                s = p / 4;
              } else {
                s = p * Math.asin(1 / a) / (2 * Math.PI);
              }

              return -(a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p));
            }
            function elasticOut(k) {
              var s;
              var a = 0.1;
              var p = 0.4;

              if (k === 0) {
                return 0;
              }

              if (k === 1) {
                return 1;
              }

              if (!a || a < 1) {
                a = 1;
                s = p / 4;
              } else {
                s = p * Math.asin(1 / a) / (2 * Math.PI);
              }

              return a * Math.pow(2, -10 * k) * Math.sin((k - s) * (2 * Math.PI) / p) + 1;
            }
            function elasticInOut(k) {
              var s;
              var a = 0.1;
              var p = 0.4;

              if (k === 0) {
                return 0;
              }

              if (k === 1) {
                return 1;
              }

              if (!a || a < 1) {
                a = 1;
                s = p / 4;
              } else {
                s = p * Math.asin(1 / a) / (2 * Math.PI);
              }

              k *= 2;

              if (k < 1) {
                return -0.5 * (a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p));
              }

              return a * Math.pow(2, -10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
            }
            function backIn(k) {
              if (k === 1) {
                return 1;
              }

              var s = 1.70158;
              return k * k * ((s + 1) * k - s);
            }
            function backOut(k) {
              if (k === 0) {
                return 0;
              }

              var s = 1.70158;
              return --k * k * ((s + 1) * k + s) + 1;
            }
            function backInOut(k) {
              var s = 1.70158 * 1.525;
              k *= 2;

              if (k < 1) {
                return 0.5 * (k * k * ((s + 1) * k - s));
              }

              return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
            }
            function bounceIn(k) {
              return 1 - bounceOut(1 - k);
            }
            function bounceOut(k) {
              if (k < 1 / 2.75) {
                return 7.5625 * k * k;
              } else if (k < 2 / 2.75) {
                return 7.5625 * (k -= 1.5 / 2.75) * k + 0.75;
              } else if (k < 2.5 / 2.75) {
                return 7.5625 * (k -= 2.25 / 2.75) * k + 0.9375;
              } else {
                return 7.5625 * (k -= 2.625 / 2.75) * k + 0.984375;
              }
            }
            function bounceInOut(k) {
              if (k < 0.5) {
                return bounceIn(k * 2) * 0.5;
              }

              return bounceOut(k * 2 - 1) * 0.5 + 0.5;
            }
            function smooth(k) {
              if (k <= 0) {
                return 0;
              }

              if (k >= 1) {
                return 1;
              }

              return k * k * (3 - 2 * k);
            }
            function fade(k) {
              if (k <= 0) {
                return 0;
              }

              if (k >= 1) {
                return 1;
              }

              return k * k * k * (k * (k * 6 - 15) + 10);
            }
            var quadOutIn = _makeOutIn(quadIn, quadOut);
            var cubicOutIn = _makeOutIn(cubicIn, cubicOut);
            var quartOutIn = _makeOutIn(quartIn, quartOut);
            var quintOutIn = _makeOutIn(quintIn, quintOut);
            var sineOutIn = _makeOutIn(sineIn, sineOut);
            var expoOutIn = _makeOutIn(expoIn, expoOut);
            var circOutIn = _makeOutIn(circIn, circOut);
            var elasticOutIn = _makeOutIn(elasticIn, elasticOut);
            var backOutIn = _makeOutIn(backIn, backOut);
            var bounceOutIn = _makeOutIn(bounceIn, bounceOut);

            function _makeOutIn(fnIn, fnOut) {
              return function (k) {
                if (k < 0.5) {
                  return fnOut(k * 2) / 2;
                }

                return fnIn(2 * k - 1) / 2 + 0.5;
              };
            }

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

            var v2_0 = new Vec2();
            var SplashScreen = function () {
              var _proto = SplashScreen.prototype;

              _proto.main = function main(root) {
                if (root == null) {
                  error('RENDER ROOT IS NULL.');
                  return;
                }

                if (window._CCSettings && window._CCSettings.splashScreen) {
                  var setting = this.settings = window._CCSettings.splashScreen;
                  setting.totalTime = this.settings.totalTime != null ? this.settings.totalTime : 3000;
                  setting.base64src = this.settings.base64src || '';
                  setting.effect = this.settings.effect || 'FADE-INOUT';
                  setting.clearColor = this.settings.clearColor || new Color$1(0.88, 0.88, 0.88, 1);
                  setting.displayRatio = this.settings.displayRatio != null ? this.settings.displayRatio : 0.4;
                  setting.displayWatermark = this.settings.displayWatermark != null ? this.settings.displayWatermark : true;
                } else {
                  this.settings = {
                    totalTime: 3000,
                    base64src: '',
                    effect: 'FADE-INOUT',
                    clearColor: new Color$1(0.88, 0.88, 0.88, 1),
                    displayRatio: 0.4,
                    displayWatermark: true
                  };
                }

                if (this.settings.base64src === '' || this.settings.totalTime <= 0) {
                  if (this.callBack) {
                    this.callBack();
                  }

                  this.callBack = null;
                  this.settings = null;
                  this._directCall = true;
                } else {
                  legacyCC.view.enableRetina(true);
                  legacyCC.view.resizeWithBrowserSize(true);
                  var designRes = window._CCSettings.designResolution;

                  if (designRes) {
                    legacyCC.view.setDesignResolutionSize(designRes.width, designRes.height, designRes.policy);
                  } else {
                    legacyCC.view.setDesignResolutionSize(960, 640, 4);
                  }

                  this.root = root;
                  this.device = root.device;
                  legacyCC.game.once(legacyCC.Game.EVENT_GAME_INITED, function () {
                    legacyCC.director._lateUpdate = performance.now();
                  }, legacyCC.director);
                  this.callBack = null;
                  this.cancelAnimate = false;
                  this.startTime = -1;
                  this.preInit();
                  this.logoImage = new Image();
                  this.logoImage.onload = this.init.bind(this);
                  this.logoImage.src = this.settings.base64src;
                }
              };

              _proto.setOnFinish = function setOnFinish(cb) {
                if (this._directCall) {
                  if (cb) {
                    SplashScreen._ins = undefined;
                    cb();
                    return;
                  }
                }

                this.callBack = cb;
              };

              _proto._tryToStart = function _tryToStart() {
                if (this._splashFinish && this._loadFinish) {
                  if (this.callBack) {
                    this.callBack();
                    this.hide();
                    legacyCC.game.resume();
                  }
                }
              };

              _proto.preInit = function preInit() {
                var clearColor = this.settings.clearColor;
                this.clearColors = [new Color$1(clearColor.x, clearColor.y, clearColor.z, clearColor.w)];
                var device = this.device;
                this.renderArea = new Rect$1(0, 0, device.width, device.height);
                this.framebuffer = this.root.mainWindow.framebuffer;
                this.cmdBuff = device.commandBuffer;
                var verts = new Float32Array([0.5, 0.5, 1, 0, -0.5, 0.5, 0, 0, 0.5, -0.5, 1, 1, -0.5, -0.5, 0, 1]);
                var vbStride = Float32Array.BYTES_PER_ELEMENT * 4;
                var vbSize = vbStride * 4;
                this.vertexBuffers = device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, vbSize, vbStride));
                this.vertexBuffers.update(verts);
                var indices = new Uint16Array([0, 1, 2, 1, 3, 2]);
                var ibStride = Uint16Array.BYTES_PER_ELEMENT;
                var ibSize = ibStride * 6;
                this.indicesBuffers = device.createBuffer(new BufferInfo(BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, ibSize, ibStride));
                this.indicesBuffers.update(indices);
                var attributes = [new Attribute('a_position', Format.RG32F), new Attribute('a_texCoord', Format.RG32F)];
                var IAInfo = new InputAssemblerInfo(attributes, [this.vertexBuffers], this.indicesBuffers);
                this.quadAssmebler = device.createInputAssembler(IAInfo);
                this.projection = new Mat4();
                Mat4.ortho(this.projection, -1, 1, -1, 1, -1, 1, device.capabilities.clipSpaceMinZ, device.capabilities.clipSpaceSignY, device.surfaceTransform);
              };

              _proto.init = function init() {
                var _this = this;

                this.initLogo();
                if (this.settings.displayWatermark) this.initWarterMark();

                var animate = function animate(time) {
                  if (_this.cancelAnimate) return;
                  var settings = _this.settings;
                  var device = _this.device;
                  Mat4.ortho(_this.projection, -1, 1, -1, 1, -1, 1, device.capabilities.clipSpaceMinZ, device.capabilities.clipSpaceSignY, device.surfaceTransform);
                  var dw = device.width;
                  var dh = device.height;
                  var refW = dw < dh ? dw : dh;
                  if (_this.startTime < 0) _this.startTime = time;
                  var elapsedTime = time - _this.startTime;
                  var percent = clamp01(elapsedTime / settings.totalTime);
                  var u_p = cubicOut(percent);
                  if (settings.effect === 'NONE') u_p = 1.0;
                  var logoTW = _this.logoTexture.width;
                  var logoTH = _this.logoTexture.height;
                  var logoW = refW * settings.displayRatio;
                  var scaleX = logoW * logoTW / logoTH;
                  var scaleY = logoW;

                  if (device.surfaceTransform === SurfaceTransform.ROTATE_90 || device.surfaceTransform === SurfaceTransform.ROTATE_270) {
                    scaleX = logoW * dw / dh;
                    scaleY = logoW * logoTH / logoTW * dh / dw;
                  }

                  _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 * 0.5, dh * 0.5), 0);

                  _this.logoMat.setProperty('precent', u_p);

                  _this.logoMat.setProperty('u_projection', _this.projection);

                  _this.logoMat.passes[0].update();

                  if (settings.displayWatermark && _this.watermarkMat) {
                    var wartermarkW = refW * 0.5;
                    var wartermarkTW = _this.watermarkTexture.width;
                    var wartermarkTH = _this.watermarkTexture.height;
                    var _scaleX = wartermarkW;

                    var _scaleY = wartermarkW * wartermarkTH / wartermarkTW;

                    if (device.surfaceTransform === SurfaceTransform.ROTATE_90 || device.surfaceTransform === SurfaceTransform.ROTATE_270) {
                      _scaleX = wartermarkW * 0.5;
                      _scaleY = wartermarkW * dw / dh * 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 * 0.5, dh * 0.1), 0);

                    _this.watermarkMat.setProperty('precent', u_p);

                    _this.watermarkMat.setProperty('u_projection', _this.projection);

                    _this.watermarkMat.passes[0].update();
                  }

                  _this.frame();

                  if (elapsedTime > settings.totalTime) _this.splashFinish = true;
                  requestAnimationFrame(animate);
                };

                legacyCC.game.pause();
                this.handle = requestAnimationFrame(animate);
              };

              _proto.hide = function hide() {
                cancelAnimationFrame(this.handle);
                this.cancelAnimate = true;
                setTimeout(this.destroy.bind(this));
              };

              _proto.initLogo = function initLogo() {
                var device = this.device;
                this.logoMat = new Material();
                this.logoMat.initialize({
                  effectName: 'splash-screen'
                });
                var samplerInfo = new SamplerInfo();
                samplerInfo.addressU = Address.CLAMP;
                samplerInfo.addressV = Address.CLAMP;
                samplerInfo.addressW = Address.CLAMP;
                this.sampler = device.createSampler(samplerInfo);
                this.logoTexture = device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.SAMPLED | TextureUsageBit.TRANSFER_DST, Format.RGBA8, this.logoImage.width, this.logoImage.height));
                var pass = this.logoMat.passes[0];
                var binding = pass.getBinding('mainTexture');
                pass.bindTexture(binding, this.logoTexture);
                this.shader = ShaderPool.get(pass.getShaderVariant());
                var descriptorSet = DSPool.get(PassPool.get(pass.handle, PassView.DESCRIPTOR_SET));
                descriptorSet.bindSampler(binding, this.sampler);
                descriptorSet.update();
                var region = new BufferTextureCopy();
                region.texExtent.width = this.logoImage.width;
                region.texExtent.height = this.logoImage.height;
                region.texExtent.depth = 1;
                device.copyTexImagesToTexture([this.logoImage], this.logoTexture, [region]);
              };

              _proto.initWarterMark = function initWarterMark() {
                var wartemarkImg = document.createElement('canvas');
                wartemarkImg.width = 330;
                wartemarkImg.height = 30;
                wartemarkImg.style.width = "" + wartemarkImg.width;
                wartemarkImg.style.height = "" + wartemarkImg.height;
                var ctx = wartemarkImg.getContext('2d');
                ctx.font = 18 + "px Arial";
                ctx.textBaseline = 'top';
                ctx.textAlign = 'left';
                ctx.fillStyle = '`#424242`';
                var text = 'Powered by Cocos Creator';
                var textMetrics = ctx.measureText(text);
                ctx.fillText(text, (330 - textMetrics.width) / 2, 6);
                var region = new BufferTextureCopy();
                region.texExtent.width = wartemarkImg.width;
                region.texExtent.height = wartemarkImg.height;
                region.texExtent.depth = 1;
                this.watermarkTexture = this.device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.SAMPLED | TextureUsageBit.TRANSFER_DST, Format.RGBA8, wartemarkImg.width, wartemarkImg.height));
                this.device.copyTexImagesToTexture([wartemarkImg], this.watermarkTexture, [region]);
                this.watermarkMat = new Material();
                this.watermarkMat.initialize({
                  effectName: 'splash-screen'
                });
                var pass = this.watermarkMat.passes[0];
                var binding = pass.getBinding('mainTexture');
                pass.bindTexture(binding, this.watermarkTexture);
                DSPool.get(PassPool.get(pass.handle, PassView.DESCRIPTOR_SET)).update();
              };

              _proto.frame = function frame() {
                var device = this.device;
                device.acquire();
                var cmdBuff = this.cmdBuff;
                var framebuffer = this.framebuffer;
                var renderArea = this.renderArea;

                {
                  renderArea.width = device.width;
                  renderArea.height = device.height;
                }

                cmdBuff.begin();
                cmdBuff.beginRenderPass(framebuffer.renderPass, framebuffer, renderArea, this.clearColors, 1.0, 0);
                var logoPass = this.logoMat.passes[0];
                var logoPso = PipelineStateManager.getOrCreatePipelineState(device, logoPass, this.shader, framebuffer.renderPass, this.quadAssmebler);
                cmdBuff.bindPipelineState(logoPso);
                cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, logoPass.descriptorSet);
                cmdBuff.bindInputAssembler(this.quadAssmebler);
                cmdBuff.draw(this.quadAssmebler);

                if (this.settings.displayWatermark && this.watermarkMat) {
                  var wartermarkPass = this.watermarkMat.passes[0];
                  var watermarkPso = PipelineStateManager.getOrCreatePipelineState(device, wartermarkPass, this.shader, framebuffer.renderPass, this.quadAssmebler);
                  cmdBuff.bindPipelineState(watermarkPso);
                  cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, wartermarkPass.descriptorSet);
                  cmdBuff.bindInputAssembler(this.quadAssmebler);
                  cmdBuff.draw(this.quadAssmebler);
                }

                cmdBuff.endRenderPass();
                cmdBuff.end();
                device.flushCommands([cmdBuff]);
                device.queue.submit([cmdBuff]);
                device.present();
              };

              _proto.destroy = function destroy() {
                this.callBack = null;
                this.root = null;
                this.device = null;
                this.clearColors = null;
                if (this.logoImage.destroy) this.logoImage.destroy();
                this.logoImage = null;
                this.framebuffer = null;
                this.renderArea = null;
                this.cmdBuff = null;
                this.shader = null;
                this.logoMat.destroy();
                this.logoMat = null;
                this.logoTexture.destroy();
                this.logoTexture = null;
                this.quadAssmebler.destroy();
                this.quadAssmebler = null;
                this.vertexBuffers.destroy();
                this.vertexBuffers = null;
                this.indicesBuffers.destroy();
                this.indicesBuffers = null;
                this.sampler.destroy();
                this.sampler = null;

                if (this.watermarkTexture) {
                  this.watermarkMat.destroy();
                  this.watermarkMat = null;
                  this.watermarkTexture.destroy();
                  this.watermarkTexture = null;
                }

                this.settings = null;
                SplashScreen._ins = undefined;
              };

              function SplashScreen() {
                this.handle = 0;
                this.callBack = null;
                this.cancelAnimate = false;
                this.startTime = -1;
                this._splashFinish = false;
                this._loadFinish = false;
                this._directCall = false;
              }

              _createClass(SplashScreen, [{
                key: "splashFinish",
                set: function set(v) {
                  this._splashFinish = v;

                  this._tryToStart();
                }
              }, {
                key: "loadFinish",
                set: function set(v) {
                  this._loadFinish = v;

                  this._tryToStart();
                }
              }], [{
                key: "instance",
                get: function get() {
                  if (!SplashScreen._ins) {
                    SplashScreen._ins = new SplashScreen();
                  }

                  return SplashScreen._ins;
                }
              }]);

              return SplashScreen;
            }();
            SplashScreen._ins = void 0;
            legacyCC.internal.SplashScreen = SplashScreen;

            var System$1 = exports('System', function () {
              function System() {
                this._id = '';
                this._priority = 0;
                this._executeInEditMode = false;
              }

              System.sortByPriority = function sortByPriority(a, b) {
                if (a._priority < b._priority) {
                  return 1;
                } else if (a._priority > b.priority) {
                  return -1;
                } else {
                  return 0;
                }
              };

              var _proto = System.prototype;

              _proto.init = function init() {};

              _proto.update = function update(dt) {};

              _proto.postUpdate = function postUpdate(dt) {};

              _createClass(System, [{
                key: "priority",
                get: function get() {
                  return this._priority;
                },
                set: function set(value) {
                  this._priority = value;
                }
              }, {
                key: "id",
                get: function get() {
                  return this._id;
                },
                set: function set(id) {
                  this._id = id;
                }
              }]);

              return System;
            }());

            var MAX_POOL_SIZE = 20;
            var idGenerator$4 = new IDGenerator('Scheduler');

            var ListEntry = function ListEntry(target, priority, paused, markedForDeletion) {
              this.target = void 0;
              this.priority = void 0;
              this.paused = void 0;
              this.markedForDeletion = void 0;
              this.target = target;
              this.priority = priority;
              this.paused = paused;
              this.markedForDeletion = markedForDeletion;
            };

            ListEntry.get = function (target, priority, paused, markedForDeletion) {
              var result = ListEntry._listEntries.pop();

              if (result) {
                result.target = target;
                result.priority = priority;
                result.paused = paused;
                result.markedForDeletion = markedForDeletion;
              } else {
                result = new ListEntry(target, priority, paused, markedForDeletion);
              }

              return result;
            };

            ListEntry.put = function (entry) {
              if (ListEntry._listEntries.length < MAX_POOL_SIZE) {
                entry.target = null;

                ListEntry._listEntries.push(entry);
              }
            };

            ListEntry._listEntries = [];

            var HashUpdateEntry = function HashUpdateEntry(list, entry, target, callback) {
              this.list = void 0;
              this.entry = void 0;
              this.target = void 0;
              this.callback = void 0;
              this.list = list;
              this.entry = entry;
              this.target = target;
              this.callback = callback;
            };

            HashUpdateEntry.get = function (list, entry, target, callback) {
              var result = HashUpdateEntry._hashUpdateEntries.pop();

              if (result) {
                result.list = list;
                result.entry = entry;
                result.target = target;
                result.callback = callback;
              } else {
                result = new HashUpdateEntry(list, entry, target, callback);
              }

              return result;
            };

            HashUpdateEntry.put = function (entry) {
              if (HashUpdateEntry._hashUpdateEntries.length < MAX_POOL_SIZE) {
                entry.list = entry.entry = entry.target = entry.callback = null;

                HashUpdateEntry._hashUpdateEntries.push(entry);
              }
            };

            HashUpdateEntry._hashUpdateEntries = [];

            var HashTimerEntry = function HashTimerEntry(timers, target, timerIndex, currentTimer, currentTimerSalvaged, paused) {
              this.timers = void 0;
              this.target = void 0;
              this.timerIndex = void 0;
              this.currentTimer = void 0;
              this.currentTimerSalvaged = void 0;
              this.paused = void 0;
              this.timers = timers;
              this.target = target;
              this.timerIndex = timerIndex;
              this.currentTimer = currentTimer;
              this.currentTimerSalvaged = currentTimerSalvaged;
              this.paused = paused;
            };

            HashTimerEntry.get = function (timers, target, timerIndex, currentTimer, currentTimerSalvaged, paused) {
              var result = HashTimerEntry._hashTimerEntries.pop();

              if (result) {
                result.timers = timers;
                result.target = target;
                result.timerIndex = timerIndex;
                result.currentTimer = currentTimer;
                result.currentTimerSalvaged = currentTimerSalvaged;
                result.paused = paused;
              } else {
                result = new HashTimerEntry(timers, target, timerIndex, currentTimer, currentTimerSalvaged, paused);
              }

              return result;
            };

            HashTimerEntry.put = function (entry) {
              if (HashTimerEntry._hashTimerEntries.length < MAX_POOL_SIZE) {
                entry.timers = entry.target = entry.currentTimer = null;

                HashTimerEntry._hashTimerEntries.push(entry);
              }
            };

            HashTimerEntry._hashTimerEntries = [];

            var CallbackTimer = function () {
              function CallbackTimer() {
                this._lock = void 0;
                this._scheduler = void 0;
                this._elapsed = void 0;
                this._runForever = void 0;
                this._useDelay = void 0;
                this._timesExecuted = void 0;
                this._repeat = void 0;
                this._delay = void 0;
                this._interval = void 0;
                this._target = void 0;
                this._callback = void 0;
                this._lock = false;
                this._scheduler = null;
                this._elapsed = -1;
                this._runForever = false;
                this._useDelay = false;
                this._timesExecuted = 0;
                this._repeat = 0;
                this._delay = 0;
                this._interval = 0;
                this._target = null;
                this._callback = null;
              }

              var _proto = CallbackTimer.prototype;

              _proto.initWithCallback = function initWithCallback(scheduler, callback, target, seconds, repeat, delay) {
                this._lock = false;
                this._scheduler = scheduler;
                this._target = target;
                this._callback = callback;
                this._elapsed = -1;
                this._interval = seconds;
                this._delay = delay;
                this._useDelay = this._delay > 0;
                this._repeat = repeat;
                this._runForever = this._repeat === legacyCC.macro.REPEAT_FOREVER;
                return true;
              };

              _proto.getInterval = function getInterval() {
                return this._interval;
              };

              _proto.setInterval = function setInterval(interval) {
                this._interval = interval;
              };

              _proto.update = function update(dt) {
                if (this._elapsed === -1) {
                  this._elapsed = 0;
                  this._timesExecuted = 0;
                } else {
                  this._elapsed += dt;

                  if (this._runForever && !this._useDelay) {
                    if (this._elapsed >= this._interval) {
                      this.trigger();
                      this._elapsed = 0;
                    }
                  } else {
                    if (this._useDelay) {
                      if (this._elapsed >= this._delay) {
                        this.trigger();
                        this._elapsed -= this._delay;
                        this._timesExecuted += 1;
                        this._useDelay = false;
                      }
                    } else if (this._elapsed >= this._interval) {
                      this.trigger();
                      this._elapsed = 0;
                      this._timesExecuted += 1;
                    }

                    if (this._callback && !this._runForever && this._timesExecuted > this._repeat) {
                      this.cancel();
                    }
                  }
                }
              };

              _proto.getCallback = function getCallback() {
                return this._callback;
              };

              _proto.trigger = function trigger() {
                if (this._target && this._callback) {
                  this._lock = true;

                  this._callback.call(this._target, this._elapsed);

                  this._lock = false;
                }
              };

              _proto.cancel = function cancel() {
                this._scheduler.unschedule(this._callback, this._target);
              };

              return CallbackTimer;
            }();

            CallbackTimer._timers = [];

            CallbackTimer.get = function () {
              return CallbackTimer._timers.pop() || new CallbackTimer();
            };

            CallbackTimer.put = function (timer) {
              if (CallbackTimer._timers.length < MAX_POOL_SIZE && !timer._lock) {
                timer._scheduler = timer._target = timer._callback = null;

                CallbackTimer._timers.push(timer);
              }
            };

            var Scheduler = exports('Scheduler', function (_System) {
              _inheritsLoose(Scheduler, _System);

              Scheduler.enableForTarget = function enableForTarget(target) {
                var found = false;

                if (target.uuid) {
                  found = true;
                } else if (target.id) {
                  found = true;
                }

                if (!found) {
                  if (target.__instanceId) {
                    warnID(1513);
                  } else {
                    target.id = idGenerator$4.getNewId();
                  }
                }
              };

              function Scheduler() {
                var _this;

                _this = _System.call(this) || this;
                _this._timeScale = void 0;
                _this._updatesNegList = void 0;
                _this._updates0List = void 0;
                _this._updatesPosList = void 0;
                _this._hashForUpdates = void 0;
                _this._hashForTimers = void 0;
                _this._currentTarget = void 0;
                _this._currentTargetSalvaged = void 0;
                _this._updateHashLocked = void 0;
                _this._arrayForTimers = void 0;
                _this._timeScale = 1.0;
                _this._updatesNegList = [];
                _this._updates0List = [];
                _this._updatesPosList = [];
                _this._hashForUpdates = createMap(true);
                _this._hashForTimers = createMap(true);
                _this._currentTarget = null;
                _this._currentTargetSalvaged = false;
                _this._updateHashLocked = false;
                _this._arrayForTimers = [];
                return _this;
              }

              var _proto2 = Scheduler.prototype;

              _proto2.setTimeScale = function setTimeScale(timeScale) {
                this._timeScale = timeScale;
              };

              _proto2.getTimeScale = function getTimeScale() {
                return this._timeScale;
              };

              _proto2.update = function update(dt) {
                this._updateHashLocked = true;

                if (this._timeScale !== 1) {
                  dt *= this._timeScale;
                }

                var i;
                var list;
                var len;
                var entry;

                for (i = 0, list = this._updatesNegList, len = list.length; i < len; i++) {
                  entry = list[i];

                  if (!entry.paused && !entry.markedForDeletion) {
                    entry.target.update(dt);
                  }
                }

                for (i = 0, list = this._updates0List, len = list.length; i < len; i++) {
                  entry = list[i];

                  if (!entry.paused && !entry.markedForDeletion) {
                    entry.target.update(dt);
                  }
                }

                for (i = 0, list = this._updatesPosList, len = list.length; i < len; i++) {
                  entry = list[i];

                  if (!entry.paused && !entry.markedForDeletion) {
                    entry.target.update(dt);
                  }
                }

                var elt;
                var arr = this._arrayForTimers;

                for (i = 0; i < arr.length; i++) {
                  elt = arr[i];
                  this._currentTarget = elt;
                  this._currentTargetSalvaged = false;

                  if (!elt.paused) {
                    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.timers.length === 0) {
                    this._removeHashElement(this._currentTarget);

                    --i;
                  }
                }

                for (i = 0, list = this._updatesNegList; i < list.length;) {
                  entry = list[i];

                  if (entry.markedForDeletion) {
                    this._removeUpdateFromHash(entry);
                  } else {
                    i++;
                  }
                }

                for (i = 0, list = this._updates0List; i < list.length;) {
                  entry = list[i];

                  if (entry.markedForDeletion) {
                    this._removeUpdateFromHash(entry);
                  } else {
                    i++;
                  }
                }

                for (i = 0, list = this._updatesPosList; i < list.length;) {
                  entry = list[i];

                  if (entry.markedForDeletion) {
                    this._removeUpdateFromHash(entry);
                  } else {
                    i++;
                  }
                }

                this._updateHashLocked = false;
                this._currentTarget = null;
              };

              _proto2.schedule = function schedule(callback, target, interval, repeat, delay, paused) {
                if (typeof callback !== 'function') {
                  var tmp = callback;
                  callback = target;
                  target = tmp;
                }

                if (arguments.length === 3 || arguments.length === 4 || arguments.length === 5) {
                  paused = !!repeat;
                  repeat = legacyCC.macro.REPEAT_FOREVER;
                  delay = 0;
                }

                assertID(target, 1502);
                var targetId = target.uuid || target.id;

                if (!targetId) {
                  errorID(1510);
                  return;
                }

                var element = this._hashForTimers[targetId];

                if (!element) {
                  element = HashTimerEntry.get(null, target, 0, null, null, paused);

                  this._arrayForTimers.push(element);

                  this._hashForTimers[targetId] = element;
                } else if (element.paused !== paused) {
                  warnID(1511);
                }

                var timer;
                var i;

                if (element.timers == null) {
                  element.timers = [];
                } else {
                  for (i = 0; i < element.timers.length; ++i) {
                    timer = element.timers[i];

                    if (timer && callback === timer._callback) {
                      logID(1507, timer.getInterval(), interval);
                      timer._interval = interval;
                      return;
                    }
                  }
                }

                timer = CallbackTimer.get();
                timer.initWithCallback(this, callback, target, interval, repeat, delay);
                element.timers.push(timer);

                if (this._currentTarget === element && this._currentTargetSalvaged) {
                  this._currentTargetSalvaged = false;
                }
              };

              _proto2.scheduleUpdate = function scheduleUpdate(target, priority, paused) {
                var targetId = target.uuid || target.id;

                if (!targetId) {
                  errorID(1510);
                  return;
                }

                var hashElement = this._hashForUpdates[targetId];

                if (hashElement && hashElement.entry) {
                  if (hashElement.entry.priority !== priority) {
                    if (this._updateHashLocked) {
                      logID(1506);
                      hashElement.entry.markedForDeletion = false;
                      hashElement.entry.paused = paused;
                      return;
                    } else {
                      this.unscheduleUpdate(target);
                    }
                  } else {
                    hashElement.entry.markedForDeletion = false;
                    hashElement.entry.paused = paused;
                    return;
                  }
                }

                var listElement = ListEntry.get(target, priority, paused, false);
                var ppList;

                if (priority === 0) {
                  ppList = this._updates0List;

                  this._appendIn(ppList, listElement);
                } else {
                  ppList = priority < 0 ? this._updatesNegList : this._updatesPosList;

                  this._priorityIn(ppList, listElement, priority);
                }

                this._hashForUpdates[targetId] = HashUpdateEntry.get(ppList, listElement, target, null);
              };

              _proto2.unschedule = function unschedule(callback, target) {
                if (!target || !callback) {
                  return;
                }

                var targetId = target.uuid || target.id;

                if (!targetId) {
                  errorID(1510);
                  return;
                }

                var self = this;
                var element = self._hashForTimers[targetId];

                if (element) {
                  var timers = element.timers;

                  for (var i = 0, li = timers.length; i < li; i++) {
                    var timer = timers[i];

                    if (callback === timer._callback) {
                      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 (self._currentTarget === element) {
                          self._currentTargetSalvaged = true;
                        } else {
                          self._removeHashElement(element);
                        }
                      }

                      return;
                    }
                  }
                }
              };

              _proto2.unscheduleUpdate = function unscheduleUpdate(target) {
                if (!target) {
                  return;
                }

                var targetId = target.uuid || target.id;

                if (!targetId) {
                  errorID(1510);
                  return;
                }

                var element = this._hashForUpdates[targetId];

                if (element) {
                  if (this._updateHashLocked) {
                    element.entry.markedForDeletion = true;
                  } else {
                    this._removeUpdateFromHash(element.entry);
                  }
                }
              };

              _proto2.unscheduleAllForTarget = function unscheduleAllForTarget(target) {
                if (!target) {
                  return;
                }

                var targetId = target.uuid || target.id;

                if (!targetId) {
                  errorID(1510);
                  return;
                }

                var element = this._hashForTimers[targetId];

                if (element) {
                  var timers = element.timers;

                  if (timers.indexOf(element.currentTimer) > -1 && !element.currentTimerSalvaged) {
                    element.currentTimerSalvaged = true;
                  }

                  for (var i = 0, l = timers.length; i < l; i++) {
                    CallbackTimer.put(timers[i]);
                  }

                  timers.length = 0;

                  if (this._currentTarget === element) {
                    this._currentTargetSalvaged = true;
                  } else {
                    this._removeHashElement(element);
                  }
                }

                this.unscheduleUpdate(target);
              };

              _proto2.unscheduleAll = function unscheduleAll() {
                this.unscheduleAllWithMinPriority(legacyCC.Scheduler.PRIORITY_SYSTEM);
              };

              _proto2.unscheduleAllWithMinPriority = function unscheduleAllWithMinPriority(minPriority) {
                var i;
                var element;
                var arr = this._arrayForTimers;

                for (i = arr.length - 1; i >= 0; i--) {
                  element = arr[i];
                  this.unscheduleAllForTarget(element.target);
                }

                var entry;
                var temp_length = 0;

                if (minPriority < 0) {
                  for (i = 0; i < this._updatesNegList.length;) {
                    temp_length = this._updatesNegList.length;
                    entry = this._updatesNegList[i];

                    if (entry && entry.priority >= minPriority) {
                      this.unscheduleUpdate(entry.target);
                    }

                    if (temp_length === this._updatesNegList.length) {
                      i++;
                    }
                  }
                }

                if (minPriority <= 0) {
                  for (i = 0; i < this._updates0List.length;) {
                    temp_length = this._updates0List.length;
                    entry = this._updates0List[i];

                    if (entry) {
                      this.unscheduleUpdate(entry.target);
                    }

                    if (temp_length === this._updates0List.length) {
                      i++;
                    }
                  }
                }

                for (i = 0; i < this._updatesPosList.length;) {
                  temp_length = this._updatesPosList.length;
                  entry = this._updatesPosList[i];

                  if (entry && entry.priority >= minPriority) {
                    this.unscheduleUpdate(entry.target);
                  }

                  if (temp_length === this._updatesPosList.length) {
                    i++;
                  }
                }
              };

              _proto2.isScheduled = function isScheduled(callback, target) {
                assertID(callback, 1508);
                assertID(target, 1509);
                var targetId = target.uuid || target.id;

                if (!targetId) {
                  errorID(1510);
                  return;
                }

                var element = this._hashForTimers[targetId];

                if (!element) {
                  return false;
                }

                if (element.timers == null) {
                  return false;
                } else {
                  var timers = element.timers;

                  for (var i = 0; i < timers.length; ++i) {
                    var timer = timers[i];

                    if (callback === timer._callback) {
                      return true;
                    }
                  }

                  return false;
                }
              };

              _proto2.pauseAllTargets = function pauseAllTargets() {
                return this.pauseAllTargetsWithMinPriority(legacyCC.Scheduler.PRIORITY_SYSTEM);
              };

              _proto2.pauseAllTargetsWithMinPriority = function pauseAllTargetsWithMinPriority(minPriority) {
                var idsWithSelectors = [];
                var self = this;
                var element;
                var locArrayForTimers = self._arrayForTimers;
                var i;
                var li;

                for (i = 0, li = locArrayForTimers.length; i < li; i++) {
                  element = locArrayForTimers[i];

                  if (element) {
                    element.paused = true;
                    idsWithSelectors.push(element.target);
                  }
                }

                var entry;

                if (minPriority < 0) {
                  for (i = 0; i < this._updatesNegList.length; i++) {
                    entry = this._updatesNegList[i];

                    if (entry) {
                      if (entry.priority >= minPriority) {
                        entry.paused = true;
                        idsWithSelectors.push(entry.target);
                      }
                    }
                  }
                }

                if (minPriority <= 0) {
                  for (i = 0; i < this._updates0List.length; i++) {
                    entry = this._updates0List[i];

                    if (entry) {
                      entry.paused = true;
                      idsWithSelectors.push(entry.target);
                    }
                  }
                }

                for (i = 0; i < this._updatesPosList.length; i++) {
                  entry = this._updatesPosList[i];

                  if (entry) {
                    if (entry.priority >= minPriority) {
                      entry.paused = true;
                      idsWithSelectors.push(entry.target);
                    }
                  }
                }

                return idsWithSelectors;
              };

              _proto2.resumeTargets = function resumeTargets(targetsToResume) {
                if (!targetsToResume) {
                  return;
                }

                for (var i = 0; i < targetsToResume.length; i++) {
                  this.resumeTarget(targetsToResume[i]);
                }
              };

              _proto2.pauseTarget = function pauseTarget(target) {
                assertID(target, 1503);
                var targetId = target.uuid || target.id;

                if (!targetId) {
                  errorID(1510);
                  return;
                }

                var self = this;
                var element = self._hashForTimers[targetId];

                if (element) {
                  element.paused = true;
                }

                var elementUpdate = self._hashForUpdates[targetId];

                if (elementUpdate) {
                  elementUpdate.entry.paused = true;
                }
              };

              _proto2.resumeTarget = function resumeTarget(target) {
                assertID(target, 1504);
                var targetId = target.uuid || target.id;

                if (!targetId) {
                  errorID(1510);
                  return;
                }

                var self = this;
                var element = self._hashForTimers[targetId];

                if (element) {
                  element.paused = false;
                }

                var elementUpdate = self._hashForUpdates[targetId];

                if (elementUpdate) {
                  elementUpdate.entry.paused = false;
                }
              };

              _proto2.isTargetPaused = function isTargetPaused(target) {
                assertID(target, 1505);
                var targetId = target.uuid || target.id;

                if (!targetId) {
                  errorID(1510);
                  return false;
                }

                var element = this._hashForTimers[targetId];

                if (element) {
                  return element.paused;
                }

                var elementUpdate = this._hashForUpdates[targetId];

                if (elementUpdate) {
                  return elementUpdate.entry.paused;
                }

                return false;
              };

              _proto2._removeHashElement = function _removeHashElement(element) {
                var targetId = element.target.uuid || element.target.id;
                delete this._hashForTimers[targetId];
                var arr = this._arrayForTimers;

                for (var i = 0, l = arr.length; i < l; i++) {
                  if (arr[i] === element) {
                    arr.splice(i, 1);
                    break;
                  }
                }

                HashTimerEntry.put(element);
              };

              _proto2._removeUpdateFromHash = function _removeUpdateFromHash(entry) {
                var targetId = entry.target.uuid || entry.target.id;
                var self = this;
                var element = self._hashForUpdates[targetId];

                if (element) {
                  var list = element.list;
                  var listEntry = element.entry;

                  for (var i = 0, l = list.length; i < l; i++) {
                    if (list[i] === listEntry) {
                      list.splice(i, 1);
                      break;
                    }
                  }

                  delete self._hashForUpdates[targetId];
                  ListEntry.put(listEntry);
                  HashUpdateEntry.put(element);
                }
              };

              _proto2._priorityIn = function _priorityIn(ppList, listElement, priority) {
                for (var i = 0; i < ppList.length; i++) {
                  if (priority < ppList[i].priority) {
                    ppList.splice(i, 0, listElement);
                    return;
                  }
                }

                ppList.push(listElement);
              };

              _proto2._appendIn = function _appendIn(ppList, listElement) {
                ppList.push(listElement);
              };

              return Scheduler;
            }(System$1));
            Scheduler.PRIORITY_SYSTEM = 1 << 31;
            Scheduler.PRIORITY_NON_SYSTEM = Scheduler.PRIORITY_SYSTEM + 1;
            Scheduler.ID = 'scheduler';
            legacyCC.Scheduler = Scheduler;

            var RenderWindow = function () {
              RenderWindow.registerCreateFunc = function registerCreateFunc(root) {
                root._createWindowFun = function (_root) {
                  return new RenderWindow(_root);
                };
              };

              function RenderWindow(root) {
                this._title = '';
                this._width = 1;
                this._height = 1;
                this._nativeWidth = 1;
                this._nativeHeight = 1;
                this._renderPass = null;
                this._colorTextures = [];
                this._depthStencilTexture = null;
                this._swapchainBufferIndices = 0;
                this._shouldSyncSizeWithSwapchain = false;
                this._poolHandle = NULL_HANDLE;
                this._cameras = [];
              }

              var _proto = RenderWindow.prototype;

              _proto.initialize = function initialize(device, info) {
                this._poolHandle = RenderWindowPool.alloc();

                if (info.title !== undefined) {
                  this._title = info.title;
                }

                if (info.swapchainBufferIndices !== undefined) {
                  this._swapchainBufferIndices = info.swapchainBufferIndices;
                }

                if (info.shouldSyncSizeWithSwapchain !== undefined) {
                  this._shouldSyncSizeWithSwapchain = info.shouldSyncSizeWithSwapchain;
                }

                this._width = info.width;
                this._height = info.height;
                this._nativeWidth = this._width;
                this._nativeHeight = this._height;
                var _info$renderPassInfo = info.renderPassInfo,
                    colorAttachments = _info$renderPassInfo.colorAttachments,
                    depthStencilAttachment = _info$renderPassInfo.depthStencilAttachment;

                for (var i = 0; i < colorAttachments.length; i++) {
                  if (colorAttachments[i].format === Format.UNKNOWN) {
                    colorAttachments[i].format = device.colorFormat;
                  }
                }

                if (depthStencilAttachment && depthStencilAttachment.format === Format.UNKNOWN) {
                  depthStencilAttachment.format = device.depthStencilFormat;
                }

                this._renderPass = device.createRenderPass(info.renderPassInfo);

                for (var _i = 0; _i < colorAttachments.length; _i++) {
                  var colorTex = null;

                  if (!(this._swapchainBufferIndices & 1 << _i)) {
                    colorTex = device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.COLOR_ATTACHMENT | TextureUsageBit.SAMPLED, colorAttachments[_i].format, this._width, this._height));
                    RenderWindowPool.set(this._poolHandle, RenderWindowView.HAS_OFF_SCREEN_ATTACHMENTS, 1);
                  } else {
                    RenderWindowPool.set(this._poolHandle, RenderWindowView.HAS_ON_SCREEN_ATTACHMENTS, 1);
                  }

                  this._colorTextures.push(colorTex);
                }

                if (depthStencilAttachment) {
                  if (this._swapchainBufferIndices >= 0) {
                    this._depthStencilTexture = device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.DEPTH_STENCIL_ATTACHMENT | TextureUsageBit.SAMPLED, depthStencilAttachment.format, this._width, this._height));
                    RenderWindowPool.set(this._poolHandle, RenderWindowView.HAS_OFF_SCREEN_ATTACHMENTS, 1);
                  } else {
                    RenderWindowPool.set(this._poolHandle, RenderWindowView.HAS_ON_SCREEN_ATTACHMENTS, 1);
                  }
                }

                var hFBO = FramebufferPool.alloc(device, new FramebufferInfo(this._renderPass, this._colorTextures, this._depthStencilTexture));
                RenderWindowPool.set(this._poolHandle, RenderWindowView.FRAMEBUFFER, hFBO);
                return true;
              };

              _proto.destroy = function destroy() {
                this.clearCameras();

                if (this._depthStencilTexture) {
                  this._depthStencilTexture.destroy();

                  this._depthStencilTexture = null;
                }

                for (var i = 0; i < this._colorTextures.length; i++) {
                  var colorTexture = this._colorTextures[i];

                  if (colorTexture) {
                    colorTexture.destroy();
                  }
                }

                this._colorTextures.length = 0;

                if (this._poolHandle) {
                  FramebufferPool.get(RenderWindowPool.get(this._poolHandle, RenderWindowView.FRAMEBUFFER)).destroy();
                  this._poolHandle = NULL_HANDLE;
                }
              };

              _proto.resize = function resize(width, height) {
                this._width = width;
                this._height = height;

                if (width > this._nativeWidth || height > this._nativeHeight) {
                  this._nativeWidth = width;
                  this._nativeHeight = height;
                  var needRebuild = false;

                  if (this._depthStencilTexture) {
                    this._depthStencilTexture.resize(width, height);

                    needRebuild = true;
                  }

                  for (var i = 0; i < this._colorTextures.length; i++) {
                    var colorTex = this._colorTextures[i];

                    if (colorTex) {
                      colorTex.resize(width, height);
                      needRebuild = true;
                    }
                  }

                  var framebuffer = FramebufferPool.get(RenderWindowPool.get(this._poolHandle, RenderWindowView.FRAMEBUFFER));

                  if (needRebuild && framebuffer) {
                    framebuffer.destroy();
                    framebuffer.initialize(new FramebufferInfo(this._renderPass, this._colorTextures, this._depthStencilTexture));
                  }
                }

                for (var _iterator = _createForOfIteratorHelperLoose(this._cameras), _step; !(_step = _iterator()).done;) {
                  var camera = _step.value;

                  if (camera.isWindowSize) {
                    camera.resize(width, height);
                  }
                }
              };

              _proto.extractRenderCameras = function extractRenderCameras(cameras) {
                for (var j = 0; j < this._cameras.length; j++) {
                  var camera = this._cameras[j];

                  if (camera.enabled) {
                    camera.update();
                    cameras.push(camera);
                  }
                }
              };

              _proto.attachCamera = function attachCamera(camera) {
                for (var i = 0; i < this._cameras.length; i++) {
                  if (this._cameras[i] === camera) {
                    return;
                  }
                }

                this._cameras.push(camera);

                this.sortCameras();
              };

              _proto.detachCamera = function detachCamera(camera) {
                for (var i = 0; i < this._cameras.length; ++i) {
                  if (this._cameras[i] === camera) {
                    this._cameras.splice(i, 1);

                    return;
                  }
                }
              };

              _proto.clearCameras = function clearCameras() {
                this._cameras.length = 0;
              };

              _proto.sortCameras = function sortCameras() {
                this._cameras.sort(function (a, b) {
                  return a.priority - b.priority;
                });
              };

              _createClass(RenderWindow, [{
                key: "width",
                get: function get() {
                  return this._width;
                }
              }, {
                key: "height",
                get: function get() {
                  return this._height;
                }
              }, {
                key: "framebuffer",
                get: function get() {
                  return FramebufferPool.get(RenderWindowPool.get(this._poolHandle, RenderWindowView.FRAMEBUFFER));
                }
              }, {
                key: "shouldSyncSizeWithSwapchain",
                get: function get() {
                  return this._shouldSyncSizeWithSwapchain;
                }
              }, {
                key: "hasOnScreenAttachments",
                get: function get() {
                  return RenderWindowPool.get(this._poolHandle, RenderWindowView.HAS_ON_SCREEN_ATTACHMENTS) === 1;
                }
              }, {
                key: "hasOffScreenAttachments",
                get: function get() {
                  return RenderWindowPool.get(this._poolHandle, RenderWindowView.HAS_OFF_SCREEN_ATTACHMENTS) === 1;
                }
              }, {
                key: "handle",
                get: function get() {
                  return this._poolHandle;
                }
              }, {
                key: "cameras",
                get: function get() {
                  return this._cameras;
                }
              }]);

              return RenderWindow;
            }();

            var Root = function () {
              function Root(device) {
                var _this = this;

                this._createSceneFun = null;
                this._createWindowFun = null;
                this._device = void 0;
                this._windows = [];
                this._mainWindow = null;
                this._curWindow = null;
                this._tempWindow = null;
                this._pipeline = null;
                this._batcher = null;
                this._dataPoolMgr = void 0;
                this._scenes = [];
                this._modelPools = new Map();
                this._cameraPool = null;
                this._lightPools = new Map();
                this._fpsTime = 0;
                this._frameCount = 0;
                this._fps = 0;
                this._fixedFPS = 0;
                this._fixedFPSFrameTime = 0;
                this._poolHandle = NULL_HANDLE;
                this._useDeferredPipeline = false;
                this._device = device;
                this._dataPoolMgr = legacyCC.internal.DataPoolManager && new legacyCC.internal.DataPoolManager(device);
                RenderScene.registerCreateFunc(this);
                RenderWindow.registerCreateFunc(this);
                this._cameraPool = new Pool$1(function () {
                  return new Camera(_this._device);
                }, 4);
              }

              var _proto = Root.prototype;

              _proto.initialize = function initialize(info) {
                var _this2 = this;

                this._poolHandle = RootPool.alloc();
                var colorAttachment = new ColorAttachment();
                var depthStencilAttachment = new DepthStencilAttachment();
                depthStencilAttachment.depthStoreOp = StoreOp.DISCARD;
                depthStencilAttachment.stencilStoreOp = StoreOp.DISCARD;
                var renderPassInfo = new RenderPassInfo([colorAttachment], depthStencilAttachment);
                this._mainWindow = this.createWindow({
                  title: 'rootMainWindow',
                  width: this._device.width,
                  height: this._device.height,
                  renderPassInfo: renderPassInfo,
                  swapchainBufferIndices: -1
                });
                this._curWindow = this._mainWindow;
                return Promise.resolve(builtinResMgr.initBuiltinRes(this._device)).then(function () {
                  legacyCC.view.on('design-resolution-changed', function () {
                    var width = legacyCC.game.canvas.width;
                    var height = legacyCC.game.canvas.height;

                    _this2.resize(width, height);
                  }, _this2);
                });
              };

              _proto.destroy = function destroy() {
                this.destroyScenes();

                if (this._pipeline) {
                  this._pipeline.destroy();

                  this._pipeline = null;
                }

                if (this._batcher) {
                  this._batcher.destroy();

                  this._batcher = null;
                }

                this._curWindow = null;
                this._mainWindow = null;
                this.dataPoolManager.clear();

                if (this._poolHandle) {
                  RootPool.free(this._poolHandle);
                  this._poolHandle = NULL_HANDLE;
                }
              };

              _proto.resize = function resize(width, height) {
                this._device.resize(width, height);

                this._mainWindow.resize(width, height);

                for (var _iterator = _createForOfIteratorHelperLoose(this._windows), _step; !(_step = _iterator()).done;) {
                  var window = _step.value;

                  if (window.shouldSyncSizeWithSwapchain) {
                    window.resize(width, height);
                  }
                }

                if (this._pipeline) {
                  this._pipeline.resize(width, height);
                }
              };

              _proto.setRenderPipeline = function setRenderPipeline(rppl) {
                if (rppl instanceof DeferredPipeline) {
                  this._useDeferredPipeline = true;
                }

                if (!rppl) {
                  rppl = createDefaultPipeline();
                }

                this._pipeline = rppl;

                if (!this._pipeline.activate()) {
                  return false;
                }

                var scene = legacyCC.director.getScene();

                if (scene) {
                  scene.globals.activate();
                }

                this.onGlobalPipelineStateChanged();

                if (!this._batcher && legacyCC.internal.Batcher2D) {
                  this._batcher = new legacyCC.internal.Batcher2D(this);

                  if (!this._batcher.initialize()) {
                    this.destroy();
                    return false;
                  }
                }

                return true;
              };

              _proto.onGlobalPipelineStateChanged = function onGlobalPipelineStateChanged() {
                for (var i = 0; i < this._scenes.length; i++) {
                  this._scenes[i].onGlobalPipelineStateChanged();
                }

                this._pipeline.pipelineSceneData.initDeferredPassInfo();
              };

              _proto.activeWindow = function activeWindow(window) {
                this._curWindow = window;
              };

              _proto.resetCumulativeTime = function resetCumulativeTime() {
                RootPool.set(this._poolHandle, RootView.CUMULATIVE_TIME, 0);
              };

              _proto.frameMove = function frameMove(deltaTime) {
                RootPool.set(this._poolHandle, RootView.FRAME_TIME, deltaTime);
                ++this._frameCount;
                RootPool.set(this._poolHandle, RootView.CUMULATIVE_TIME, RootPool.get(this._poolHandle, RootView.CUMULATIVE_TIME) + deltaTime);
                this._fpsTime += deltaTime;

                if (this._fpsTime > 1.0) {
                  this._fps = this._frameCount;
                  this._frameCount = 0;
                  this._fpsTime = 0.0;
                }

                for (var i = 0; i < this._scenes.length; ++i) {
                  this._scenes[i].removeBatches();
                }

                if (this._batcher) this._batcher.update();
                var windows = this._windows;
                var cameraList = [];

                for (var _i = 0; _i < windows.length; _i++) {
                  var window = windows[_i];
                  window.extractRenderCameras(cameraList);
                }

                if (this._pipeline && cameraList.length > 0) {
                  this._device.acquire();

                  var scenes = this._scenes;
                  var stamp = legacyCC.director.getTotalFrames();
                  if (this._batcher) this._batcher.uploadBuffers();

                  for (var _i2 = 0; _i2 < scenes.length; _i2++) {
                    scenes[_i2].update(stamp);
                  }

                  legacyCC.director.emit(legacyCC.Director.EVENT_BEFORE_COMMIT);
                  cameraList.sort(function (a, b) {
                    return a.priority - b.priority;
                  });

                  this._pipeline.render(cameraList);

                  this._device.present();
                }

                if (this._batcher) this._batcher.reset();
              };

              _proto.createWindow = function createWindow(info) {
                var window = this._createWindowFun(this);

                window.initialize(this.device, info);

                this._windows.push(window);

                return window;
              };

              _proto.destroyWindow = function destroyWindow(window) {
                for (var i = 0; i < this._windows.length; ++i) {
                  if (this._windows[i] === window) {
                    window.destroy();

                    this._windows.splice(i, 1);

                    return;
                  }
                }
              };

              _proto.destroyWindows = function destroyWindows() {
                for (var _iterator2 = _createForOfIteratorHelperLoose(this._windows), _step2; !(_step2 = _iterator2()).done;) {
                  var window = _step2.value;
                  window.destroy();
                }

                this._windows = [];
              };

              _proto.createScene = function createScene(info) {
                var scene = this._createSceneFun(this);

                scene.initialize(info);

                this._scenes.push(scene);

                return scene;
              };

              _proto.destroyScene = function destroyScene(scene) {
                for (var i = 0; i < this._scenes.length; ++i) {
                  if (this._scenes[i] === scene) {
                    scene.destroy();

                    this._scenes.splice(i, 1);

                    return;
                  }
                }
              };

              _proto.destroyScenes = function destroyScenes() {
                for (var _iterator3 = _createForOfIteratorHelperLoose(this._scenes), _step3; !(_step3 = _iterator3()).done;) {
                  var scene = _step3.value;
                  scene.destroy();
                }

                this._scenes = [];
              };

              _proto.createModel = function createModel(ModelCtor) {
                var p = this._modelPools.get(ModelCtor);

                if (!p) {
                  this._modelPools.set(ModelCtor, new Pool$1(function () {
                    return new ModelCtor();
                  }, 10));

                  p = this._modelPools.get(ModelCtor);
                }

                var model = p.alloc();
                model.initialize();
                return model;
              };

              _proto.destroyModel = function destroyModel(m) {
                var p = this._modelPools.get(m.constructor);

                if (p) {
                  p.free(m);
                  m.destroy();

                  if (m.scene) {
                    m.scene.removeModel(m);
                  }
                } else {
                  warnID(1300, m.constructor.name);
                }
              };

              _proto.createCamera = function createCamera() {
                return this._cameraPool.alloc();
              };

              _proto.createLight = function createLight(LightCtor) {
                var l = this._lightPools.get(LightCtor);

                if (!l) {
                  this._lightPools.set(LightCtor, new Pool$1(function () {
                    return new LightCtor();
                  }, 4));

                  l = this._lightPools.get(LightCtor);
                }

                var light = l.alloc();
                light.initialize();
                return light;
              };

              _proto.destroyLight = function destroyLight(l) {
                var p = this._lightPools.get(l.constructor);

                l.destroy();

                if (p) {
                  p.free(l);

                  if (l.scene) {
                    switch (l.type) {
                      case LightType.SPHERE:
                        l.scene.removeSphereLight(l);
                        break;

                      case LightType.SPOT:
                        l.scene.removeSpotLight(l);
                        break;
                    }
                  }
                }
              };

              _createClass(Root, [{
                key: "device",
                get: function get() {
                  return this._device;
                }
              }, {
                key: "mainWindow",
                get: function get() {
                  return this._mainWindow;
                }
              }, {
                key: "curWindow",
                get: function get() {
                  return this._curWindow;
                },
                set: function set(window) {
                  this._curWindow = window;
                }
              }, {
                key: "tempWindow",
                get: function get() {
                  return this._tempWindow;
                },
                set: function set(window) {
                  this._tempWindow = window;
                }
              }, {
                key: "windows",
                get: function get() {
                  return this._windows;
                }
              }, {
                key: "pipeline",
                get: function get() {
                  return this._pipeline;
                }
              }, {
                key: "batcher2D",
                get: function get() {
                  return this._batcher;
                }
              }, {
                key: "scenes",
                get: function get() {
                  return this._scenes;
                }
              }, {
                key: "cumulativeTime",
                get: function get() {
                  return RootPool.get(this._poolHandle, RootView.CUMULATIVE_TIME);
                }
              }, {
                key: "frameTime",
                get: function get() {
                  return RootPool.get(this._poolHandle, RootView.FRAME_TIME);
                }
              }, {
                key: "frameCount",
                get: function get() {
                  return this._frameCount;
                }
              }, {
                key: "fps",
                get: function get() {
                  return this._fps;
                }
              }, {
                key: "fixedFPS",
                get: function get() {
                  return this._fixedFPS;
                },
                set: function set(fps) {
                  if (fps > 0) {
                    this._fixedFPS = fps;
                    this._fixedFPSFrameTime = 1000.0 / fps;
                  } else {
                    this._fixedFPSFrameTime = 0;
                  }
                }
              }, {
                key: "dataPoolManager",
                get: function get() {
                  return this._dataPoolMgr;
                }
              }, {
                key: "handle",
                get: function get() {
                  return this._poolHandle;
                }
              }, {
                key: "useDeferredPipeline",
                get: function get() {
                  return this._useDeferredPipeline;
                }
              }]);

              return Root;
            }();
            legacyCC.Root = Root;

            var 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(EventTouch.prototype, 'EventTouch.prototype', [{
              name: 'getUILocationInView',
              newName: 'getLocationInView',
              target: EventTouch,
              targetName: 'EventTouch'
            }]);
            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'
            }]);
            replaceProperty(Root.prototype, 'Root.prototype', [{
              name: 'ui',
              newName: 'batcher2D'
            }]);

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

            var _dec$x, _class$x, _class2$w, _temp$w;
            var BufferAsset = exports('BufferAsset', (_dec$x = ccclass('cc.BufferAsset'), _dec$x(_class$x = (_class2$w = (_temp$w = function (_Asset) {
              _inheritsLoose(BufferAsset, _Asset);

              function BufferAsset() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;
                _this._buffer = null;
                return _this;
              }

              var _proto = BufferAsset.prototype;

              _proto.buffer = function buffer() {
                return this._buffer;
              };

              _proto.validate = function validate() {
                return !!this.buffer;
              };

              _createClass(BufferAsset, [{
                key: "_nativeAsset",
                get: function get() {
                  return this._buffer;
                },
                set: function set(bin) {
                  if (bin instanceof ArrayBuffer) {
                    this._buffer = bin;
                  } else {
                    this._buffer = bin.buffer;
                  }
                }
              }]);

              return BufferAsset;
            }(Asset), _temp$w), (_applyDecoratedDescriptor(_class2$w.prototype, "_nativeAsset", [override], Object.getOwnPropertyDescriptor(_class2$w.prototype, "_nativeAsset"), _class2$w.prototype)), _class2$w)) || _class$x));
            legacyCC.BufferAsset = BufferAsset;

            var _typeMap2;

            var _typeMap = (_typeMap2 = {}, _typeMap2[FormatType.UNORM] = 'Uint', _typeMap2[FormatType.SNORM] = 'Int', _typeMap2[FormatType.UINT] = 'Uint', _typeMap2[FormatType.INT] = 'Int', _typeMap2[FormatType.UFLOAT] = 'Float', _typeMap2[FormatType.FLOAT] = 'Float', _typeMap2["default"] = 'Uint', _typeMap2);

            function _getDataViewType(info) {
              var type = _typeMap[info.type] || _typeMap["default"];
              var bytes = info.size / info.count * 8;
              return "" + type + bytes;
            }

            function writeBuffer(target, data, format, offset, stride) {
              if (format === void 0) {
                format = Format.R32F;
              }

              if (offset === void 0) {
                offset = 0;
              }

              if (stride === void 0) {
                stride = 0;
              }

              var info = FormatInfos[format];

              if (!stride) {
                stride = info.size;
              }

              var writer = "set" + _getDataViewType(info);

              var componentBytesLength = info.size / info.count;
              var nSeg = Math.floor(data.length / info.count);
              var isLittleEndian = sys.isLittleEndian;

              for (var iSeg = 0; iSeg < nSeg; ++iSeg) {
                var x = offset + stride * iSeg;

                for (var iComponent = 0; iComponent < info.count; ++iComponent) {
                  var y = x + componentBytesLength * iComponent;
                  target[writer](y, data[info.count * iSeg + iComponent], isLittleEndian);
                }
              }
            }
            function mapBuffer(target, callback, format, offset, length, stride, out) {
              if (format === void 0) {
                format = Format.R32F;
              }

              if (offset === void 0) {
                offset = 0;
              }

              if (length === void 0) {
                length = target.byteLength - offset;
              }

              if (stride === void 0) {
                stride = 0;
              }

              if (!out) {
                out = new DataView(target.buffer.slice(target.byteOffset, target.byteOffset + target.byteLength));
              }

              var info = FormatInfos[format];

              if (!stride) {
                stride = info.size;
              }

              var writer = "set" + _getDataViewType(info);

              var reader = "get" + _getDataViewType(info);

              var componentBytesLength = info.size / info.count;
              var nSeg = Math.floor(length / stride);
              var isLittleEndian = sys.isLittleEndian;

              for (var iSeg = 0; iSeg < nSeg; ++iSeg) {
                var x = offset + stride * iSeg;

                for (var iComponent = 0; iComponent < info.count; ++iComponent) {
                  var y = x + componentBytesLength * iComponent;

                  var _cur = target[reader](y, isLittleEndian);

                  out[writer](y, callback(_cur, iComponent, target), isLittleEndian);
                }
              }

              return out;
            }

            var RenderingSubMesh = exports('RenderingSubMesh', function () {
              function RenderingSubMesh(vertexBuffers, attributes, primitiveMode, indexBuffer, indirectBuffer) {
                if (indexBuffer === void 0) {
                  indexBuffer = null;
                }

                if (indirectBuffer === void 0) {
                  indirectBuffer = null;
                }

                this.mesh = void 0;
                this.subMeshIdx = void 0;
                this._flatBuffers = [];
                this._jointMappedBuffers = void 0;
                this._jointMappedBufferIndices = void 0;
                this._vertexIdChannel = void 0;
                this._geometricInfo = void 0;
                this._vertexBuffers = void 0;
                this._attributes = void 0;
                this._indexBuffer = null;
                this._indirectBuffer = null;
                this._primitiveMode = void 0;
                this._iaInfo = void 0;
                this._handle = NULL_HANDLE;
                this._attributes = attributes;
                this._vertexBuffers = vertexBuffers;
                this._indexBuffer = indexBuffer;
                this._indirectBuffer = indirectBuffer;
                this._primitiveMode = primitiveMode;
                this._iaInfo = new InputAssemblerInfo(attributes, vertexBuffers, indexBuffer, indirectBuffer);
                this._handle = SubMeshPool.alloc();
                var fbArrayHandle = FlatBufferArrayPool.alloc();
                SubMeshPool.set(this._handle, SubMeshView.FLAT_BUFFER_ARRAY, fbArrayHandle);
              }

              var _proto = RenderingSubMesh.prototype;

              _proto.genFlatBuffers = function genFlatBuffers() {
                if (this._flatBuffers.length || !this.mesh || this.subMeshIdx === undefined) {
                  return;
                }

                var mesh = this.mesh;
                var idxCount = 0;
                var prim = mesh.struct.primitives[this.subMeshIdx];
                var fbArrayHandle = SubMeshPool.get(this._handle, SubMeshView.FLAT_BUFFER_ARRAY);

                if (prim.indexView) {
                  idxCount = prim.indexView.count;
                }

                for (var i = 0; i < prim.vertexBundelIndices.length; i++) {
                  var bundleIdx = prim.vertexBundelIndices[i];
                  var vertexBundle = mesh.struct.vertexBundles[bundleIdx];
                  var vbCount = prim.indexView ? prim.indexView.count : vertexBundle.view.count;
                  var vbStride = vertexBundle.view.stride;
                  var vbSize = vbStride * vbCount;
                  var view = new Uint8Array(mesh.data.buffer, vertexBundle.view.offset, vertexBundle.view.length);
                  var hBuffer = RawBufferPool.alloc(prim.indexView ? vbSize : vertexBundle.view.length);
                  var hFlatBuffer = FlatBufferPool.alloc();
                  FlatBufferPool.set(hFlatBuffer, FlatBufferView.STRIDE, vbStride);
                  FlatBufferPool.set(hFlatBuffer, FlatBufferView.AMOUNT, vbCount);
                  FlatBufferPool.set(hFlatBuffer, FlatBufferView.BUFFER, hBuffer);
                  FlatBufferArrayPool.push(fbArrayHandle, hFlatBuffer);
                  var buffer = RawBufferPool.getBuffer(hBuffer);
                  var sharedView = new Uint8Array(buffer);

                  if (!prim.indexView) {
                    sharedView.set(mesh.data.subarray(vertexBundle.view.offset, vertexBundle.view.offset + vertexBundle.view.length));

                    this._flatBuffers.push({
                      stride: vbStride,
                      count: vbCount,
                      buffer: sharedView
                    });

                    continue;
                  }

                  var ibView = mesh.readIndices(this.subMeshIdx);

                  for (var n = 0; n < idxCount; ++n) {
                    var idx = ibView[n];
                    var offset = n * vbStride;
                    var srcOffset = idx * vbStride;

                    for (var m = 0; m < vbStride; ++m) {
                      sharedView[offset + m] = view[srcOffset + m];
                    }
                  }

                  this._flatBuffers.push({
                    stride: vbStride,
                    count: vbCount,
                    buffer: sharedView
                  });
                }
              };

              _proto.destroy = function destroy() {
                for (var i = 0; i < this.vertexBuffers.length; i++) {
                  this.vertexBuffers[i].destroy();
                }

                this.vertexBuffers.length = 0;

                if (this._indexBuffer) {
                  this._indexBuffer.destroy();

                  this._indexBuffer = null;
                }

                if (this._jointMappedBuffers && this._jointMappedBufferIndices) {
                  for (var _i = 0; _i < this._jointMappedBufferIndices.length; _i++) {
                    this._jointMappedBuffers[this._jointMappedBufferIndices[_i]].destroy();
                  }

                  this._jointMappedBuffers = undefined;
                  this._jointMappedBufferIndices = undefined;
                }

                if (this._indirectBuffer) {
                  this._indirectBuffer.destroy();

                  this._indirectBuffer = null;
                }

                if (this._handle) {
                  var fbArrayHandle = SubMeshPool.get(this._handle, SubMeshView.FLAT_BUFFER_ARRAY);
                  freeHandleArray(fbArrayHandle, FlatBufferArrayPool, FlatBufferPool);
                  SubMeshPool.free(this._handle);
                  this._handle = NULL_HANDLE;
                }
              };

              _proto.enableVertexIdChannel = function enableVertexIdChannel(device) {
                if (this._vertexIdChannel) {
                  return;
                }

                var streamIndex = this.vertexBuffers.length;
                var attributeIndex = this.attributes.length;

                var vertexIdBuffer = this._allocVertexIdBuffer(device);

                this._vertexBuffers.push(vertexIdBuffer);

                this._attributes.push(new Attribute('a_vertexId', Format.R32F, false, streamIndex));

                this._iaInfo.attributes = this._attributes;
                this._iaInfo.vertexBuffers = this._vertexBuffers;
                this._vertexIdChannel = {
                  stream: streamIndex,
                  index: attributeIndex
                };
              };

              _proto._allocVertexIdBuffer = function _allocVertexIdBuffer(device) {
                var vertexCount = this.vertexBuffers.length === 0 || this.vertexBuffers[0].stride === 0 ? 0 : this.vertexBuffers[0].size / this.vertexBuffers[0].stride;
                var vertexIds = new Float32Array(vertexCount);

                for (var iVertex = 0; iVertex < vertexCount; ++iVertex) {
                  vertexIds[iVertex] = iVertex + 0.5;
                }

                var vertexIdBuffer = device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, vertexIds.byteLength, vertexIds.BYTES_PER_ELEMENT));
                vertexIdBuffer.update(vertexIds);
                return vertexIdBuffer;
              };

              _createClass(RenderingSubMesh, [{
                key: "attributes",
                get: function get() {
                  return this._attributes;
                }
              }, {
                key: "vertexBuffers",
                get: function get() {
                  return this._vertexBuffers;
                }
              }, {
                key: "indexBuffer",
                get: function get() {
                  return this._indexBuffer;
                }
              }, {
                key: "indirectBuffer",
                get: function get() {
                  return this._indirectBuffer;
                }
              }, {
                key: "primitiveMode",
                get: function get() {
                  return this._primitiveMode;
                }
              }, {
                key: "geometricInfo",
                get: function get() {
                  if (this._geometricInfo) {
                    return this._geometricInfo;
                  }

                  if (this.mesh === undefined) {
                    return {
                      positions: new Float32Array(),
                      indices: new Uint8Array(),
                      boundingBox: {
                        min: Vec3.ZERO,
                        max: Vec3.ZERO
                      }
                    };
                  }

                  if (this.subMeshIdx === undefined) {
                    return {
                      positions: new Float32Array(),
                      indices: new Uint8Array(),
                      boundingBox: {
                        min: Vec3.ZERO,
                        max: Vec3.ZERO
                      }
                    };
                  }

                  var mesh = this.mesh;
                  var index = this.subMeshIdx;
                  var positions = mesh.readAttribute(index, AttributeName.ATTR_POSITION);
                  var indices = mesh.readIndices(index);
                  var max = new Vec3();
                  var min = new Vec3();
                  var pAttri = this.attributes.find(function (element) {
                    return element.name === AttributeName.ATTR_POSITION;
                  });

                  if (pAttri) {
                    var conut = FormatInfos[pAttri.format].count;

                    if (conut === 2) {
                      max.set(positions[0], positions[1], 0);
                      min.set(positions[0], positions[1], 0);
                    } else {
                      max.set(positions[0], positions[1], positions[2]);
                      min.set(positions[0], positions[1], positions[2]);
                    }

                    for (var i = 0; i < positions.length; i += conut) {
                      if (conut === 2) {
                        max.x = positions[i] > max.x ? positions[i] : max.x;
                        max.y = positions[i + 1] > max.y ? positions[i + 1] : max.y;
                        min.x = positions[i] < min.x ? positions[i] : min.x;
                        min.y = positions[i + 1] < min.y ? positions[i + 1] : min.y;
                      } else {
                        max.x = positions[i] > max.x ? positions[i] : max.x;
                        max.y = positions[i + 1] > max.y ? positions[i + 1] : max.y;
                        max.z = positions[i + 2] > max.z ? positions[i + 2] : max.z;
                        min.x = positions[i] < min.x ? positions[i] : min.x;
                        min.y = positions[i + 1] < min.y ? positions[i + 1] : min.y;
                        min.z = positions[i + 2] < min.z ? positions[i + 2] : min.z;
                      }
                    }
                  }

                  this._geometricInfo = {
                    positions: positions,
                    indices: indices,
                    boundingBox: {
                      max: max,
                      min: min
                    }
                  };
                  return this._geometricInfo;
                }
              }, {
                key: "flatBuffers",
                get: function get() {
                  return this._flatBuffers;
                }
              }, {
                key: "jointMappedBuffers",
                get: function get() {
                  var _this = this;

                  if (this._jointMappedBuffers) {
                    return this._jointMappedBuffers;
                  }

                  var buffers = this._jointMappedBuffers = [];
                  var indices = this._jointMappedBufferIndices = [];

                  if (!this.mesh || this.subMeshIdx === undefined) {
                    return this._jointMappedBuffers = this.vertexBuffers;
                  }

                  var struct = this.mesh.struct;
                  var prim = struct.primitives[this.subMeshIdx];

                  if (!struct.jointMaps || prim.jointMapIndex === undefined || !struct.jointMaps[prim.jointMapIndex]) {
                    return this._jointMappedBuffers = this.vertexBuffers;
                  }

                  var jointFormat;
                  var jointOffset;
                  var device = legacyCC.director.root.device;

                  for (var i = 0; i < prim.vertexBundelIndices.length; i++) {
                    var bundle = struct.vertexBundles[prim.vertexBundelIndices[i]];
                    jointOffset = 0;
                    jointFormat = Format.UNKNOWN;

                    for (var j = 0; j < bundle.attributes.length; j++) {
                      var attr = bundle.attributes[j];

                      if (attr.name === AttributeName.ATTR_JOINTS) {
                        jointFormat = attr.format;
                        break;
                      }

                      jointOffset += FormatInfos[attr.format].size;
                    }

                    if (jointFormat) {
                      (function () {
                        var data = new Uint8Array(_this.mesh.data.buffer, bundle.view.offset, bundle.view.length);
                        var dataView = new DataView(data.slice().buffer);
                        var idxMap = struct.jointMaps[prim.jointMapIndex];
                        mapBuffer(dataView, function (cur) {
                          return idxMap.indexOf(cur);
                        }, jointFormat, jointOffset, bundle.view.length, bundle.view.stride, dataView);
                        var buffer = device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, bundle.view.length, bundle.view.stride));
                        buffer.update(dataView.buffer);
                        buffers.push(buffer);
                        indices.push(i);
                      })();
                    } else {
                      buffers.push(this.vertexBuffers[prim.vertexBundelIndices[i]]);
                    }
                  }

                  if (this._vertexIdChannel) {
                    buffers.push(this._allocVertexIdBuffer(device));
                  }

                  return buffers;
                }
              }, {
                key: "iaInfo",
                get: function get() {
                  return this._iaInfo;
                }
              }, {
                key: "handle",
                get: function get() {
                  return this._handle;
                }
              }]);

              return RenderingSubMesh;
            }());

            var _cachedArray = new Array(16);

            var _currentHovered = null;
            var pos = new Vec2();
            var _touchEvents = [SystemEventType.TOUCH_START.toString(), SystemEventType.TOUCH_MOVE.toString(), SystemEventType.TOUCH_END.toString(), SystemEventType.TOUCH_CANCEL.toString()];
            var _mouseEvents = [SystemEventType.MOUSE_DOWN.toString(), SystemEventType.MOUSE_ENTER.toString(), SystemEventType.MOUSE_MOVE.toString(), SystemEventType.MOUSE_LEAVE.toString(), SystemEventType.MOUSE_UP.toString(), SystemEventType.MOUSE_WHEEL.toString()];

            function _touchStartHandler(touch, event) {
              var node = this.owner;

              if (!node || !node._uiProps.uiTransformComp) {
                return false;
              }

              touch.getUILocation(pos);

              if (node._uiProps.uiTransformComp.isHit(pos, this)) {
                event.type = SystemEventType.TOUCH_START.toString();
                event.touch = touch;
                event.bubbles = true;
                node.dispatchEvent(event);
                return true;
              }

              return false;
            }

            function _touchMoveHandler(touch, event) {
              var node = this.owner;

              if (!node || !node._uiProps.uiTransformComp) {
                return false;
              }

              event.type = SystemEventType.TOUCH_MOVE.toString();
              event.touch = touch;
              event.bubbles = true;
              node.dispatchEvent(event);
              return true;
            }

            function _touchEndHandler(touch, event) {
              var node = this.owner;

              if (!node || !node._uiProps.uiTransformComp) {
                return;
              }

              touch.getUILocation(pos);

              if (node._uiProps.uiTransformComp.isHit(pos, this)) {
                event.type = SystemEventType.TOUCH_END.toString();
              } else {
                event.type = SystemEventType.TOUCH_CANCEL.toString();
              }

              event.touch = touch;
              event.bubbles = true;
              node.dispatchEvent(event);
            }

            function _touchCancelHandler(touch, event) {
              var node = this.owner;

              if (!node || !node._uiProps.uiTransformComp) {
                return;
              }

              event.type = SystemEventType.TOUCH_CANCEL.toString();
              event.touch = touch;
              event.bubbles = true;
              node.dispatchEvent(event);
            }

            function _mouseDownHandler(event) {
              var node = this.owner;

              if (!node || !node._uiProps.uiTransformComp) {
                return;
              }

              pos = event.getUILocation();

              if (node._uiProps.uiTransformComp.isHit(pos, this)) {
                event.type = SystemEventType.MOUSE_DOWN.toString();
                event.bubbles = true;
                node.dispatchEvent(event);
              }
            }

            function _mouseMoveHandler(event) {
              var node = this.owner;

              if (!node || !node._uiProps.uiTransformComp) {
                return;
              }

              pos = event.getUILocation();

              var hit = node._uiProps.uiTransformComp.isHit(pos, this);

              if (hit) {
                if (!this._previousIn) {
                  if (_currentHovered && _currentHovered.eventProcessor.mouseListener) {
                    event.type = SystemEventType.MOUSE_LEAVE;

                    _currentHovered.dispatchEvent(event);

                    if (_currentHovered.eventProcessor.mouseListener) {
                      _currentHovered.eventProcessor.mouseListener._previousIn = false;
                    }
                  }

                  _currentHovered = node;
                  event.type = SystemEventType.MOUSE_ENTER.toString();
                  node.dispatchEvent(event);
                  this._previousIn = true;
                }

                event.type = SystemEventType.MOUSE_MOVE.toString();
                event.bubbles = true;
                node.dispatchEvent(event);
              } else if (this._previousIn) {
                event.type = SystemEventType.MOUSE_LEAVE.toString();
                node.dispatchEvent(event);
                this._previousIn = false;
                _currentHovered = null;
              } else {
                return;
              }

              event.propagationStopped = true;
            }

            function _mouseUpHandler(event) {
              var node = this.owner;

              if (!node || !node._uiProps.uiTransformComp) {
                return;
              }

              pos = event.getUILocation();

              if (node._uiProps.uiTransformComp.isHit(pos, this)) {
                event.type = SystemEventType.MOUSE_UP.toString();
                event.bubbles = true;
                node.dispatchEvent(event);
                event.propagationStopped = true;
              }
            }

            function _mouseWheelHandler(event) {
              var node = this.owner;

              if (!node || !node._uiProps.uiTransformComp) {
                return;
              }

              pos = event.getUILocation();

              if (node._uiProps.uiTransformComp.isHit(pos, this)) {
                event.type = SystemEventType.MOUSE_WHEEL.toString();
                event.bubbles = true;
                node.dispatchEvent(event);
                event.propagationStopped = true;
              }
            }

            function _doDispatchEvent(owner, event) {
              var target;
              var i = 0;
              event.target = owner;
              _cachedArray.length = 0;
              owner.eventProcessor.getCapturingTargets(event.type, _cachedArray);
              event.eventPhase = 1;

              for (i = _cachedArray.length - 1; i >= 0; --i) {
                target = _cachedArray[i];

                if (target.eventProcessor.capturingTargets) {
                  event.currentTarget = target;
                  target.eventProcessor.capturingTargets.emit(event.type, event, _cachedArray);

                  if (event.propagationStopped) {
                    _cachedArray.length = 0;
                    return;
                  }
                }
              }

              _cachedArray.length = 0;
              event.eventPhase = 2;
              event.currentTarget = owner;

              if (owner.eventProcessor.capturingTargets) {
                owner.eventProcessor.capturingTargets.emit(event.type, event);
              }

              if (!event.propagationImmediateStopped && owner.eventProcessor.bubblingTargets) {
                owner.eventProcessor.bubblingTargets.emit(event.type, event);
              }

              if (!event.propagationStopped && event.bubbles) {
                owner.eventProcessor.getBubblingTargets(event.type, _cachedArray);
                event.eventPhase = 3;

                for (i = 0; i < _cachedArray.length; ++i) {
                  target = _cachedArray[i];

                  if (target.eventProcessor.bubblingTargets) {
                    event.currentTarget = target;
                    target.eventProcessor.bubblingTargets.emit(event.type, event);

                    if (event.propagationStopped) {
                      _cachedArray.length = 0;
                      return;
                    }
                  }
                }
              }

              _cachedArray.length = 0;
            }

            function _searchComponentsInParent(node, ctor) {
              if (ctor) {
                var index = 0;
                var list = [];

                for (var curr = node; curr && Node$1.isNode(curr); curr = curr.parent, ++index) {
                  var comp = curr.getComponent(ctor);

                  if (comp) {
                    var next = {
                      index: index,
                      comp: comp
                    };

                    if (list) {
                      list.push(next);
                    } else {
                      list = [next];
                    }
                  }
                }

                return list.length > 0 ? list : null;
              }

              return null;
            }

            function _checkListeners(node, events) {
              if (!node._persistNode) {
                if (node.eventProcessor.bubblingTargets) {
                  for (var i = 0; i < events.length; ++i) {
                    if (node.eventProcessor.bubblingTargets.hasEventListener(events[i])) {
                      return true;
                    }
                  }
                }

                if (node.eventProcessor.capturingTargets) {
                  for (var _i = 0; _i < events.length; ++_i) {
                    if (node.eventProcessor.capturingTargets.hasEventListener(events[_i])) {
                      return true;
                    }
                  }
                }

                return false;
              }

              return true;
            }

            var NodeEventProcessor = function () {
              function NodeEventProcessor(node) {
                this.bubblingTargets = null;
                this.capturingTargets = null;
                this.touchListener = null;
                this.mouseListener = null;
                this._node = void 0;
                this._node = node;
              }

              var _proto = NodeEventProcessor.prototype;

              _proto.reattach = function reattach() {
                var currMask;
                this.node.walk(function (node) {
                  if (!currMask) {
                    currMask = _searchComponentsInParent(node, NodeEventProcessor._comp);
                  }

                  if (node.eventProcessor.touchListener) {
                    node.eventProcessor.touchListener.mask = currMask;
                  }

                  if (node.eventProcessor.mouseListener) {
                    node.eventProcessor.mouseListener.mask = currMask;
                  }
                });
              };

              _proto.destroy = function destroy() {
                if (_currentHovered === this._node) {
                  _currentHovered = null;
                }

                if (this.touchListener || this.mouseListener) {
                  eventManager.removeListeners(this._node);

                  if (this.touchListener) {
                    this.touchListener.owner = null;
                    this.touchListener.mask = null;
                    this.touchListener = null;
                  }

                  if (this.mouseListener) {
                    this.mouseListener.owner = null;
                    this.mouseListener.mask = null;
                    this.mouseListener = null;
                  }
                }

                if (this.capturingTargets) this.capturingTargets.clear();
                if (this.bubblingTargets) this.bubblingTargets.clear();
              };

              _proto.on = function on(type, callback, target, useCapture) {
                var forDispatch = this._checknSetupSysEvent(type);

                if (forDispatch) {
                  return this._onDispatch(type, callback, target, useCapture);
                } else {
                  if (!this.bubblingTargets) {
                    this.bubblingTargets = new CallbacksInvoker();
                  }

                  return this.bubblingTargets.on(type, callback, target);
                }
              };

              _proto.once = function once(type, callback, target, useCapture) {
                var _this = this;

                var forDispatch = this._checknSetupSysEvent(type);

                var listeners;

                if (forDispatch && useCapture) {
                  listeners = this.capturingTargets = this.capturingTargets || new CallbacksInvoker();
                } else {
                  listeners = this.bubblingTargets = this.bubblingTargets || new CallbacksInvoker();
                }

                listeners.on(type, callback, target, true);
                listeners.on(type, function () {
                  _this.off(type, callback, target);
                }, undefined, true);
              };

              _proto.off = function off(type, callback, target, useCapture) {
                var touchEvent = _touchEvents.indexOf(type) !== -1;
                var mouseEvent = !touchEvent && _mouseEvents.indexOf(type) !== -1;

                if (touchEvent || mouseEvent) {
                  this._offDispatch(type, callback, target, useCapture);

                  if (touchEvent) {
                    if (this.touchListener && !_checkListeners(this._node, _touchEvents)) {
                      eventManager.removeListener(this.touchListener);
                      this.touchListener = null;
                    }
                  } else if (mouseEvent) {
                    if (this.mouseListener && !_checkListeners(this._node, _mouseEvents)) {
                      eventManager.removeListener(this.mouseListener);
                      this.mouseListener = null;
                    }
                  }
                } else if (this.bubblingTargets) {
                  this.bubblingTargets.off(type, callback, target);
                }
              };

              _proto.emit = function emit(type, arg0, arg1, arg2, arg3, arg4) {
                if (this.bubblingTargets) {
                  this.bubblingTargets.emit(type, arg0, arg1, arg2, arg3, arg4);
                }
              };

              _proto.dispatchEvent = function dispatchEvent(event) {
                _doDispatchEvent(this._node, event);

                _cachedArray.length = 0;
              };

              _proto.hasEventListener = function hasEventListener(type, callback, target) {
                var has = false;

                if (this.bubblingTargets) {
                  has = this.bubblingTargets.hasEventListener(type, callback, target);
                }

                if (!has && this.capturingTargets) {
                  has = this.capturingTargets.hasEventListener(type, callback, target);
                }

                return has;
              };

              _proto.targetOff = function targetOff(target) {
                if (this.capturingTargets) {
                  this.capturingTargets.removeAll(target);
                }

                if (this.bubblingTargets) {
                  this.bubblingTargets.removeAll(target);
                }

                if (this.touchListener && !_checkListeners(this.node, _touchEvents)) {
                  eventManager.removeListener(this.touchListener);
                  this.touchListener = null;
                }

                if (this.mouseListener && !_checkListeners(this.node, _mouseEvents)) {
                  eventManager.removeListener(this.mouseListener);
                  this.mouseListener = null;
                }
              };

              _proto.getCapturingTargets = function getCapturingTargets(type, targets) {
                var parent = this._node.parent;

                while (parent) {
                  if (parent.eventProcessor.capturingTargets && parent.eventProcessor.capturingTargets.hasEventListener(type)) {
                    targets.push(parent);
                  }

                  parent = parent.parent;
                }
              };

              _proto.getBubblingTargets = function getBubblingTargets(type, targets) {
                var parent = this._node.parent;

                while (parent) {
                  if (parent.eventProcessor.bubblingTargets && parent.eventProcessor.bubblingTargets.hasEventListener(type)) {
                    targets.push(parent);
                  }

                  parent = parent.parent;
                }
              };

              _proto._checknSetupSysEvent = function _checknSetupSysEvent(type) {
                var _this2 = this;

                var newAdded = false;
                var forDispatch = false;

                if (_touchEvents.indexOf(type) !== -1) {
                  if (!this.touchListener) {
                    this.touchListener = legacyCC.EventListener.create({
                      event: legacyCC.EventListener.TOUCH_ONE_BY_ONE,
                      swallowTouches: true,
                      owner: this._node,
                      mask: _searchComponentsInParent(this._node, NodeEventProcessor._comp),
                      onTouchBegan: _touchStartHandler,
                      onTouchMoved: _touchMoveHandler,
                      onTouchEnded: _touchEndHandler,
                      onTouchCancelled: _touchCancelHandler
                    });
                    eventManager.addListener(this.touchListener, this._node);
                    newAdded = true;
                  }

                  forDispatch = true;
                } else if (_mouseEvents.indexOf(type) !== -1) {
                  if (!this.mouseListener) {
                    this.mouseListener = legacyCC.EventListener.create({
                      event: legacyCC.EventListener.MOUSE,
                      _previousIn: false,
                      owner: this._node,
                      mask: _searchComponentsInParent(this._node, NodeEventProcessor._comp),
                      onMouseDown: _mouseDownHandler,
                      onMouseMove: _mouseMoveHandler,
                      onMouseUp: _mouseUpHandler,
                      onMouseScroll: _mouseWheelHandler
                    });
                    eventManager.addListener(this.mouseListener, this._node);
                    newAdded = true;
                  }

                  forDispatch = true;
                }

                if (newAdded && !this._node.activeInHierarchy) {
                  legacyCC.director.getScheduler().schedule(function () {
                    if (!_this2._node.activeInHierarchy) {
                      eventManager.pauseTarget(_this2._node);
                    }
                  }, this._node, 0, 0, 0, false);
                }

                return forDispatch;
              };

              _proto._onDispatch = function _onDispatch(type, callback, target, useCapture) {
                if (typeof target === 'boolean') {
                  useCapture = target;
                  target = undefined;
                } else {
                  useCapture = !!useCapture;
                }

                if (!callback) {
                  errorID(6800);
                  return undefined;
                }

                var listeners = null;

                if (useCapture) {
                  listeners = this.capturingTargets = this.capturingTargets || new CallbacksInvoker();
                } else {
                  listeners = this.bubblingTargets = this.bubblingTargets || new CallbacksInvoker();
                }

                if (!listeners.hasEventListener(type, callback, target)) {
                  listeners.on(type, callback, target);
                }

                return callback;
              };

              _proto._offDispatch = function _offDispatch(type, callback, target, useCapture) {
                if (typeof target === 'boolean') {
                  useCapture = target;
                  target = undefined;
                } else {
                  useCapture = !!useCapture;
                }

                if (!callback) {
                  if (this.capturingTargets) {
                    this.capturingTargets.removeAll(type);
                  }

                  if (this.bubblingTargets) {
                    this.bubblingTargets.removeAll(type);
                  }
                } else {
                  var listeners = useCapture ? this.capturingTargets : this.bubblingTargets;

                  if (listeners) {
                    listeners.off(type, callback, target);
                  }
                }
              };

              _createClass(NodeEventProcessor, [{
                key: "node",
                get: function get() {
                  return this._node;
                }
              }]);

              return NodeEventProcessor;
            }();
            NodeEventProcessor._comp = null;
            legacyCC.NodeEventProcessor = NodeEventProcessor;

            var _dec$y, _class$y;
            replaceProperty(BaseNode.prototype, 'BaseNode', [{
              name: 'childrenCount',
              newName: 'children.length',
              customGetter: function customGetter() {
                return this.children.length;
              }
            }]);
            replaceProperty(Node$1.prototype, 'Node', [{
              name: 'width',
              targetName: 'node.getComponent(UITransform)',
              customGetter: function customGetter() {
                return this._uiProps.uiTransformComp.width;
              },
              customSetter: function customSetter(value) {
                this._uiProps.uiTransformComp.width = value;
              }
            }, {
              name: 'height',
              targetName: 'node.getComponent(UITransform)',
              customGetter: function customGetter() {
                return this._uiProps.uiTransformComp.height;
              },
              customSetter: function customSetter(value) {
                this._uiProps.uiTransformComp.height = value;
              }
            }, {
              name: 'anchorX',
              targetName: 'node.getComponent(UITransform)',
              customGetter: function customGetter() {
                return this._uiProps.uiTransformComp.anchorX;
              },
              customSetter: function customSetter(value) {
                this._uiProps.uiTransformComp.anchorX = value;
              }
            }, {
              name: 'anchorY',
              targetName: 'node.getComponent(UITransform)',
              customGetter: function customGetter() {
                return this._uiProps.uiTransformComp.anchorY;
              },
              customSetter: function customSetter(value) {
                this._uiProps.uiTransformComp.anchorY = value;
              }
            }, {
              name: 'getAnchorPoint',
              targetName: 'node.getComponent(UITransform)',
              customFunction: function customFunction(out) {
                if (!out) {
                  out = new Vec2();
                }

                out.set(this._uiProps.uiTransformComp.anchorPoint);
                return out;
              }
            }, {
              name: 'setAnchorPoint',
              targetName: 'node.getComponent(UITransform)',
              customFunction: function customFunction(point, y) {
                this._uiProps.uiTransformComp.setAnchorPoint(point, y);
              }
            }, {
              name: 'getContentSize',
              targetName: 'node.getComponent(UITransform)',
              customFunction: function customFunction(out) {
                if (!out) {
                  out = new Size();
                }

                out.set(this._uiProps.uiTransformComp.contentSize);
                return out;
              }
            }, {
              name: 'setContentSize',
              targetName: 'node.getComponent(UITransform)',
              customFunction: function customFunction(size, height) {
                if (typeof size === 'number') {
                  this._uiProps.uiTransformComp.setContentSize(size, height);
                } else {
                  this._uiProps.uiTransformComp.setContentSize(size);
                }
              }
            }]);
            removeProperty(Node$1.prototype, 'Node.prototype', [{
              name: 'addLayer'
            }, {
              name: 'removeLayer'
            }]);
            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'
            }]);
            var HideInHierarchy$1 = CCObject.Flags.HideInHierarchy;
            var DontSave$1 = CCObject.Flags.DontSave;
            var PrivateNode = exports('PrivateNode', (_dec$y = ccclass('cc.PrivateNode'), _dec$y(_class$y = function (_Node) {
              _inheritsLoose(PrivateNode, _Node);

              function PrivateNode(name) {
                var _this;

                _this = _Node.call(this, name) || this;
                warnID(12003, _this.name);
                _this.hideFlags |= DontSave$1 | HideInHierarchy$1;
                return _this;
              }

              return PrivateNode;
            }(Node$1)) || _class$y));

            legacyCC.PrivateNode = PrivateNode;

            var _dec$z, _dec2$j, _class$z, _class2$x, _descriptor$p, _descriptor2$h, _descriptor3$b, _temp$x, _dec3$f, _dec4$a, _dec5$7, _class4$2, _class5$2, _descriptor4$9, _descriptor5$6, _descriptor6$3, _descriptor7$3, _temp2$2, _dec6$3, _dec7$2, _dec8$2, _dec9$2, _dec10$2, _dec11$2, _dec12$2, _dec13$2, _dec14$2, _dec15$2, _dec16$2, _dec17$2, _dec18$2, _dec19$2, _dec20$2, _dec21$2, _dec22$2, _dec23$2, _dec24$2, _dec25$2, _dec26$2, _dec27$1, _dec28$1, _dec29$1, _dec30$1, _dec31$1, _dec32, _dec33, _class7$2, _class8$2, _descriptor8$3, _descriptor9$2, _descriptor10$2, _descriptor11$2, _descriptor12$2, _descriptor13$2, _descriptor14$2, _descriptor15$2, _descriptor16$2, _class9, _temp3$2, _dec34, _dec35, _dec36, _dec37, _dec38, _dec39, _dec40, _dec41, _dec42, _dec43, _dec44, _dec45, _dec46, _dec47, _dec48, _dec49, _dec50, _dec51, _dec52, _dec53, _dec54, _dec55, _dec56, _dec57, _dec58, _dec59, _dec60, _dec61, _dec62, _dec63, _class10$2, _class11$2, _descriptor17$2, _descriptor18$2, _descriptor19$2, _descriptor20$2, _descriptor21$2, _descriptor22$2, _descriptor23$2, _descriptor24$2, _descriptor25$2, _descriptor26$1, _descriptor27$1, _descriptor28$1, _descriptor29$1, _descriptor30$1, _descriptor31$1, _descriptor32$1, _descriptor33$1, _descriptor34$1, _temp4$2, _dec64, _dec65, _class13$2, _class14$2, _descriptor35$1, _descriptor36, _descriptor37, _descriptor38, _temp5$2;

            var _up = new Vec3(0, 1, 0);

            var _v3$1 = new Vec3();

            var _qt$1 = new Quat();

            var AmbientInfo = (_dec$z = ccclass('cc.AmbientInfo'), _dec2$j = type(CCFloat), _dec$z(_class$z = (_class2$x = (_temp$x = function () {
              function AmbientInfo() {
                _initializerDefineProperty(this, "_skyColor", _descriptor$p, this);

                _initializerDefineProperty(this, "_skyIllum", _descriptor2$h, this);

                _initializerDefineProperty(this, "_groundAlbedo", _descriptor3$b, this);

                this._resource = null;
              }

              var _proto = AmbientInfo.prototype;

              _proto.activate = function activate(resource) {
                this._resource = resource;

                this._resource.initialize(this);
              };

              _createClass(AmbientInfo, [{
                key: "skyColor",
                get: function get() {
                  return this._skyColor;
                },
                set: function set(val) {
                  this._skyColor.set(val);

                  if (this._resource) {
                    this._resource.skyColor = this._skyColor;
                  }
                }
              }, {
                key: "skyIllum",
                get: function get() {
                  return this._skyIllum;
                },
                set: function set(val) {
                  this._skyIllum = val;

                  if (this._resource) {
                    this._resource.skyIllum = this.skyIllum;
                  }
                }
              }, {
                key: "groundAlbedo",
                get: function get() {
                  return this._groundAlbedo;
                },
                set: function set(val) {
                  this._groundAlbedo.set(val);

                  if (this._resource) {
                    this._resource.groundAlbedo = this._groundAlbedo;
                  }
                }
              }]);

              return AmbientInfo;
            }(), _temp$x), (_descriptor$p = _applyDecoratedDescriptor(_class2$x.prototype, "_skyColor", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new Color(51, 128, 204, 1.0);
              }
            }), _descriptor2$h = _applyDecoratedDescriptor(_class2$x.prototype, "_skyIllum", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return Ambient.SKY_ILLUM;
              }
            }), _descriptor3$b = _applyDecoratedDescriptor(_class2$x.prototype, "_groundAlbedo", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new Color(51, 51, 51, 255);
              }
            }), _applyDecoratedDescriptor(_class2$x.prototype, "skyColor", [editable], Object.getOwnPropertyDescriptor(_class2$x.prototype, "skyColor"), _class2$x.prototype), _applyDecoratedDescriptor(_class2$x.prototype, "skyIllum", [editable, _dec2$j], Object.getOwnPropertyDescriptor(_class2$x.prototype, "skyIllum"), _class2$x.prototype), _applyDecoratedDescriptor(_class2$x.prototype, "groundAlbedo", [editable], Object.getOwnPropertyDescriptor(_class2$x.prototype, "groundAlbedo"), _class2$x.prototype)), _class2$x)) || _class$z);
            legacyCC.AmbientInfo = AmbientInfo;
            var SkyboxInfo = (_dec3$f = ccclass('cc.SkyboxInfo'), _dec4$a = type(TextureCube), _dec5$7 = type(TextureCube), _dec3$f(_class4$2 = (_class5$2 = (_temp2$2 = function () {
              function SkyboxInfo() {
                _initializerDefineProperty(this, "_envmap", _descriptor4$9, this);

                _initializerDefineProperty(this, "_isRGBE", _descriptor5$6, this);

                _initializerDefineProperty(this, "_enabled", _descriptor6$3, this);

                _initializerDefineProperty(this, "_useIBL", _descriptor7$3, this);

                this._resource = null;
              }

              var _proto2 = SkyboxInfo.prototype;

              _proto2.activate = function activate(resource) {
                this._resource = resource;

                this._resource.initialize(this);

                this._resource.activate();
              };

              _createClass(SkyboxInfo, [{
                key: "enabled",
                get: function get() {
                  return this._enabled;
                },
                set: function set(val) {
                  if (this._enabled === val) return;
                  this._enabled = val;

                  if (this._resource) {
                    this._resource.enabled = this._enabled;
                  }
                }
              }, {
                key: "useIBL",
                get: function get() {
                  return this._useIBL;
                },
                set: function set(val) {
                  this._useIBL = val;

                  if (this._resource) {
                    this._resource.useIBL = this._useIBL;
                  }
                }
              }, {
                key: "envmap",
                get: function get() {
                  return this._envmap;
                },
                set: function set(val) {
                  this._envmap = val;

                  if (this._resource) {
                    this._resource.envmap = this._envmap;
                  }
                }
              }, {
                key: "isRGBE",
                get: function get() {
                  return this._isRGBE;
                },
                set: function set(val) {
                  this._isRGBE = val;

                  if (this._resource) {
                    this._resource.isRGBE = this._isRGBE;
                  }
                }
              }]);

              return SkyboxInfo;
            }(), _temp2$2), (_descriptor4$9 = _applyDecoratedDescriptor(_class5$2.prototype, "_envmap", [_dec4$a], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor5$6 = _applyDecoratedDescriptor(_class5$2.prototype, "_isRGBE", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor6$3 = _applyDecoratedDescriptor(_class5$2.prototype, "_enabled", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor7$3 = _applyDecoratedDescriptor(_class5$2.prototype, "_useIBL", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _applyDecoratedDescriptor(_class5$2.prototype, "enabled", [editable], Object.getOwnPropertyDescriptor(_class5$2.prototype, "enabled"), _class5$2.prototype), _applyDecoratedDescriptor(_class5$2.prototype, "useIBL", [editable], Object.getOwnPropertyDescriptor(_class5$2.prototype, "useIBL"), _class5$2.prototype), _applyDecoratedDescriptor(_class5$2.prototype, "envmap", [editable, _dec5$7], Object.getOwnPropertyDescriptor(_class5$2.prototype, "envmap"), _class5$2.prototype), _applyDecoratedDescriptor(_class5$2.prototype, "isRGBE", [editable], Object.getOwnPropertyDescriptor(_class5$2.prototype, "isRGBE"), _class5$2.prototype)), _class5$2)) || _class4$2);
            legacyCC.SkyboxInfo = SkyboxInfo;
            var FogInfo = (_dec6$3 = ccclass('cc.FogInfo'), _dec7$2 = type(FogType), _dec8$2 = visible(), _dec9$2 = type(CCFloat), _dec10$2 = range(), _dec11$2 = rangeStep(), _dec12$2 = displayOrder(), _dec13$2 = visible(), _dec14$2 = type(CCFloat), _dec15$2 = rangeStep(), _dec16$2 = displayOrder(), _dec17$2 = visible(), _dec18$2 = type(CCFloat), _dec19$2 = rangeStep(), _dec20$2 = displayOrder(), _dec21$2 = visible(), _dec22$2 = type(CCFloat), _dec23$2 = rangeMin(), _dec24$2 = rangeStep(), _dec25$2 = displayOrder(), _dec26$2 = visible(), _dec27$1 = type(CCFloat), _dec28$1 = rangeStep(), _dec29$1 = displayOrder(), _dec30$1 = visible(), _dec31$1 = type(CCFloat), _dec32 = rangeStep(), _dec33 = displayOrder(), _dec6$3(_class7$2 = (_class8$2 = (_temp3$2 = _class9 = function () {
              function FogInfo() {
                _initializerDefineProperty(this, "_type", _descriptor8$3, this);

                _initializerDefineProperty(this, "_fogColor", _descriptor9$2, this);

                _initializerDefineProperty(this, "_enabled", _descriptor10$2, this);

                _initializerDefineProperty(this, "_fogDensity", _descriptor11$2, this);

                _initializerDefineProperty(this, "_fogStart", _descriptor12$2, this);

                _initializerDefineProperty(this, "_fogEnd", _descriptor13$2, this);

                _initializerDefineProperty(this, "_fogAtten", _descriptor14$2, this);

                _initializerDefineProperty(this, "_fogTop", _descriptor15$2, this);

                _initializerDefineProperty(this, "_fogRange", _descriptor16$2, this);

                this._resource = null;
              }

              var _proto3 = FogInfo.prototype;

              _proto3.activate = function activate(resource) {
                this._resource = resource;

                this._resource.initialize(this);

                this._resource.activate();
              };

              _createClass(FogInfo, [{
                key: "enabled",
                get: function get() {
                  return this._enabled;
                },
                set: function set(val) {
                  if (this._enabled === val) return;
                  this._enabled = val;

                  if (this._resource) {
                    this._resource.enabled = val;

                    if (val) {
                      this._resource.type = this._type;
                    }
                  }
                }
              }, {
                key: "fogColor",
                get: function get() {
                  return this._fogColor;
                },
                set: function set(val) {
                  this._fogColor.set(val);

                  if (this._resource) {
                    this._resource.fogColor = this._fogColor;
                  }
                }
              }, {
                key: "type",
                get: function get() {
                  return this._type;
                },
                set: function set(val) {
                  this._type = val;

                  if (this._resource) {
                    this._resource.type = val;
                  }
                }
              }, {
                key: "fogDensity",
                get: function get() {
                  return this._fogDensity;
                },
                set: function set(val) {
                  this._fogDensity = val;

                  if (this._resource) {
                    this._resource.fogDensity = val;
                  }
                }
              }, {
                key: "fogStart",
                get: function get() {
                  return this._fogStart;
                },
                set: function set(val) {
                  this._fogStart = val;

                  if (this._resource) {
                    this._resource.fogStart = val;
                  }
                }
              }, {
                key: "fogEnd",
                get: function get() {
                  return this._fogEnd;
                },
                set: function set(val) {
                  this._fogEnd = val;

                  if (this._resource) {
                    this._resource.fogEnd = val;
                  }
                }
              }, {
                key: "fogAtten",
                get: function get() {
                  return this._fogAtten;
                },
                set: function set(val) {
                  this._fogAtten = val;

                  if (this._resource) {
                    this._resource.fogAtten = val;
                  }
                }
              }, {
                key: "fogTop",
                get: function get() {
                  return this._fogTop;
                },
                set: function set(val) {
                  this._fogTop = val;

                  if (this._resource) {
                    this._resource.fogTop = val;
                  }
                }
              }, {
                key: "fogRange",
                get: function get() {
                  return this._fogRange;
                },
                set: function set(val) {
                  this._fogRange = val;

                  if (this._resource) {
                    this._resource.fogRange = val;
                  }
                }
              }]);

              return FogInfo;
            }(), _class9.FogType = FogType, _temp3$2), (_descriptor8$3 = _applyDecoratedDescriptor(_class8$2.prototype, "_type", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return FogType.LINEAR;
              }
            }), _descriptor9$2 = _applyDecoratedDescriptor(_class8$2.prototype, "_fogColor", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new Color('#C8C8C8');
              }
            }), _descriptor10$2 = _applyDecoratedDescriptor(_class8$2.prototype, "_enabled", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor11$2 = _applyDecoratedDescriptor(_class8$2.prototype, "_fogDensity", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0.3;
              }
            }), _descriptor12$2 = _applyDecoratedDescriptor(_class8$2.prototype, "_fogStart", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0.5;
              }
            }), _descriptor13$2 = _applyDecoratedDescriptor(_class8$2.prototype, "_fogEnd", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 300;
              }
            }), _descriptor14$2 = _applyDecoratedDescriptor(_class8$2.prototype, "_fogAtten", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 5;
              }
            }), _descriptor15$2 = _applyDecoratedDescriptor(_class8$2.prototype, "_fogTop", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1.5;
              }
            }), _descriptor16$2 = _applyDecoratedDescriptor(_class8$2.prototype, "_fogRange", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1.2;
              }
            }), _applyDecoratedDescriptor(_class8$2.prototype, "enabled", [editable], Object.getOwnPropertyDescriptor(_class8$2.prototype, "enabled"), _class8$2.prototype), _applyDecoratedDescriptor(_class8$2.prototype, "fogColor", [editable], Object.getOwnPropertyDescriptor(_class8$2.prototype, "fogColor"), _class8$2.prototype), _applyDecoratedDescriptor(_class8$2.prototype, "type", [editable, _dec7$2], Object.getOwnPropertyDescriptor(_class8$2.prototype, "type"), _class8$2.prototype), _applyDecoratedDescriptor(_class8$2.prototype, "fogDensity", [_dec8$2, _dec9$2, _dec10$2, _dec11$2, slide, _dec12$2], Object.getOwnPropertyDescriptor(_class8$2.prototype, "fogDensity"), _class8$2.prototype), _applyDecoratedDescriptor(_class8$2.prototype, "fogStart", [_dec13$2, _dec14$2, _dec15$2, _dec16$2], Object.getOwnPropertyDescriptor(_class8$2.prototype, "fogStart"), _class8$2.prototype), _applyDecoratedDescriptor(_class8$2.prototype, "fogEnd", [_dec17$2, _dec18$2, _dec19$2, _dec20$2], Object.getOwnPropertyDescriptor(_class8$2.prototype, "fogEnd"), _class8$2.prototype), _applyDecoratedDescriptor(_class8$2.prototype, "fogAtten", [_dec21$2, _dec22$2, _dec23$2, _dec24$2, _dec25$2], Object.getOwnPropertyDescriptor(_class8$2.prototype, "fogAtten"), _class8$2.prototype), _applyDecoratedDescriptor(_class8$2.prototype, "fogTop", [_dec26$2, _dec27$1, _dec28$1, _dec29$1], Object.getOwnPropertyDescriptor(_class8$2.prototype, "fogTop"), _class8$2.prototype), _applyDecoratedDescriptor(_class8$2.prototype, "fogRange", [_dec30$1, _dec31$1, _dec32, _dec33], Object.getOwnPropertyDescriptor(_class8$2.prototype, "fogRange"), _class8$2.prototype)), _class8$2)) || _class7$2);
            var ShadowsInfo = (_dec34 = ccclass('cc.ShadowsInfo'), _dec35 = type(ShadowType), _dec36 = visible(), _dec37 = type(CCFloat), _dec38 = visible(), _dec39 = type(PCFType), _dec40 = visible(), _dec41 = type(CCInteger), _dec42 = visible(), _dec43 = type(CCFloat), _dec44 = visible(), _dec45 = type(CCBoolean), _dec46 = visible(), _dec47 = type(CCBoolean), _dec48 = visible(), _dec49 = type(CCBoolean), _dec50 = visible(), _dec51 = type(CCFloat), _dec52 = visible(), _dec53 = type(CCBoolean), _dec54 = visible(), _dec55 = type(CCFloat), _dec56 = visible(), _dec57 = type(CCFloat), _dec58 = visible(), _dec59 = type(CCFloat), _dec60 = visible(), _dec61 = visible(), _dec62 = type(CCFloat), _dec63 = visible(), _dec34(_class10$2 = (_class11$2 = (_temp4$2 = function () {
              function ShadowsInfo() {
                _initializerDefineProperty(this, "_type", _descriptor17$2, this);

                _initializerDefineProperty(this, "_enabled", _descriptor18$2, this);

                _initializerDefineProperty(this, "_normal", _descriptor19$2, this);

                _initializerDefineProperty(this, "_distance", _descriptor20$2, this);

                _initializerDefineProperty(this, "_shadowColor", _descriptor21$2, this);

                _initializerDefineProperty(this, "_autoAdapt", _descriptor22$2, this);

                _initializerDefineProperty(this, "_pcf", _descriptor23$2, this);

                _initializerDefineProperty(this, "_bias", _descriptor24$2, this);

                _initializerDefineProperty(this, "_packing", _descriptor25$2, this);

                _initializerDefineProperty(this, "_linear", _descriptor26$1, this);

                _initializerDefineProperty(this, "_selfShadow", _descriptor27$1, this);

                _initializerDefineProperty(this, "_normalBias", _descriptor28$1, this);

                _initializerDefineProperty(this, "_near", _descriptor29$1, this);

                _initializerDefineProperty(this, "_far", _descriptor30$1, this);

                _initializerDefineProperty(this, "_aspect", _descriptor31$1, this);

                _initializerDefineProperty(this, "_orthoSize", _descriptor32$1, this);

                _initializerDefineProperty(this, "_maxReceived", _descriptor33$1, this);

                _initializerDefineProperty(this, "_size", _descriptor34$1, this);

                this._resource = null;
              }

              var _proto4 = ShadowsInfo.prototype;

              _proto4.setPlaneFromNode = function setPlaneFromNode(node) {
                node.getWorldRotation(_qt$1);
                this.normal = Vec3.transformQuat(_v3$1, _up, _qt$1);
                node.getWorldPosition(_v3$1);
                this.distance = Vec3.dot(this._normal, _v3$1);
              };

              _proto4.activate = function activate(resource) {
                this._resource = resource;

                this._resource.initialize(this);

                this._resource.activate();
              };

              _createClass(ShadowsInfo, [{
                key: "enabled",
                get: function get() {
                  return this._enabled;
                },
                set: function set(val) {
                  if (this._enabled === val) return;
                  this._enabled = val;

                  if (this._resource) {
                    this._resource.enabled = val;

                    if (val) {
                      this._resource.type = this._type;
                    }
                  }
                }
              }, {
                key: "type",
                get: function get() {
                  return this._type;
                },
                set: function set(val) {
                  this._type = val;

                  if (this._resource) {
                    this._resource.type = val;
                  }
                }
              }, {
                key: "shadowColor",
                get: function get() {
                  return this._shadowColor;
                },
                set: function set(val) {
                  this._shadowColor.set(val);

                  if (this._resource) {
                    this._resource.shadowColor = val;
                  }
                }
              }, {
                key: "normal",
                get: function get() {
                  return this._normal;
                },
                set: function set(val) {
                  Vec3.copy(this._normal, val);

                  if (this._resource) {
                    this._resource.normal = val;
                  }
                }
              }, {
                key: "distance",
                get: function get() {
                  return this._distance;
                },
                set: function set(val) {
                  this._distance = val;

                  if (this._resource) {
                    this._resource.distance = val;
                  }
                }
              }, {
                key: "pcf",
                get: function get() {
                  return this._pcf;
                },
                set: function set(val) {
                  this._pcf = val;

                  if (this._resource) {
                    this._resource.pcf = val;
                  }
                }
              }, {
                key: "maxReceived",
                get: function get() {
                  return this._maxReceived;
                },
                set: function set(val) {
                  this._maxReceived = val;

                  if (this._resource) {
                    this._resource.maxReceived = val;
                  }
                }
              }, {
                key: "bias",
                get: function get() {
                  return this._bias;
                },
                set: function set(val) {
                  this._bias = val;

                  if (this._resource) {
                    this._resource.bias = val;
                  }
                }
              }, {
                key: "packing",
                get: function get() {
                  return this._packing;
                },
                set: function set(val) {
                  this._packing = val;

                  if (val) {
                    this._linear = this._linear ? false : this._linear;

                    if (this._resource) {
                      this._resource.linear = this._linear;
                    }
                  }

                  if (this._resource) {
                    this._resource.packing = val;
                    this._resource.shadowMapDirty = true;
                  }
                }
              }, {
                key: "linear",
                get: function get() {
                  return this._linear;
                },
                set: function set(val) {
                  this._linear = val;

                  if (val) {
                    this._packing = this._packing ? false : this._packing;

                    if (this._resource) {
                      this._resource.packing = this._packing;
                    }
                  }

                  if (this._resource) {
                    this._resource.linear = val;
                  }
                }
              }, {
                key: "selfShadow",
                get: function get() {
                  return this._selfShadow;
                },
                set: function set(val) {
                  this._selfShadow = val;

                  if (this._resource) {
                    this._resource.selfShadow = val;
                  }
                }
              }, {
                key: "normalBias",
                get: function get() {
                  return this._normalBias;
                },
                set: function set(val) {
                  this._normalBias = val;

                  if (this._resource) {
                    this._resource.normalBias = val;
                  }
                }
              }, {
                key: "autoAdapt",
                get: function get() {
                  return this._autoAdapt;
                },
                set: function set(val) {
                  this._autoAdapt = val;

                  if (this._resource) {
                    this._resource.autoAdapt = val;
                  }
                }
              }, {
                key: "near",
                get: function get() {
                  return this._near;
                },
                set: function set(val) {
                  this._near = val;

                  if (this._resource) {
                    this._resource.near = val;
                  }
                }
              }, {
                key: "far",
                get: function get() {
                  return this._far;
                },
                set: function set(val) {
                  this._far = val;

                  if (this._resource) {
                    this._resource.far = val;
                  }
                }
              }, {
                key: "orthoSize",
                get: function get() {
                  return this._orthoSize;
                },
                set: function set(val) {
                  this._orthoSize = val;

                  if (this._resource) {
                    this._resource.orthoSize = val;
                  }
                }
              }, {
                key: "shadowMapSize",
                get: function get() {
                  return this._size;
                },
                set: function set(val) {
                  this._size.set(val);

                  if (this._resource) {
                    this._resource.size = val;
                    this._resource.shadowMapDirty = true;
                  }
                }
              }, {
                key: "aspect",
                get: function get() {
                  return this._aspect;
                },
                set: function set(val) {
                  this._aspect = val;

                  if (this._resource) {
                    this._resource.aspect = val;
                  }
                }
              }]);

              return ShadowsInfo;
            }(), _temp4$2), (_descriptor17$2 = _applyDecoratedDescriptor(_class11$2.prototype, "_type", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return ShadowType.Planar;
              }
            }), _descriptor18$2 = _applyDecoratedDescriptor(_class11$2.prototype, "_enabled", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor19$2 = _applyDecoratedDescriptor(_class11$2.prototype, "_normal", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new Vec3(0, 1, 0);
              }
            }), _descriptor20$2 = _applyDecoratedDescriptor(_class11$2.prototype, "_distance", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor21$2 = _applyDecoratedDescriptor(_class11$2.prototype, "_shadowColor", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new Color(0, 0, 0, 76);
              }
            }), _descriptor22$2 = _applyDecoratedDescriptor(_class11$2.prototype, "_autoAdapt", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _descriptor23$2 = _applyDecoratedDescriptor(_class11$2.prototype, "_pcf", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return PCFType.HARD;
              }
            }), _descriptor24$2 = _applyDecoratedDescriptor(_class11$2.prototype, "_bias", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0.00001;
              }
            }), _descriptor25$2 = _applyDecoratedDescriptor(_class11$2.prototype, "_packing", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor26$1 = _applyDecoratedDescriptor(_class11$2.prototype, "_linear", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _descriptor27$1 = _applyDecoratedDescriptor(_class11$2.prototype, "_selfShadow", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor28$1 = _applyDecoratedDescriptor(_class11$2.prototype, "_normalBias", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0.0;
              }
            }), _descriptor29$1 = _applyDecoratedDescriptor(_class11$2.prototype, "_near", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1;
              }
            }), _descriptor30$1 = _applyDecoratedDescriptor(_class11$2.prototype, "_far", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 30;
              }
            }), _descriptor31$1 = _applyDecoratedDescriptor(_class11$2.prototype, "_aspect", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1;
              }
            }), _descriptor32$1 = _applyDecoratedDescriptor(_class11$2.prototype, "_orthoSize", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 5;
              }
            }), _descriptor33$1 = _applyDecoratedDescriptor(_class11$2.prototype, "_maxReceived", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 4;
              }
            }), _descriptor34$1 = _applyDecoratedDescriptor(_class11$2.prototype, "_size", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new Vec2(512, 512);
              }
            }), _applyDecoratedDescriptor(_class11$2.prototype, "enabled", [editable], Object.getOwnPropertyDescriptor(_class11$2.prototype, "enabled"), _class11$2.prototype), _applyDecoratedDescriptor(_class11$2.prototype, "type", [editable, _dec35], Object.getOwnPropertyDescriptor(_class11$2.prototype, "type"), _class11$2.prototype), _applyDecoratedDescriptor(_class11$2.prototype, "shadowColor", [editable], Object.getOwnPropertyDescriptor(_class11$2.prototype, "shadowColor"), _class11$2.prototype), _applyDecoratedDescriptor(_class11$2.prototype, "normal", [_dec36], Object.getOwnPropertyDescriptor(_class11$2.prototype, "normal"), _class11$2.prototype), _applyDecoratedDescriptor(_class11$2.prototype, "distance", [_dec37, _dec38], Object.getOwnPropertyDescriptor(_class11$2.prototype, "distance"), _class11$2.prototype), _applyDecoratedDescriptor(_class11$2.prototype, "pcf", [_dec39, _dec40], Object.getOwnPropertyDescriptor(_class11$2.prototype, "pcf"), _class11$2.prototype), _applyDecoratedDescriptor(_class11$2.prototype, "maxReceived", [_dec41, _dec42], Object.getOwnPropertyDescriptor(_class11$2.prototype, "maxReceived"), _class11$2.prototype), _applyDecoratedDescriptor(_class11$2.prototype, "bias", [_dec43, _dec44], Object.getOwnPropertyDescriptor(_class11$2.prototype, "bias"), _class11$2.prototype), _applyDecoratedDescriptor(_class11$2.prototype, "packing", [_dec45, _dec46], Object.getOwnPropertyDescriptor(_class11$2.prototype, "packing"), _class11$2.prototype), _applyDecoratedDescriptor(_class11$2.prototype, "linear", [_dec47, _dec48], Object.getOwnPropertyDescriptor(_class11$2.prototype, "linear"), _class11$2.prototype), _applyDecoratedDescriptor(_class11$2.prototype, "selfShadow", [_dec49, _dec50], Object.getOwnPropertyDescriptor(_class11$2.prototype, "selfShadow"), _class11$2.prototype), _applyDecoratedDescriptor(_class11$2.prototype, "normalBias", [_dec51, _dec52], Object.getOwnPropertyDescriptor(_class11$2.prototype, "normalBias"), _class11$2.prototype), _applyDecoratedDescriptor(_class11$2.prototype, "autoAdapt", [_dec53, _dec54], Object.getOwnPropertyDescriptor(_class11$2.prototype, "autoAdapt"), _class11$2.prototype), _applyDecoratedDescriptor(_class11$2.prototype, "near", [_dec55, _dec56], Object.getOwnPropertyDescriptor(_class11$2.prototype, "near"), _class11$2.prototype), _applyDecoratedDescriptor(_class11$2.prototype, "far", [_dec57, _dec58], Object.getOwnPropertyDescriptor(_class11$2.prototype, "far"), _class11$2.prototype), _applyDecoratedDescriptor(_class11$2.prototype, "orthoSize", [_dec59, _dec60], Object.getOwnPropertyDescriptor(_class11$2.prototype, "orthoSize"), _class11$2.prototype), _applyDecoratedDescriptor(_class11$2.prototype, "shadowMapSize", [_dec61], Object.getOwnPropertyDescriptor(_class11$2.prototype, "shadowMapSize"), _class11$2.prototype), _applyDecoratedDescriptor(_class11$2.prototype, "aspect", [_dec62, _dec63], Object.getOwnPropertyDescriptor(_class11$2.prototype, "aspect"), _class11$2.prototype)), _class11$2)) || _class10$2);
            legacyCC.ShadowsInfo = ShadowsInfo;
            var SceneGlobals = (_dec64 = ccclass('cc.SceneGlobals'), _dec65 = type(SkyboxInfo), _dec64(_class13$2 = (_class14$2 = (_temp5$2 = function () {
              function SceneGlobals() {
                _initializerDefineProperty(this, "ambient", _descriptor35$1, this);

                _initializerDefineProperty(this, "shadows", _descriptor36, this);

                _initializerDefineProperty(this, "_skybox", _descriptor37, this);

                _initializerDefineProperty(this, "fog", _descriptor38, this);
              }

              var _proto5 = SceneGlobals.prototype;

              _proto5.activate = function activate() {
                var sceneData = legacyCC.director.root.pipeline.pipelineSceneData;
                this.ambient.activate(sceneData.ambient);
                this.skybox.activate(sceneData.skybox);
                this.shadows.activate(sceneData.shadows);
                this.fog.activate(sceneData.fog);
              };

              _createClass(SceneGlobals, [{
                key: "skybox",
                get: function get() {
                  return this._skybox;
                },
                set: function set(value) {
                  this._skybox = value;
                }
              }]);

              return SceneGlobals;
            }(), _temp5$2), (_descriptor35$1 = _applyDecoratedDescriptor(_class14$2.prototype, "ambient", [serializable, editable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new AmbientInfo();
              }
            }), _descriptor36 = _applyDecoratedDescriptor(_class14$2.prototype, "shadows", [serializable, editable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new ShadowsInfo();
              }
            }), _descriptor37 = _applyDecoratedDescriptor(_class14$2.prototype, "_skybox", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new SkyboxInfo();
              }
            }), _descriptor38 = _applyDecoratedDescriptor(_class14$2.prototype, "fog", [editable, serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new FogInfo();
              }
            }), _applyDecoratedDescriptor(_class14$2.prototype, "skybox", [editable, _dec65], Object.getOwnPropertyDescriptor(_class14$2.prototype, "skybox"), _class14$2.prototype)), _class14$2)) || _class13$2);
            legacyCC.SceneGlobals = SceneGlobals;

            var _dec$A, _class$A, _class2$y, _descriptor$q, _descriptor2$i, _temp$y;
            var Scene = exports('Scene', (_dec$A = ccclass('cc.Scene'), _dec$A(_class$A = (_class2$y = (_temp$y = function (_BaseNode) {
              _inheritsLoose(Scene, _BaseNode);

              var _proto = Scene.prototype;

              _proto._updateScene = function _updateScene() {
                this._scene = this;
              };

              function Scene(name) {
                var _this;

                _this = _BaseNode.call(this, name) || this;

                _initializerDefineProperty(_this, "autoReleaseAssets", _descriptor$q, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_globals", _descriptor2$i, _assertThisInitialized(_this));

                _this._renderScene = null;
                _this.dependAssets = null;
                _this._inited = void 0;
                _this._prefabSyncedInLiveReload = false;
                _this._pos = Vec3.ZERO;
                _this._rot = Quat.IDENTITY;
                _this._scale = Vec3.ONE;
                _this._mat = Mat4.IDENTITY;
                _this._dirtyFlags = 0;
                _this._activeInHierarchy = false;

                if (legacyCC.director && legacyCC.director.root) {
                  _this._renderScene = legacyCC.director.root.createScene({});
                }

                _this._inited = legacyCC.game ? !legacyCC.game._isCloning : true;
                return _this;
              }

              _proto.destroy = function destroy() {
                var success = CCObject.prototype.destroy.call(this);

                if (success) {
                  var children = this._children;

                  for (var i = 0; i < children.length; ++i) {
                    children[i].active = false;
                  }
                }

                legacyCC.director.root.destroyScene(this._renderScene);
                this._active = false;
                this._activeInHierarchy = false;
                return success;
              };

              _proto.addComponent = function addComponent() {
                throw new Error(getError(3822));
              };

              _proto._onHierarchyChanged = function _onHierarchyChanged() {};

              _proto._onBatchCreated = function _onBatchCreated(dontSyncChildPrefab) {
                _BaseNode.prototype._onBatchCreated.call(this, dontSyncChildPrefab);

                var len = this._children.length;

                for (var i = 0; i < len; ++i) {
                  this.children[i]._siblingIndex = i;

                  this._children[i]._onBatchCreated(dontSyncChildPrefab);
                }

                applyTargetOverrides(this);
              };

              _proto.getPosition = function getPosition(out) {
                return Vec3.copy(out || new Vec3(), Vec3.ZERO);
              };

              _proto.getRotation = function getRotation(out) {
                return Quat.copy(out || new Quat(), Quat.IDENTITY);
              };

              _proto.getScale = function getScale(out) {
                return Vec3.copy(out || new Vec3(), Vec3.ONE);
              };

              _proto.getWorldPosition = function getWorldPosition(out) {
                return Vec3.copy(out || new Vec3(), Vec3.ZERO);
              };

              _proto.getWorldRotation = function getWorldRotation(out) {
                return Quat.copy(out || new Quat(), Quat.IDENTITY);
              };

              _proto.getWorldScale = function getWorldScale(out) {
                return Vec3.copy(out || new Vec3(), Vec3.ONE);
              };

              _proto.getWorldMatrix = function getWorldMatrix(out) {
                return Mat4.copy(out || new Mat4(), Mat4.IDENTITY);
              };

              _proto.getWorldRS = function getWorldRS(out) {
                return Mat4.copy(out || new Mat4(), Mat4.IDENTITY);
              };

              _proto.getWorldRT = function getWorldRT(out) {
                return Mat4.copy(out || new Mat4(), Mat4.IDENTITY);
              };

              _proto.updateWorldTransform = function updateWorldTransform() {};

              _proto._instantiate = function _instantiate() {};

              _proto._load = function _load() {
                if (!this._inited) {

                  this._onBatchCreated(EDITOR );

                  this._inited = true;
                }

                this.walk(BaseNode._setScene);
              };

              _proto._activate = function _activate(active) {
                active = active !== false;

                legacyCC.director._nodeActivator.activateNode(this, active);

                this._globals.activate();
              };

              _createClass(Scene, [{
                key: "renderScene",
                get: function get() {
                  return this._renderScene;
                }
              }, {
                key: "globals",
                get: function get() {
                  return this._globals;
                }
              }, {
                key: "position",
                get: function get() {
                  return Vec3.ZERO;
                }
              }, {
                key: "worldPosition",
                get: function get() {
                  return Vec3.ZERO;
                }
              }, {
                key: "rotation",
                get: function get() {
                  return Quat.IDENTITY;
                }
              }, {
                key: "worldRotation",
                get: function get() {
                  return Quat.IDENTITY;
                }
              }, {
                key: "scale",
                get: function get() {
                  return Vec3.ONE;
                }
              }, {
                key: "worldScale",
                get: function get() {
                  return Vec3.ONE;
                }
              }, {
                key: "eulerAngles",
                get: function get() {
                  return Vec3.ZERO;
                }
              }, {
                key: "worldMatrix",
                get: function get() {
                  return Mat4.IDENTITY;
                }
              }]);

              return Scene;
            }(BaseNode), _temp$y), (_applyDecoratedDescriptor(_class2$y.prototype, "globals", [editable], Object.getOwnPropertyDescriptor(_class2$y.prototype, "globals"), _class2$y.prototype), _descriptor$q = _applyDecoratedDescriptor(_class2$y.prototype, "autoReleaseAssets", [serializable, editable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor2$i = _applyDecoratedDescriptor(_class2$y.prototype, "_globals", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new SceneGlobals();
              }
            })), _class2$y)) || _class$A));
            legacyCC.Scene = Scene;

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

                if (!scene) {

                  return null;
                }

                referenceNode = scene;
              }

              return referenceNode.getChildByPath(path);
            }
            legacyCC.find = find;

            var fastRemoveAt$2 = array.fastRemoveAt;
            var IsStartCalled$1 = CCObject.Flags.IsStartCalled;
            var IsOnEnableCalled$1 = CCObject.Flags.IsOnEnableCalled;
            var IsEditorOnEnableCalled$1 = CCObject.Flags.IsEditorOnEnableCalled;

            function sortedIndex(array, comp) {
              var order = comp.constructor._executionOrder;
              var id = comp._id;
              var l = 0;

              for (var h = array.length - 1, m = h >>> 1; l <= h; m = l + h >>> 1) {
                var test = array[m];
                var testOrder = test.constructor._executionOrder;

                if (testOrder > order) {
                  h = m - 1;
                } else if (testOrder < order) {
                  l = m + 1;
                } else {
                  var testId = test._id;

                  if (testId > id) {
                    h = m - 1;
                  } else if (testId < id) {
                    l = m + 1;
                  } else {
                    return m;
                  }
                }
              }

              return ~l;
            }

            function stableRemoveInactive(iterator, flagToClear) {
              var array = iterator.array;
              var next = iterator.i + 1;

              while (next < array.length) {
                var comp = array[next];

                if (comp.node._activeInHierarchy) {
                  ++next;
                } else {
                  iterator.removeAt(next);

                  if (flagToClear) {
                    comp._objFlags &= ~flagToClear;
                  }
                }
              }
            }

            var LifeCycleInvoker = function LifeCycleInvoker(invokeFunc) {
              this._zero = void 0;
              this._neg = void 0;
              this._pos = void 0;
              this._invoke = void 0;
              var Iterator = MutableForwardIterator;
              this._zero = new Iterator([]);
              this._neg = new Iterator([]);
              this._pos = new Iterator([]);

              this._invoke = invokeFunc;
            };
            LifeCycleInvoker.stableRemoveInactive = stableRemoveInactive;

            function compareOrder(a, b) {
              return a.constructor._executionOrder - b.constructor._executionOrder;
            }

            var OneOffInvoker = function (_LifeCycleInvoker) {
              _inheritsLoose(OneOffInvoker, _LifeCycleInvoker);

              function OneOffInvoker() {
                return _LifeCycleInvoker.apply(this, arguments) || this;
              }

              var _proto = OneOffInvoker.prototype;

              _proto.add = function add(comp) {
                var order = comp.constructor._executionOrder;
                (order === 0 ? this._zero : order < 0 ? this._neg : this._pos).array.push(comp);
              };

              _proto.remove = function remove(comp) {
                var order = comp.constructor._executionOrder;
                (order === 0 ? this._zero : order < 0 ? this._neg : this._pos).fastRemove(comp);
              };

              _proto.cancelInactive = function cancelInactive(flagToClear) {
                stableRemoveInactive(this._zero, flagToClear);
                stableRemoveInactive(this._neg, flagToClear);
                stableRemoveInactive(this._pos, flagToClear);
              };

              _proto.invoke = function invoke() {
                var compsNeg = this._neg;

                if (compsNeg.array.length > 0) {
                  compsNeg.array.sort(compareOrder);

                  this._invoke(compsNeg);

                  compsNeg.array.length = 0;
                }

                this._invoke(this._zero);

                this._zero.array.length = 0;
                var compsPos = this._pos;

                if (compsPos.array.length > 0) {
                  compsPos.array.sort(compareOrder);

                  this._invoke(compsPos);

                  compsPos.array.length = 0;
                }
              };

              return OneOffInvoker;
            }(LifeCycleInvoker);

            var ReusableInvoker = function (_LifeCycleInvoker2) {
              _inheritsLoose(ReusableInvoker, _LifeCycleInvoker2);

              function ReusableInvoker() {
                return _LifeCycleInvoker2.apply(this, arguments) || this;
              }

              var _proto2 = ReusableInvoker.prototype;

              _proto2.add = function add(comp) {
                var order = comp.constructor._executionOrder;

                if (order === 0) {
                  this._zero.array.push(comp);
                } else {
                  var _array = order < 0 ? this._neg.array : this._pos.array;

                  var i = sortedIndex(_array, comp);

                  if (i < 0) {
                    _array.splice(~i, 0, comp);
                  }
                }
              };

              _proto2.remove = function remove(comp) {
                var order = comp.constructor._executionOrder;

                if (order === 0) {
                  this._zero.fastRemove(comp);
                } else {
                  var iterator = order < 0 ? this._neg : this._pos;
                  var i = sortedIndex(iterator.array, comp);

                  if (i >= 0) {
                    iterator.removeAt(i);
                  }
                }
              };

              _proto2.invoke = function invoke(dt) {
                if (this._neg.array.length > 0) {
                  this._invoke(this._neg, dt);
                }

                this._invoke(this._zero, dt);

                if (this._pos.array.length > 0) {
                  this._invoke(this._pos, dt);
                }
              };

              return ReusableInvoker;
            }(LifeCycleInvoker);

            function createInvokeImplJit(code, useDt, ensureFlag) {
              var body = "" + ('var a=it.array;' + 'for(it.i=0;it.i<a.length;++it.i){' + 'var c=a[it.i];') + code + "}";
              var fastPath = useDt ? Function('it', 'dt', body) : Function('it', body);
              var singleInvoke = Function('c', 'dt', code);
              return createInvokeImpl(singleInvoke, fastPath, ensureFlag);
            }
            function createInvokeImpl(singleInvoke, fastPath, ensureFlag) {
              return function (iterator, dt) {
                try {
                  fastPath(iterator, dt);
                } catch (e) {
                  legacyCC._throw(e);

                  var _array2 = iterator.array;

                  if (ensureFlag) {
                    _array2[iterator.i]._objFlags |= ensureFlag;
                  }

                  ++iterator.i;

                  for (; iterator.i < _array2.length; ++iterator.i) {
                    try {
                      singleInvoke(_array2[iterator.i], dt);
                    } catch (e) {
                      legacyCC._throw(e);

                      if (ensureFlag) {
                        _array2[iterator.i]._objFlags |= ensureFlag;
                      }
                    }
                  }
                }
              };
            }
            var invokeStart =  createInvokeImplJit("c.start();c._objFlags|=" + IsStartCalled$1, false, IsStartCalled$1) ;
            var invokeUpdate =  createInvokeImplJit('c.update(dt)', true) ;
            var invokeLateUpdate =  createInvokeImplJit('c.lateUpdate(dt)', true) ;
            var invokeOnEnable =  function (iterator) {
              var compScheduler = legacyCC.director._compScheduler;
              var array = iterator.array;

              for (iterator.i = 0; iterator.i < array.length; ++iterator.i) {
                var comp = array[iterator.i];

                if (comp._enabled) {
                  comp.onEnable();
                  var deactivatedDuringOnEnable = !comp.node._activeInHierarchy;

                  if (!deactivatedDuringOnEnable) {
                    compScheduler._onEnabled(comp);
                  }
                }
              }
            };
            var ComponentScheduler = function () {
              function ComponentScheduler() {
                this._deferredComps = [];
                this.unscheduleAll();
              }

              var _proto3 = ComponentScheduler.prototype;

              _proto3.unscheduleAll = function unscheduleAll() {
                this.startInvoker = new OneOffInvoker(invokeStart);
                this.updateInvoker = new ReusableInvoker(invokeUpdate);
                this.lateUpdateInvoker = new ReusableInvoker(invokeLateUpdate);
                this._updating = false;
              };

              _proto3._onEnabled = function _onEnabled(comp) {
                legacyCC.director.getScheduler().resumeTarget(comp);
                comp._objFlags |= IsOnEnableCalled$1;

                if (this._updating) {
                  this._deferredComps.push(comp);
                } else {
                  this._scheduleImmediate(comp);
                }
              };

              _proto3._onDisabled = function _onDisabled(comp) {
                legacyCC.director.getScheduler().pauseTarget(comp);
                comp._objFlags &= ~IsOnEnableCalled$1;

                var index = this._deferredComps.indexOf(comp);

                if (index >= 0) {
                  fastRemoveAt$2(this._deferredComps, index);
                  return;
                }

                if (comp.start && !(comp._objFlags & IsStartCalled$1)) {
                  this.startInvoker.remove(comp);
                }

                if (comp.update) {
                  this.updateInvoker.remove(comp);
                }

                if (comp.lateUpdate) {
                  this.lateUpdateInvoker.remove(comp);
                }
              };

              _proto3.enableComp = function enableComp(comp, invoker) {
                if (!(comp._objFlags & IsOnEnableCalled$1)) {
                  if (comp.onEnable) {
                    if (invoker) {
                      invoker.add(comp);
                      return;
                    } else {
                      comp.onEnable();
                      var deactivatedDuringOnEnable = !comp.node._activeInHierarchy;

                      if (deactivatedDuringOnEnable) {
                        return;
                      }
                    }
                  }

                  this._onEnabled(comp);
                }
              };

              _proto3.disableComp = function disableComp(comp) {
                if (comp._objFlags & IsOnEnableCalled$1) {
                  if (comp.onDisable) {
                    comp.onDisable();
                  }

                  this._onDisabled(comp);
                }
              };

              _proto3.startPhase = function startPhase() {
                this._updating = true;
                this.startInvoker.invoke();

                this._startForNewComps();
              };

              _proto3.updatePhase = function updatePhase(dt) {
                this.updateInvoker.invoke(dt);
              };

              _proto3.lateUpdatePhase = function lateUpdatePhase(dt) {
                this.lateUpdateInvoker.invoke(dt);
                this._updating = false;

                this._startForNewComps();
              };

              _proto3._startForNewComps = function _startForNewComps() {
                if (this._deferredComps.length > 0) {
                  this._deferredSchedule();

                  this.startInvoker.invoke();
                }
              };

              _proto3._scheduleImmediate = function _scheduleImmediate(comp) {
                if (typeof comp.start === 'function' && !(comp._objFlags & IsStartCalled$1)) {
                  this.startInvoker.add(comp);
                }

                if (typeof comp.update === 'function') {
                  this.updateInvoker.add(comp);
                }

                if (typeof comp.lateUpdate === 'function') {
                  this.lateUpdateInvoker.add(comp);
                }
              };

              _proto3._deferredSchedule = function _deferredSchedule() {
                var comps = this._deferredComps;

                for (var i = 0, len = comps.length; i < len; i++) {
                  this._scheduleImmediate(comps[i]);
                }

                comps.length = 0;
              };

              return ComponentScheduler;
            }();

            var MAX_POOL_SIZE$1 = 4;
            var IsPreloadStarted$1 = CCObject.Flags.IsPreloadStarted;
            var IsOnLoadStarted$1 = CCObject.Flags.IsOnLoadStarted;
            var IsOnLoadCalled$2 = CCObject.Flags.IsOnLoadCalled;
            var Deactivating$2 = CCObject.Flags.Deactivating;

            var UnsortedInvoker = function (_LifeCycleInvoker) {
              _inheritsLoose(UnsortedInvoker, _LifeCycleInvoker);

              function UnsortedInvoker() {
                return _LifeCycleInvoker.apply(this, arguments) || this;
              }

              var _proto = UnsortedInvoker.prototype;

              _proto.add = function add(comp) {
                this._zero.array.push(comp);
              };

              _proto.remove = function remove(comp) {
                this._zero.fastRemove(comp);
              };

              _proto.cancelInactive = function cancelInactive(flagToClear) {
                LifeCycleInvoker.stableRemoveInactive(this._zero, flagToClear);
              };

              _proto.invoke = function invoke() {
                this._invoke(this._zero);

                this._zero.array.length = 0;
              };

              return UnsortedInvoker;
            }(LifeCycleInvoker);

            var invokePreload =  createInvokeImplJit('c.__preload();') ;
            var invokeOnLoad =  createInvokeImplJit("c.onLoad();c._objFlags|=" + IsOnLoadCalled$2, false, IsOnLoadCalled$2) ;
            var activateTasksPool = new Pool(MAX_POOL_SIZE$1);

            activateTasksPool.get = function getActivateTask() {
              var task = this._get() || {
                preload: new UnsortedInvoker(invokePreload),
                onLoad: new OneOffInvoker(invokeOnLoad),
                onEnable: new OneOffInvoker(invokeOnEnable)
              };
              task.preload._zero.i = -1;
              var invoker = task.onLoad;
              invoker._zero.i = -1;
              invoker._neg.i = -1;
              invoker._pos.i = -1;
              invoker = task.onEnable;
              invoker._zero.i = -1;
              invoker._neg.i = -1;
              invoker._pos.i = -1;
              return task;
            };

            function _componentCorrupted(node, comp, index) {

              if (comp) {
                node._removeComponent(comp);
              } else {
                array.removeAt(node._components, index);
              }
            }

            var NodeActivator = exports('NodeActivator', function () {
              function NodeActivator() {
                this.resetComp = void 0;
                this.reset();
              }

              var _proto2 = NodeActivator.prototype;

              _proto2.reset = function reset() {
                this._activatingStack = [];
              };

              _proto2.activateNode = function activateNode(node, active) {
                if (active) {
                  var task = activateTasksPool.get();

                  this._activatingStack.push(task);

                  this._activateNodeRecursively(node, task.preload, task.onLoad, task.onEnable);

                  task.preload.invoke();
                  task.onLoad.invoke();
                  task.onEnable.invoke();

                  this._activatingStack.pop();

                  activateTasksPool.put(task);
                } else {
                  this._deactivateNodeRecursively(node);

                  var stack = this._activatingStack;

                  for (var _iterator = _createForOfIteratorHelperLoose(stack), _step; !(_step = _iterator()).done;) {
                    var lastTask = _step.value;
                    lastTask.preload.cancelInactive(IsPreloadStarted$1);
                    lastTask.onLoad.cancelInactive(IsOnLoadStarted$1);
                    lastTask.onEnable.cancelInactive();
                  }
                }

                node.emit('active-in-hierarchy-changed', node);
              };

              _proto2.activateComp = function activateComp(comp, preloadInvoker, onLoadInvoker, onEnableInvoker) {
                if (!isValid(comp, true)) {
                  return;
                }

                if (!(comp._objFlags & IsPreloadStarted$1)) {
                  comp._objFlags |= IsPreloadStarted$1;

                  if (comp.__preload) {
                    if (preloadInvoker) {
                      preloadInvoker.add(comp);
                    } else {
                      comp.__preload();
                    }
                  }
                }

                if (!(comp._objFlags & IsOnLoadStarted$1)) {
                  comp._objFlags |= IsOnLoadStarted$1;

                  if (comp.onLoad) {
                    if (onLoadInvoker) {
                      onLoadInvoker.add(comp);
                    } else {
                      comp.onLoad();
                      comp._objFlags |= IsOnLoadCalled$2;
                    }
                  } else {
                    comp._objFlags |= IsOnLoadCalled$2;
                  }
                }

                if (comp._enabled) {
                  var deactivatedOnLoading = !comp.node._activeInHierarchy;

                  if (deactivatedOnLoading) {
                    return;
                  }

                  legacyCC.director._compScheduler.enableComp(comp, onEnableInvoker);
                }
              };

              _proto2.destroyComp = function destroyComp(comp) {
                legacyCC.director._compScheduler.disableComp(comp);

                if (comp.onDestroy && comp._objFlags & IsOnLoadCalled$2) {
                  comp.onDestroy();
                }
              };

              _proto2._activateNodeRecursively = function _activateNodeRecursively(node, preloadInvoker, onLoadInvoker, onEnableInvoker) {
                if (node._objFlags & Deactivating$2) {
                  errorID(3816, node.name);
                  return;
                }

                node._activeInHierarchy = true;
                var originCount = node._components.length;

                for (var i = 0; i < originCount; ++i) {
                  var component = node._components[i];

                  if (component instanceof legacyCC.Component) {
                    this.activateComp(component, preloadInvoker, onLoadInvoker, onEnableInvoker);
                  } else {
                    _componentCorrupted(node, component, i);

                    --i;
                    --originCount;
                  }
                }

                node._childArrivalOrder = node._children.length;

                for (var _i = 0, len = node._children.length; _i < len; ++_i) {
                  var child = node._children[_i];

                  if (child._active) {
                    this._activateNodeRecursively(child, preloadInvoker, onLoadInvoker, onEnableInvoker);
                  }
                }

                node._onPostActivated(true);
              };

              _proto2._deactivateNodeRecursively = function _deactivateNodeRecursively(node) {

                node._objFlags |= Deactivating$2;
                node._activeInHierarchy = false;
                var originCount = node._components.length;

                for (var c = 0; c < originCount; ++c) {
                  var component = node._components[c];

                  if (component._enabled) {
                    legacyCC.director._compScheduler.disableComp(component);

                    if (node._activeInHierarchy) {
                      node._objFlags &= ~Deactivating$2;
                      return;
                    }
                  }
                }

                for (var i = 0, len = node._children.length; i < len; ++i) {
                  var child = node._children[i];

                  if (child._activeInHierarchy) {
                    this._deactivateNodeRecursively(child);

                    if (node._activeInHierarchy) {
                      node._objFlags &= ~Deactivating$2;
                      return;
                    }
                  }
                }

                node._onPostActivated(false);

                node._objFlags &= ~Deactivating$2;
              };

              return NodeActivator;
            }());

            var _dec$B, _class$B, _class2$z, _descriptor$r, _temp$z;
            var SceneAsset = exports('SceneAsset', (_dec$B = ccclass('cc.SceneAsset'), _dec$B(_class$B = (_class2$z = (_temp$z = function (_Asset) {
              _inheritsLoose(SceneAsset, _Asset);

              function SceneAsset() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "scene", _descriptor$r, _assertThisInitialized(_this));

                return _this;
              }

              var _proto = SceneAsset.prototype;

              _proto.initDefault = function initDefault(uuid) {
                _Asset.prototype.initDefault.call(this, uuid);

                this.scene = new Scene('New Scene');
              };

              _proto.validate = function validate() {
                return !!this.scene;
              };

              return SceneAsset;
            }(Asset), _temp$z), (_descriptor$r = _applyDecoratedDescriptor(_class2$z.prototype, "scene", [editable, serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            })), _class2$z)) || _class$B));
            legacyCC.SceneAsset = SceneAsset;

            var _dec$C, _class$C, _class2$A, _descriptor$s, _temp$A;
            var TextAsset = exports('TextAsset', (_dec$C = ccclass('cc.TextAsset'), _dec$C(_class$C = (_class2$A = (_temp$A = function (_Asset) {
              _inheritsLoose(TextAsset, _Asset);

              function TextAsset() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "text", _descriptor$s, _assertThisInitialized(_this));

                return _this;
              }

              var _proto = TextAsset.prototype;

              _proto.toString = function toString() {
                return this.text;
              };

              return TextAsset;
            }(Asset), _temp$A), (_descriptor$s = _applyDecoratedDescriptor(_class2$A.prototype, "text", [serializable, editable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return '';
              }
            })), _class2$A)) || _class$C));
            legacyCC.TextAsset = TextAsset;

            var _dec$D, _class$D, _class2$B, _descriptor$t, _temp$B;
            var JsonAsset = exports('JsonAsset', (_dec$D = ccclass('cc.JsonAsset'), _dec$D(_class$D = (_class2$B = (_temp$B = function (_Asset) {
              _inheritsLoose(JsonAsset, _Asset);

              function JsonAsset() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "json", _descriptor$t, _assertThisInitialized(_this));

                return _this;
              }

              return JsonAsset;
            }(Asset), _temp$B), (_descriptor$t = _applyDecoratedDescriptor(_class2$B.prototype, "json", [serializable, editable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            })), _class2$B)) || _class$D));
            legacyCC.JsonAsset = JsonAsset;

            var Director = exports('Director', function (_EventTarget) {
              _inheritsLoose(Director, _EventTarget);

              function Director() {
                var _this;

                _this = _EventTarget.call(this) || this;
                _this._compScheduler = void 0;
                _this._nodeActivator = void 0;
                _this._invalid = void 0;
                _this._paused = void 0;
                _this._purgeDirectorInNextLoop = void 0;
                _this._root = void 0;
                _this._loadingScene = void 0;
                _this._scene = void 0;
                _this._totalFrames = void 0;
                _this._lastUpdate = void 0;
                _this._deltaTime = void 0;
                _this._startTime = void 0;
                _this._scheduler = void 0;
                _this._systems = void 0;
                _this._invalid = false;
                _this._paused = false;
                _this._purgeDirectorInNextLoop = false;
                _this._root = null;
                _this._loadingScene = '';
                _this._scene = null;
                _this._totalFrames = 0;
                _this._lastUpdate = 0;
                _this._deltaTime = 0.0;
                _this._startTime = 0.0;
                _this._scheduler = new Scheduler();
                _this._compScheduler = new ComponentScheduler();
                _this._nodeActivator = new NodeActivator();
                _this._systems = [];
                legacyCC.game.once(Game.EVENT_RENDERER_INITED, _this._initOnRendererInitialized, _assertThisInitialized(_this));
                return _this;
              }

              var _proto = Director.prototype;

              _proto.calculateDeltaTime = function calculateDeltaTime(now) {
                if (!now) now = performance.now();
                this._deltaTime = now > this._lastUpdate ? (now - this._lastUpdate) / 1000 : 0;

                if ( this._deltaTime > 1) {
                  this._deltaTime = 1 / 60.0;
                }

                this._lastUpdate = now;
              };

              _proto.convertToGL = function convertToGL(uiPoint) {
                var container = legacyCC.game.container;
                var view = legacyCC.view;
                var box = container.getBoundingClientRect();
                var left = box.left + window.pageXOffset - container.clientLeft;
                var top = box.top + window.pageYOffset - container.clientTop;
                var x = view._devicePixelRatio * (uiPoint.x - left);
                var y = view._devicePixelRatio * (top + box.height - uiPoint.y);
                return view._isRotated ? v2(view._viewportRect.width - y, x) : v2(x, y);
              };

              _proto.convertToUI = function convertToUI(glPoint) {
                var container = legacyCC.game.container;
                var view = legacyCC.view;
                var box = container.getBoundingClientRect();
                var left = box.left + window.pageXOffset - container.clientLeft;
                var top = box.top + window.pageYOffset - container.clientTop;
                var uiPoint = v2(0, 0);

                if (view._isRotated) {
                  uiPoint.x = left + glPoint.y / view._devicePixelRatio;
                  uiPoint.y = top + box.height - (view._viewportRect.width - glPoint.x) / view._devicePixelRatio;
                } else {
                  uiPoint.x = left + glPoint.x * view._devicePixelRatio;
                  uiPoint.y = top + box.height - glPoint.y * view._devicePixelRatio;
                }

                return uiPoint;
              };

              _proto.end = function end() {
                this._purgeDirectorInNextLoop = true;
              };

              _proto.getWinSize = function getWinSize() {
                return size(legacyCC.winSize);
              };

              _proto.getWinSizeInPixels = function getWinSizeInPixels() {
                return size(legacyCC.winSize);
              };

              _proto.pause = function pause() {
                if (this._paused) {
                  return;
                }

                this._paused = true;
              };

              _proto.purgeCachedData = function purgeCachedData() {
                legacyCC.assetManager.releaseAll();
              };

              _proto.purgeDirector = function purgeDirector() {
                this._scheduler.unscheduleAll();

                this._compScheduler.unscheduleAll();

                this._nodeActivator.reset();

                if (eventManager) {
                  eventManager.setEnabled(false);
                }

                {
                  if (legacyCC.isValid(this._scene)) {
                    this._scene.destroy();
                  }

                  this._scene = null;
                }

                this.stopAnimation();
                legacyCC.assetManager.releaseAll();
              };

              _proto.reset = function reset() {
                this.purgeDirector();
                this.emit(Director.EVENT_RESET);

                if (eventManager) {
                  eventManager.setEnabled(true);
                }

                this.startAnimation();
              };

              _proto.runSceneImmediate = function 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');
                }

                var persistNodeList = Object.keys(legacyCC.game._persistRootNodes).map(function (x) {
                  return legacyCC.game._persistRootNodes[x];
                });

                for (var i = 0; i < persistNodeList.length; i++) {
                  var node = persistNodeList[i];
                  node.emit(legacyCC.Node.SCENE_CHANGED_FOR_PERSISTS, scene.renderScene);
                  var existNode = scene.uuid === node._originalSceneId && scene.getChildByUuid(node.uuid);

                  if (existNode) {
                    var index = existNode.getSiblingIndex();

                    existNode._destroyImmediate();

                    scene.insertChild(node, index);
                  } else {
                    node.parent = scene;
                  }
                }

                {
                  console.timeEnd('AttachPersist');
                }

                var oldScene = this._scene;

                {
                  console.time('Destroy');
                }

                if (legacyCC.isValid(oldScene)) {
                  oldScene.destroy();
                }

                {
                  {
                    console.time('AutoRelease');
                  }

                  legacyCC.assetManager._releaseManager._autoRelease(oldScene, scene, legacyCC.game._persistRootNodes);

                  {
                    console.timeEnd('AutoRelease');
                  }
                }

                this._scene = null;

                CCObject._deferredDestroy();

                {
                  console.timeEnd('Destroy');
                }

                if (onBeforeLoadScene) {
                  onBeforeLoadScene();
                }

                this.emit(legacyCC.Director.EVENT_BEFORE_SCENE_LAUNCH, scene);
                this._scene = scene;

                {
                  console.time('Activate');
                }

                scene._activate();

                {
                  console.timeEnd('Activate');
                }

                if (this._root) {
                  this._root.resetCumulativeTime();
                }

                this.startAnimation();

                if (onLaunched) {
                  onLaunched(null, scene);
                }

                this.emit(legacyCC.Director.EVENT_AFTER_SCENE_LAUNCH, scene);
              };

              _proto.runScene = function runScene(scene, onBeforeLoadScene, onLaunched) {
                var _this2 = this;

                if (scene instanceof SceneAsset) scene = scene.scene;
                assertID(scene, 1205);
                assertID(scene instanceof Scene, 1216);

                scene._load();

                this.once(legacyCC.Director.EVENT_AFTER_DRAW, function () {
                  _this2.runSceneImmediate(scene, onBeforeLoadScene, onLaunched);
                });
              };

              _proto.loadScene = function loadScene(sceneName, onLaunched, onUnloaded) {
                var _this3 = this;

                if (this._loadingScene) {
                  warnID(1208, sceneName, this._loadingScene);
                  return false;
                }

                var bundle = legacyCC.assetManager.bundles.find(function (bundle) {
                  return !!bundle.getSceneInfo(sceneName);
                });

                if (bundle) {
                  this.emit(legacyCC.Director.EVENT_BEFORE_SCENE_LOADING, sceneName);
                  this._loadingScene = sceneName;
                  console.time("LoadScene " + sceneName);
                  bundle.loadScene(sceneName, function (err, scene) {
                    console.timeEnd("LoadScene " + sceneName);
                    _this3._loadingScene = '';

                    if (err) {
                      error(err);

                      if (onLaunched) {
                        onLaunched(err);
                      }
                    } else {
                      _this3.runSceneImmediate(scene, onUnloaded, onLaunched);
                    }
                  });
                  return true;
                } else {
                  errorID(1209, sceneName);
                  return false;
                }
              };

              _proto.preloadScene = function preloadScene(sceneName, onProgress, onLoaded) {
                var bundle = legacyCC.assetManager.bundles.find(function (bundle) {
                  return !!bundle.getSceneInfo(sceneName);
                });

                if (bundle) {
                  bundle.preloadScene(sceneName, null, onProgress, onLoaded);
                } else {
                  var err = "Can not preload the scene \"" + sceneName + "\" because it is not in the build settings.";

                  if (onLoaded) {
                    onLoaded(new Error(err));
                  }

                  error("preloadScene: " + err);
                }
              };

              _proto.resume = function resume() {
                if (!this._paused) {
                  return;
                }

                this._lastUpdate = performance.now();

                if (!this._lastUpdate) {
                  logID(1200);
                }

                this._paused = false;
                this._deltaTime = 0;
              };

              _proto.setDepthTest = function setDepthTest(value) {
                if (!legacyCC.Camera.main) {
                  return;
                }

                legacyCC.Camera.main.depth = !!value;
              };

              _proto.setClearColor = function setClearColor(clearColor) {
                if (!legacyCC.Camera.main) {
                  return;
                }

                legacyCC.Camera.main.backgroundColor = clearColor;
              };

              _proto.getRunningScene = function getRunningScene() {
                return this._scene;
              };

              _proto.getScene = function getScene() {
                return this._scene;
              };

              _proto.getAnimationInterval = function getAnimationInterval() {
                return 1000 / legacyCC.game.getFrameRate();
              };

              _proto.setAnimationInterval = function setAnimationInterval(value) {
                legacyCC.game.setFrameRate(Math.round(1000 / value));
              };

              _proto.getDeltaTime = function getDeltaTime() {
                return this._deltaTime;
              };

              _proto.getTotalTime = function getTotalTime() {
                return performance.now() - this._startTime;
              };

              _proto.getCurrentTime = function getCurrentTime() {
                return this._lastUpdate;
              };

              _proto.getTotalFrames = function getTotalFrames() {
                return this._totalFrames;
              };

              _proto.isPaused = function isPaused() {
                return this._paused;
              };

              _proto.getScheduler = function getScheduler() {
                return this._scheduler;
              };

              _proto.setScheduler = function setScheduler(scheduler) {
                if (this._scheduler !== scheduler) {
                  this.unregisterSystem(this._scheduler);
                  this._scheduler = scheduler;
                  this.registerSystem(Scheduler.ID, scheduler, 200);
                }
              };

              _proto.registerSystem = function registerSystem(name, sys, priority) {
                sys.id = name;
                sys.priority = priority;
                sys.init();

                this._systems.push(sys);

                this._systems.sort(System$1.sortByPriority);
              };

              _proto.unregisterSystem = function unregisterSystem(sys) {
                array.fastRemove(this._systems, sys);

                this._systems.sort(System$1.sortByPriority);
              };

              _proto.getSystem = function getSystem(name) {
                return this._systems.find(function (sys) {
                  return sys.id === name;
                });
              };

              _proto.getAnimationManager = function getAnimationManager() {
                return this.getSystem(legacyCC.AnimationManager.ID);
              };

              _proto.startAnimation = function startAnimation() {
                this._invalid = false;
                this._lastUpdate = performance.now();
              };

              _proto.stopAnimation = function stopAnimation() {
                this._invalid = true;
              };

              _proto.mainLoop = function mainLoop(time) {
                if (this._purgeDirectorInNextLoop) {
                  this._purgeDirectorInNextLoop = false;
                  this.purgeDirector();
                } else if (!this._invalid) {
                  {
                    this.calculateDeltaTime(time);
                  }

                  this.emit(Director.EVENT_BEGIN_FRAME);
                  var dt = this._deltaTime;

                  if (!this._paused) {
                    this.emit(Director.EVENT_BEFORE_UPDATE);

                    this._compScheduler.startPhase();

                    this._compScheduler.updatePhase(dt);

                    for (var i = 0; i < this._systems.length; ++i) {
                      this._systems[i].update(dt);
                    }

                    this._compScheduler.lateUpdatePhase(dt);

                    this.emit(Director.EVENT_AFTER_UPDATE);

                    CCObject._deferredDestroy();

                    for (var _i = 0; _i < this._systems.length; ++_i) {
                      this._systems[_i].postUpdate(dt);
                    }
                  }

                  this.emit(Director.EVENT_BEFORE_DRAW);

                  this._root.frameMove(this._deltaTime);

                  this.emit(Director.EVENT_AFTER_DRAW);
                  eventManager.frameUpdateListeners();
                  Node$1.resetHasChangedFlags();
                  Node$1.clearNodeArray();
                  this.emit(Director.EVENT_END_FRAME);
                  this._totalFrames++;
                }
              };

              _proto._initOnRendererInitialized = function _initOnRendererInitialized() {
                this._totalFrames = 0;
                this._lastUpdate = performance.now();
                this._startTime = this._lastUpdate;
                this._paused = false;
                this._purgeDirectorInNextLoop = false;

                if (eventManager) {
                  eventManager.setEnabled(true);
                }

                this.registerSystem(Scheduler.ID, this._scheduler, 200);
                this.emit(Director.EVENT_INIT);
              };

              _proto._init = function _init() {
                this._root = new Root(legacyCC.game._gfxDevice);
                var rootInfo = {};
                return this._root.initialize(rootInfo)["catch"](function (error) {
                  errorID(1217);
                  return Promise.reject(error);
                });
              };

              _createClass(Director, [{
                key: "root",
                get: function get() {
                  return this._root;
                }
              }]);

              return Director;
            }(EventTarget));
            Director.EVENT_INIT = 'director_init';
            Director.EVENT_RESET = 'director_reset';
            Director.EVENT_BEFORE_SCENE_LOADING = 'director_before_scene_loading';
            Director.EVENT_BEFORE_SCENE_LAUNCH = 'director_before_scene_launch';
            Director.EVENT_AFTER_SCENE_LAUNCH = 'director_after_scene_launch';
            Director.EVENT_BEFORE_UPDATE = 'director_before_update';
            Director.EVENT_AFTER_UPDATE = 'director_after_update';
            Director.EVENT_BEFORE_DRAW = 'director_before_draw';
            Director.EVENT_AFTER_DRAW = 'director_after_draw';
            Director.EVENT_BEFORE_COMMIT = 'director_before_commit';
            Director.EVENT_BEFORE_PHYSICS = 'director_before_physics';
            Director.EVENT_AFTER_PHYSICS = 'director_after_physics';
            Director.EVENT_BEGIN_FRAME = 'director_begin_frame';
            Director.EVENT_END_FRAME = 'director_end_frame';
            Director.instance = void 0;
            legacyCC.Director = Director;
            var director = exports('director', Director.instance = legacyCC.director = new Director());

            var isMatchByWord = function isMatchByWord(path, test) {
              if (path.length > test.length) {
                var nextAscii = path.charCodeAt(test.length);
                return nextAscii === 47;
              }

              return true;
            };

            var processOptions = function processOptions(options) {

              var uuids = options.uuids;
              var paths = options.paths;
              var types = options.types;
              var bundles = options.deps;
              var realEntries = options.paths = Object.create(null);

              if (options.debug === false) {
                for (var i = 0, l = uuids.length; i < l; i++) {
                  uuids[i] = decodeUuid(uuids[i]);
                }

                for (var id in paths) {
                  var entry = paths[id];
                  var type = entry[1];
                  entry[1] = types[type];
                }
              } else {
                var out = Object.create(null);

                for (var _i = 0, _l = uuids.length; _i < _l; _i++) {
                  var uuid = uuids[_i];
                  uuids[_i] = out[uuid] = decodeUuid(uuid);
                }

                uuids = out;
              }

              for (var _id in paths) {
                var _entry = paths[_id];
                realEntries[uuids[_id]] = _entry;
              }

              var scenes = options.scenes;

              for (var name in scenes) {
                var _uuid = scenes[name];
                scenes[name] = uuids[_uuid];
              }

              var packs = options.packs;

              for (var packId in packs) {
                var packedIds = packs[packId];

                for (var j = 0; j < packedIds.length; ++j) {
                  packedIds[j] = uuids[packedIds[j]];
                }
              }

              var versions = options.versions;

              if (versions) {
                for (var folder in versions) {
                  var entries = versions[folder];

                  for (var _i2 = 0; _i2 < entries.length; _i2 += 2) {
                    var _uuid2 = entries[_i2];
                    entries[_i2] = uuids[_uuid2] || _uuid2;
                  }
                }
              }

              var redirect = options.redirect;

              if (redirect) {
                for (var _i3 = 0; _i3 < redirect.length; _i3 += 2) {
                  redirect[_i3] = uuids[redirect[_i3]];
                  redirect[_i3 + 1] = bundles[redirect[_i3 + 1]];
                }
              }
            };

            var Config = function () {
              function Config() {
                this.name = '';
                this.base = '';
                this.importBase = '';
                this.nativeBase = '';
                this.deps = null;
                this.assetInfos = new Cache();
                this.scenes = new Cache();
                this.paths = new Cache();
              }

              var _proto = Config.prototype;

              _proto.init = function init(options) {
                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);
              };

              _proto.getInfoWithPath = function getInfoWithPath(path, type) {
                if (!path) {
                  return null;
                }

                path = normalize(path);
                var items = this.paths.get(path);

                if (items) {
                  if (type) {
                    for (var i = 0, l = items.length; i < l; i++) {
                      var assetInfo = items[i];

                      if (js.isChildClassOf(assetInfo.ctor, type)) {
                        return assetInfo;
                      }
                    }
                  } else {
                    return items[0];
                  }
                }

                return null;
              };

              _proto.getDirWithPath = function getDirWithPath(path, type, out) {
                path = normalize(path);

                if (path[path.length - 1] === '/') {
                  path = path.slice(0, -1);
                }

                var infos = out || [];
                this.paths.forEach(function (items, p) {
                  if (p.startsWith(path) && isMatchByWord(p, path) || !path) {
                    for (var i = 0, l = items.length; i < l; i++) {
                      var entry = items[i];

                      if (!type || js.isChildClassOf(entry.ctor, type)) {
                        infos.push(entry);
                      }
                    }
                  }
                });
                return infos;
              };

              _proto.getAssetInfo = function getAssetInfo(uuid) {
                return this.assetInfos.get(uuid) || null;
              };

              _proto.getSceneInfo = function getSceneInfo(name) {
                if (!name.endsWith('.scene')) {
                  name += '.scene';
                }

                if (name[0] !== '/' && !name.startsWith('db://')) {
                  name = "/" + name;
                }

                var info = this.scenes.find(function (val, key) {
                  return key.endsWith(name);
                });
                return info;
              };

              _proto.destroy = function destroy() {
                this.paths.destroy();
                this.scenes.destroy();
                this.assetInfos.destroy();
              };

              _proto._initUuid = function _initUuid(uuidList) {
                if (!uuidList) {
                  return;
                }

                this.assetInfos.clear();

                for (var i = 0, l = uuidList.length; i < l; i++) {
                  var uuid = uuidList[i];
                  this.assetInfos.add(uuid, {
                    uuid: uuid
                  });
                }
              };

              _proto._initPath = function _initPath(pathList) {
                if (!pathList) {
                  return;
                }

                var paths = this.paths;
                paths.clear();

                for (var uuid in pathList) {
                  var info = pathList[uuid];
                  var path = info[0];
                  var type = info[1];
                  var isSubAsset = info.length === 3;
                  var assetInfo = this.assetInfos.get(uuid);
                  assetInfo.path = path;
                  assetInfo.ctor = js._getClassById(type);

                  if (paths.has(path)) {
                    if (isSubAsset) {
                      paths.get(path).push(assetInfo);
                    } else {
                      paths.get(path).splice(0, 0, assetInfo);
                    }
                  } else {
                    paths.add(path, [assetInfo]);
                  }
                }
              };

              _proto._initScene = function _initScene(sceneList) {
                if (!sceneList) {
                  return;
                }

                var scenes = this.scenes;
                scenes.clear();
                var assetInfos = this.assetInfos;

                for (var sceneName in sceneList) {
                  var uuid = sceneList[sceneName];
                  var assetInfo = assetInfos.get(uuid);
                  assetInfo.url = sceneName;
                  scenes.add(sceneName, assetInfo);
                }
              };

              _proto._initPackage = function _initPackage(packageList) {
                if (!packageList) {
                  return;
                }

                var assetInfos = this.assetInfos;

                for (var packUuid in packageList) {
                  var uuids = packageList[packUuid];
                  var pack = {
                    uuid: packUuid,
                    packedUuids: uuids,
                    ext: '.json'
                  };
                  assetInfos.add(packUuid, pack);

                  for (var i = 0, l = uuids.length; i < l; i++) {
                    var uuid = uuids[i];
                    var assetInfo = assetInfos.get(uuid);
                    var assetPacks = assetInfo.packs;

                    if (assetPacks) {
                      if (l === 1) {
                        assetPacks.splice(0, 0, pack);
                      } else {
                        assetPacks.push(pack);
                      }
                    } else {
                      assetInfo.packs = [pack];
                    }
                  }
                }
              };

              _proto._initVersion = function _initVersion(versions) {
                if (!versions) {
                  return;
                }

                var assetInfos = this.assetInfos;
                var entries = versions["import"];

                if (entries) {
                  for (var i = 0, l = entries.length; i < l; i += 2) {
                    var uuid = entries[i];
                    var assetInfo = assetInfos.get(uuid);
                    assetInfo.ver = entries[i + 1];
                  }
                }

                entries = versions["native"];

                if (entries) {
                  for (var _i4 = 0, _l2 = entries.length; _i4 < _l2; _i4 += 2) {
                    var _uuid3 = entries[_i4];

                    var _assetInfo = assetInfos.get(_uuid3);

                    _assetInfo.nativeVer = entries[_i4 + 1];
                  }
                }
              };

              _proto._initRedirect = function _initRedirect(redirect) {
                if (!redirect) {
                  return;
                }

                var assetInfos = this.assetInfos;

                for (var i = 0, l = redirect.length; i < l; i += 2) {
                  var uuid = redirect[i];
                  var assetInfo = assetInfos.get(uuid);
                  assetInfo.redirect = redirect[i + 1];
                }
              };

              return Config;
            }();

            function visitAsset(asset, deps) {
              if (!asset._uuid) {
                return;
              }

              deps.push(asset._uuid);
            }

            function visitComponent(comp, deps) {
              var props = Object.getOwnPropertyNames(comp);

              for (var i = 0; i < props.length; i++) {
                var propName = props[i];

                if (propName === 'node' || propName === '__eventTargets') {
                  continue;
                }

                var value = comp[propName];

                if (typeof value === 'object' && value) {
                  if (Array.isArray(value)) {
                    for (var j = 0; j < value.length; j++) {
                      var val = value[j];

                      if (val instanceof Asset) {
                        visitAsset(val, deps);
                      }
                    }
                  } else if (!value.constructor || value.constructor === Object) {
                    var keys = Object.getOwnPropertyNames(value);

                    for (var _j = 0; _j < keys.length; _j++) {
                      var _val = value[keys[_j]];

                      if (_val instanceof Asset) {
                        visitAsset(_val, deps);
                      }
                    }
                  } else if (value instanceof Asset) {
                    visitAsset(value, deps);
                  }
                }
              }
            }

            function visitNode(node, deps) {
              for (var i = 0; i < node._components.length; i++) {
                visitComponent(node._components[i], deps);
              }

              for (var _i = 0; _i < node._children.length; _i++) {
                visitNode(node._children[_i], deps);
              }
            }

            function descendOpRef(asset, refs, exclude, op) {
              exclude.push(asset._uuid);
              var depends = dependUtil.getDeps(asset._uuid);

              for (var i = 0, l = depends.length; i < l; i++) {
                var dependAsset = assets.get(depends[i]);

                if (!dependAsset) {
                  continue;
                }

                var uuid = dependAsset._uuid;

                if (!(uuid in refs)) {
                  refs[uuid] = dependAsset.refCount + op;
                } else {
                  refs[uuid] += op;
                }

                if (exclude.includes(uuid)) {
                  continue;
                }

                descendOpRef(dependAsset, refs, exclude, op);
              }
            }

            var _temp$C = [];

            function checkCircularReference(asset) {
              var refs = Object.create(null);
              refs[asset._uuid] = asset.refCount;
              descendOpRef(asset, refs, _temp$C, -1);
              _temp$C.length = 0;

              if (refs[asset._uuid] !== 0) {
                return refs[asset._uuid];
              }

              for (var uuid in refs) {
                if (refs[uuid] !== 0) {
                  descendOpRef(assets.get(uuid), refs, _temp$C, 1);
                }
              }

              _temp$C.length = 0;
              return refs[asset._uuid];
            }

            var ReleaseManager = function () {
              function ReleaseManager() {
                this._persistNodeDeps = new Cache();
                this._toDelete = new Cache();
                this._eventListener = false;
              }

              var _proto = ReleaseManager.prototype;

              _proto.init = function init() {
                this._persistNodeDeps.clear();

                this._toDelete.clear();
              };

              _proto._addPersistNodeRef = function _addPersistNodeRef(node) {
                var deps = [];
                visitNode(node, deps);

                for (var i = 0, l = deps.length; i < l; i++) {
                  var dependAsset = assets.get(deps[i]);

                  if (dependAsset) {
                    dependAsset.addRef();
                  }
                }

                this._persistNodeDeps.add(node.uuid, deps);
              };

              _proto._removePersistNodeRef = function _removePersistNodeRef(node) {
                if (!this._persistNodeDeps.has(node.uuid)) {
                  return;
                }

                var deps = this._persistNodeDeps.get(node.uuid);

                for (var i = 0, l = deps.length; i < l; i++) {
                  var dependAsset = assets.get(deps[i]);

                  if (dependAsset) {
                    dependAsset.decRef();
                  }
                }

                this._persistNodeDeps.remove(node.uuid);
              };

              _proto._autoRelease = function _autoRelease(oldScene, newScene, persistNodes) {
                if (oldScene) {
                  var childs = dependUtil.getDeps(oldScene.uuid);

                  for (var i = 0, l = childs.length; i < l; i++) {
                    var asset = assets.get(childs[i]);

                    if (asset) {
                      asset.decRef( oldScene.autoReleaseAssets);
                    }
                  }

                  var dependencies = dependUtil._depends.get(oldScene.uuid);

                  if (dependencies && dependencies.persistDeps) {
                    var persistDeps = dependencies.persistDeps;

                    for (var _i2 = 0, _l = persistDeps.length; _i2 < _l; _i2++) {
                      var _asset = assets.get(persistDeps[_i2]);

                      if (_asset) {
                        _asset.decRef( oldScene.autoReleaseAssets);
                      }
                    }
                  }

                  if (oldScene.uuid !== newScene.uuid) {
                    dependUtil.remove(oldScene.uuid);
                  }
                }

                var sceneDeps = dependUtil._depends.get(newScene.uuid);

                if (sceneDeps) {
                  sceneDeps.persistDeps = [];
                }

                for (var key in persistNodes) {
                  var _ref;

                  var node = persistNodes[key];

                  var deps = this._persistNodeDeps.get(node.uuid);

                  for (var _iterator = _createForOfIteratorHelperLoose(deps), _step; !(_step = _iterator()).done;) {
                    var dep = _step.value;
                    var dependAsset = assets.get(dep);

                    if (dependAsset) {
                      dependAsset.addRef();
                    }
                  }

                  if (!sceneDeps) {
                    continue;
                  }

                  (_ref = sceneDeps.persistDeps).push.apply(_ref, deps);
                }
              };

              _proto.tryRelease = function tryRelease(asset, force) {
                if (force === void 0) {
                  force = false;
                }

                if (!(asset instanceof Asset)) {
                  return;
                }

                if (force) {
                  this._free(asset, force);

                  return;
                }

                this._toDelete.add(asset._uuid, asset);

                if (!this._eventListener) {
                  this._eventListener = true;
                  callInNextTick(this._freeAssets.bind(this));
                }
              };

              _proto._freeAssets = function _freeAssets() {
                var _this = this;

                this._eventListener = false;

                this._toDelete.forEach(function (asset) {
                  _this._free(asset);
                });

                this._toDelete.clear();
              };

              _proto._free = function _free(asset, force) {
                if (force === void 0) {
                  force = false;
                }

                var uuid = asset._uuid;

                this._toDelete.remove(uuid);

                if (!isValid(asset, true)) {
                  return;
                }

                if (!force) {
                  if (asset.refCount > 0) {
                    if (checkCircularReference(asset) > 0) {
                      return;
                    }
                  }
                }

                assets.remove(uuid);
                var depends = dependUtil.getDeps(uuid);

                for (var i = 0, l = depends.length; i < l; i++) {
                  var dependAsset = assets.get(depends[i]);

                  if (dependAsset) {
                    dependAsset.decRef(false);

                    {
                      this._free(dependAsset, false);
                    }
                  }
                }

                {
                  asset.destroy();
                }

                dependUtil.remove(uuid);
              };

              return ReleaseManager;
            }();

            var releaseManager = new ReleaseManager();

            var defaultProgressCallback = null;
            function setDefaultProgressCallback(onProgress) {
              defaultProgressCallback = onProgress;
            }
            function clear$1(task, clearRef) {
              for (var i = 0, l = task.input.length; i < l; i++) {
                var _item = task.input[i];

                if (clearRef) {
                  if (!_item.isNative && _item.content instanceof Asset) {
                    _item.content.decRef(false);
                  }
                }

                _item.recycle();
              }

              task.input = null;
            }
            function urlAppendTimestamp(url, append) {
              if (append) {
                if (/\?/.test(url)) {
                  return url + "&_t=" + Date.now();
                }

                return url + "?_t=" + Date.now();
              }

              return url;
            }
            function retry(process, times, wait, onComplete, index) {
              if (index === void 0) {
                index = 0;
              }

              process(index, function (err, result) {
                index++;

                if (!err || index > times) {
                  if (onComplete) {
                    onComplete(err, result);
                  }
                } else {
                  setTimeout(function () {
                    retry(process, times, wait, onComplete, index);
                  }, wait);
                }
              });
            }
            function getDepends(uuid, data, exclude, depends, config) {
              try {
                var info = dependUtil.parse(uuid, data);

                for (var i = 0, l = info.deps.length; i < l; i++) {
                  var dep = info.deps[i];

                  if (!(dep in exclude)) {
                    exclude[dep] = true;
                    depends.push({
                      uuid: dep,
                      bundle: config && config.name
                    });
                  }
                }

                if (info.nativeDep) {
                  if (config) {
                    info.nativeDep.bundle = config.name;
                  }

                  depends.push(_extends({}, info.nativeDep));
                }
              } catch (e) {
                error(e.message, e.stack);
              }
            }
            function cache(id, asset, cacheAsset) {
              if (!asset) {
                return;
              }

              cacheAsset = cacheAsset !== undefined ? cacheAsset : legacyCC.assetManager.cacheAsset;

              if (!isScene(asset) && cacheAsset && !asset.isDefault) {
                assets.add(id, asset);
              }
            }
            function setProperties(uuid, asset, assetsMap) {
              var missingAsset = false;
              var depends = asset.__depends__;

              if (depends) {
                var missingAssetReporter = null;

                for (var i = 0, l = depends.length; i < l; i++) {
                  var depend = depends[i];
                  var dependAsset = assetsMap[depend.uuid + "@import"];

                  if (!dependAsset) {
                    {
                      error("The asset " + depend.uuid + " is missing!");
                    }

                    if (depend.type && depend.type !== Asset) {
                      var placeHolder = new depend.type();
                      placeHolder.initDefault(depend.uuid);
                      depend.owner[depend.prop] = placeHolder;
                    }

                    missingAsset = true;
                  } else {
                    depend.owner[depend.prop] = dependAsset.addRef();
                  }
                }

                if (missingAssetReporter) {
                  missingAssetReporter.reportByOwner();
                }

                asset.__depends__ = null;
              }

              if (asset.__nativeDepend__) {
                if (assetsMap[uuid + "@native"]) {
                  asset._nativeAsset = assetsMap[uuid + "@native"];
                } else {
                  missingAsset = true;
                  console.error("the native asset of " + uuid + " is missing!");
                }

                asset.__nativeDepend__ = false;
              }

              return missingAsset;
            }
            function gatherAsset(task) {
              var source = task.source;

              if (!task.options.__outputAsArray__ && source.length === 1) {
                task.output = source[0].content;
              } else {
                var output = task.output = [];

                for (var i = 0, l = source.length; i < l; i++) {
                  output.push(source[i].content);
                }
              }
            }
            function forEach(array, process, onComplete) {
              var count = 0;
              var errs = [];
              var length = array.length;

              if (length === 0 && onComplete) {
                onComplete(errs);
              }

              var cb = function cb(err) {
                if (err) {
                  errs.push(err);
                }

                count++;

                if (count === length) {
                  if (onComplete) {
                    onComplete(errs);
                  }
                }
              };

              for (var i = 0; i < length; i++) {
                process(array[i], cb);
              }
            }
            function parseParameters(options, onProgress, onComplete) {
              var optionsOut = options;
              var onProgressOut = onProgress;
              var onCompleteOut = onComplete;

              if (onComplete === undefined) {
                var isCallback = typeof options === 'function';

                if (onProgress) {
                  onCompleteOut = onProgress;

                  if (!isCallback) {
                    onProgressOut = null;
                  }
                } else if (onProgress === undefined && isCallback) {
                  onCompleteOut = options;
                  optionsOut = null;
                  onProgressOut = null;
                }

                if (onProgress !== undefined && isCallback) {
                  onProgressOut = options;
                  optionsOut = null;
                }
              }

              return {
                options: optionsOut || Object.create(null),
                onProgress: onProgressOut,
                onComplete: onCompleteOut
              };
            }
            function parseLoadResArgs(type, onProgress, onComplete) {
              var typeOut = type;
              var onProgressOut = onProgress;
              var onCompleteOut = onComplete;

              if (onComplete === undefined) {
                var isValidType = js.isChildClassOf(type, Asset);

                if (onProgress) {
                  onCompleteOut = onProgress;

                  if (isValidType) {
                    onProgressOut = null;
                  }
                } else if (onProgress === undefined && !isValidType) {
                  onCompleteOut = type;
                  onProgressOut = null;
                  typeOut = null;
                }

                if (onProgress !== undefined && !isValidType) {
                  onProgressOut = type;
                  typeOut = null;
                }
              }

              return {
                type: typeOut,
                onProgress: onProgressOut || defaultProgressCallback,
                onComplete: onCompleteOut
              };
            }
            function checkCircleReference(owner, uuid, map, checked) {
              if (checked === void 0) {
                checked = {};
              }

              var item = map[uuid];

              if (!item || checked[uuid]) {
                return false;
              }

              checked[uuid] = true;
              var result = false;
              var deps = dependUtil.getDeps(uuid);

              if (deps) {
                for (var i = 0, l = deps.length; i < l; i++) {
                  var dep = deps[i];

                  if (dep === owner || checkCircleReference(owner, dep, map, checked)) {
                    result = true;
                    break;
                  }
                }
              }

              return result;
            }
            function asyncify(cb) {
              return function (p1, p2) {
                if (!cb) {
                  return;
                }

                var refs = [];

                if (Array.isArray(p2)) {
                  p2.forEach(function (x) {
                    return x instanceof Asset && refs.push(x.addRef());
                  });
                } else if (p2 instanceof Asset) {
                  refs.push(p2.addRef());
                }

                callInNextTick(function () {
                  refs.forEach(function (x) {
                    return x.decRef(false);
                  });
                  cb(p1, p2);
                });
              };
            }

            var Bundle = function () {
              function Bundle() {
                this._config = new Config();
              }

              var _proto = Bundle.prototype;

              _proto.getInfoWithPath = function getInfoWithPath(path, type) {
                return this._config.getInfoWithPath(path, type);
              };

              _proto.getDirWithPath = function getDirWithPath(path, type, out) {
                return this._config.getDirWithPath(path, type, out);
              };

              _proto.getAssetInfo = function getAssetInfo(uuid) {
                return this._config.getAssetInfo(uuid);
              };

              _proto.getSceneInfo = function getSceneInfo(name) {
                return this._config.getSceneInfo(name);
              };

              _proto.init = function init(options) {
                this._config.init(options);

                bundles.add(options.name, this);
              };

              _proto.load = function load(paths, type, onProgress, onComplete) {
                var _parseLoadResArgs = parseLoadResArgs(type, onProgress, onComplete),
                    _type = _parseLoadResArgs.type,
                    onProg = _parseLoadResArgs.onProgress,
                    onComp = _parseLoadResArgs.onComplete;

                var options = {
                  __requestType__: RequestType.PATH,
                  type: _type,
                  bundle: this.name,
                  __outputAsArray__: Array.isArray(paths)
                };
                legacyCC.assetManager.loadAny(paths, options, onProg, onComp);
              };

              _proto.preload = function preload(paths, type, onProgress, onComplete) {
                var _parseLoadResArgs2 = parseLoadResArgs(type, onProgress, onComplete),
                    _type = _parseLoadResArgs2.type,
                    onProg = _parseLoadResArgs2.onProgress,
                    onComp = _parseLoadResArgs2.onComplete;

                legacyCC.assetManager.preloadAny(paths, {
                  __requestType__: RequestType.PATH,
                  type: _type,
                  bundle: this.name
                }, onProg, onComp);
              };

              _proto.loadDir = function loadDir(dir, type, onProgress, onComplete) {
                var _parseLoadResArgs3 = parseLoadResArgs(type, onProgress, onComplete),
                    _type = _parseLoadResArgs3.type,
                    onProg = _parseLoadResArgs3.onProgress,
                    onComp = _parseLoadResArgs3.onComplete;

                legacyCC.assetManager.loadAny(dir, {
                  __requestType__: RequestType.DIR,
                  type: _type,
                  bundle: this.name,
                  __outputAsArray__: true
                }, onProg, onComp);
              };

              _proto.preloadDir = function preloadDir(dir, type, onProgress, onComplete) {
                var _parseLoadResArgs4 = parseLoadResArgs(type, onProgress, onComplete),
                    _type = _parseLoadResArgs4.type,
                    onProg = _parseLoadResArgs4.onProgress,
                    onComp = _parseLoadResArgs4.onComplete;

                legacyCC.assetManager.preloadAny(dir, {
                  __requestType__: RequestType.DIR,
                  type: _type,
                  bundle: this.name
                }, onProg, onComp);
              };

              _proto.loadScene = function loadScene(sceneName, options, onProgress, onComplete) {
                var _parseParameters = parseParameters(options, onProgress, onComplete),
                    opts = _parseParameters.options,
                    onProg = _parseParameters.onProgress,
                    onComp = _parseParameters.onComplete;

                opts.preset = opts.preset || 'scene';
                opts.bundle = this.name;
                legacyCC.assetManager.loadAny({
                  scene: sceneName
                }, opts, onProg, function (err, sceneAsset) {
                  if (err) {
                    error(err.message, err.stack);
                  } else if (sceneAsset instanceof SceneAsset && sceneAsset.scene) {
                    var scene = sceneAsset.scene;
                    scene._id = sceneAsset._uuid;
                    scene.name = sceneAsset.name;
                  } else {
                    err = new Error("The asset " + sceneAsset._uuid + " is not a scene");
                  }

                  if (onComp) {
                    onComp(err, sceneAsset);
                  }
                });
              };

              _proto.preloadScene = function preloadScene(sceneName, options, onProgress, onComplete) {
                var _parseParameters2 = parseParameters(options, onProgress, onComplete),
                    opts = _parseParameters2.options,
                    onProg = _parseParameters2.onProgress,
                    onComp = _parseParameters2.onComplete;

                opts.bundle = this.name;
                legacyCC.assetManager.preloadAny({
                  scene: sceneName
                }, opts, onProg, function (err) {
                  if (err) {
                    errorID(1210, sceneName, err.message);
                  }

                  if (onComp) {
                    onComp(err);
                  }
                });
              };

              _proto.get = function get(path, type) {
                var info = this.getInfoWithPath(path, type);

                if (info) {
                  return assets.get(info.uuid) || null;
                }

                return null;
              };

              _proto.release = function release(path, type) {
                var asset = this.get(path, type);

                if (asset) {
                  releaseManager.tryRelease(asset, true);
                }
              };

              _proto.releaseUnusedAssets = function releaseUnusedAssets() {
                var _this = this;

                assets.forEach(function (asset) {
                  var info = _this.getAssetInfo(asset._uuid);

                  if (info && !info.redirect) {
                    releaseManager.tryRelease(asset);
                  }
                });
              };

              _proto.releaseAll = function releaseAll() {
                var _this2 = this;

                assets.forEach(function (asset) {
                  var info = _this2.getAssetInfo(asset._uuid);

                  if (info && !info.redirect) {
                    releaseManager.tryRelease(asset, true);
                  }
                });
              };

              _proto._destroy = function _destroy() {
                this._config.destroy();
              };

              _createClass(Bundle, [{
                key: "config",
                get: function get() {
                  return this._config;
                }
              }, {
                key: "name",
                get: function get() {
                  return this._config.name;
                }
              }, {
                key: "deps",
                get: function get() {
                  return this._config.deps;
                }
              }, {
                key: "base",
                get: function get() {
                  return this._config.base;
                }
              }]);

              return Bundle;
            }();
            var resources = exports('resources', new Bundle());
            legacyCC.resources = resources;

            function downloadDomImage(url, options, onComplete) {
              var img = new Image();

              if (window.location.protocol !== 'file:') {
                img.crossOrigin = 'anonymous';
              }

              function loadCallback() {
                img.removeEventListener('load', loadCallback);
                img.removeEventListener('error', errorCallback);

                if (onComplete) {
                  onComplete(null, img);
                }
              }

              function errorCallback() {
                img.removeEventListener('load', loadCallback);
                img.removeEventListener('error', errorCallback);

                if (onComplete) {
                  onComplete(new Error(getError(4930, url)));
                }
              }

              img.addEventListener('load', loadCallback);
              img.addEventListener('error', errorCallback);
              img.src = url;
              return img;
            }

            function downloadFile(url, options, onProgress, onComplete) {
              var xhr = new XMLHttpRequest();
              var errInfo = "download failed: " + url + ", status: ";
              xhr.open('GET', url, true);

              if (options.xhrResponseType !== undefined) {
                xhr.responseType = options.xhrResponseType;
              }

              if (options.xhrWithCredentials !== undefined) {
                xhr.withCredentials = options.xhrWithCredentials;
              }

              if (options.xhrMimeType !== undefined && xhr.overrideMimeType) {
                xhr.overrideMimeType(options.xhrMimeType);
              }

              if (options.xhrTimeout !== undefined) {
                xhr.timeout = options.xhrTimeout;
              }

              if (options.xhrHeader) {
                for (var header in options.xhrHeader) {
                  xhr.setRequestHeader(header, options.xhrHeader[header]);
                }
              }

              xhr.onload = function () {
                if (xhr.status === 200 || xhr.status === 0) {
                  if (onComplete) {
                    onComplete(null, xhr.response);
                  }
                } else if (onComplete) {
                  onComplete(new Error("" + errInfo + xhr.status + "(no response)"));
                }
              };

              if (onProgress) {
                xhr.onprogress = function (e) {
                  if (e.lengthComputable) {
                    onProgress(e.loaded, e.total);
                  }
                };
              }

              xhr.onerror = function () {
                if (onComplete) {
                  onComplete(new Error("" + errInfo + xhr.status + "(error)"));
                }
              };

              xhr.ontimeout = function () {
                if (onComplete) {
                  onComplete(new Error("" + errInfo + xhr.status + "(time out)"));
                }
              };

              xhr.onabort = function () {
                if (onComplete) {
                  onComplete(new Error("" + errInfo + xhr.status + "(abort)"));
                }
              };

              xhr.send(null);
              return xhr;
            }

            var downloaded = {};
            function downloadScript(url, options, onComplete) {
              if (downloaded[url]) {
                if (onComplete) {
                  onComplete(null);
                }

                return null;
              }

              var script = document.createElement('script');

              if (window.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);
              document.body.appendChild(script);
              return script;
            }

            var REGEX = /^(?:\w+:\/\/|\.+\/).+/;

            var downloadImage = function downloadImage(url, options, onComplete) {
              var func = sys.capabilities.imageBitmap && legacyCC.assetManager.allowImageBitmap ? downloadBlob : downloadDomImage;
              func(url, options, onComplete);
            };

            var downloadBlob = function downloadBlob(url, options, onComplete) {
              options.xhrResponseType = 'blob';
              downloadFile(url, options, options.onFileProgress, onComplete);
            };

            var downloadJson = function downloadJson(url, options, onComplete) {
              options.xhrResponseType = 'json';
              downloadFile(url, options, options.onFileProgress, onComplete);
            };

            var downloadArrayBuffer = function downloadArrayBuffer(url, options, onComplete) {
              options.xhrResponseType = 'arraybuffer';
              downloadFile(url, options, options.onFileProgress, onComplete);
            };

            var downloadText = function downloadText(url, options, onComplete) {
              options.xhrResponseType = 'text';
              downloadFile(url, options, options.onFileProgress, onComplete);
            };

            var downloadBundle = function downloadBundle(nameOrUrl, options, onComplete) {
              var bundleName = basename(nameOrUrl);
              var url = nameOrUrl;

              if (!REGEX.test(url)) {
                if (downloader.remoteBundles.indexOf(bundleName) !== -1) {
                  url = downloader.remoteServerAddress + "remote/" + bundleName;
                } else {
                  url = "assets/" + bundleName;
                }
              }

              var version = options.version || downloader.bundleVers[bundleName];
              var count = 0;
              var config = url + "/config." + (version ? version + "." : '') + "json";
              var out = null;
              var error = null;
              downloadJson(config, options, function (err, response) {
                error = err;
                out = response;

                if (out) {
                  out.base = url + "/";
                }

                if (++count === 2) {
                  onComplete(error, out);
                }
              });
              var jspath = url + "/index." + (version ? version + "." : '') + "js";
              downloadScript(jspath, options, function (err) {
                error = err;

                if (++count === 2) {
                  onComplete(err, out);
                }
              });
            };

            var Downloader = function () {
              function Downloader() {
                this.maxConcurrency = 6;
                this.maxRequestsPerFrame = 6;
                this.maxRetryCount =  3 ;
                this.appendTimeStamp = !!EDITOR;
                this.limited = !EDITOR;
                this.retryInterval = 2000;
                this.bundleVers = null;
                this.remoteBundles = [];
                this.downloadDomImage = downloadDomImage;
                this.downloadDomAudio = null;
                this.downloadFile = downloadFile;
                this.downloadScript = downloadScript;
                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,
                  '.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;
              }

              var _proto = Downloader.prototype;

              _proto.init = function init(remoteServerAddress, bundleVers, remoteBundles) {
                if (remoteServerAddress === void 0) {
                  remoteServerAddress = '';
                }

                if (bundleVers === void 0) {
                  bundleVers = {};
                }

                if (remoteBundles === void 0) {
                  remoteBundles = [];
                }

                this._downloading.clear();

                this._queue.length = 0;
                this._remoteServerAddress = remoteServerAddress;
                this.bundleVers = bundleVers;
                this.remoteBundles = remoteBundles;
              };

              _proto.register = function register(type, handler) {
                if (typeof type === 'object') {
                  mixin(this._downloaders, type);
                } else {
                  this._downloaders[type] = handler;
                }
              };

              _proto.download = function download(id, url, type, options, onComplete) {
                var _this = this;

                var file = files.get(id);

                if (file) {
                  onComplete(null, file);
                  return;
                }

                var downloadCallbacks = this._downloading.get(id);

                if (downloadCallbacks) {
                  downloadCallbacks.push(onComplete);

                  var request = this._queue.find(function (x) {
                    return x.id === id;
                  });

                  if (!request) {
                    return;
                  }

                  var priority = options.priority || 0;

                  if (request.priority < priority) {
                    request.priority = priority;
                    this._queueDirty = true;
                  }

                  return;
                }

                var maxRetryCount = typeof options.maxRetryCount !== 'undefined' ? options.maxRetryCount : this.maxRetryCount;
                var maxConcurrency = typeof options.maxConcurrency !== 'undefined' ? options.maxConcurrency : this.maxConcurrency;
                var maxRequestsPerFrame = typeof options.maxRequestsPerFrame !== 'undefined' ? options.maxRequestsPerFrame : this.maxRequestsPerFrame;
                var handler = this._downloaders[type] || this._downloaders["default"];

                var process = function process(index, callback) {
                  if (index === 0) {
                    _this._downloading.add(id, [onComplete]);
                  }

                  if (!_this.limited) {
                    handler(urlAppendTimestamp(url, _this.appendTimeStamp), options, callback);
                    return;
                  }

                  _this._updateTime();

                  var done = function done(err, data) {
                    _this._totalNum--;

                    _this._handleQueueInNextFrame(maxConcurrency, maxRequestsPerFrame);

                    callback(err, data);
                  };

                  if (_this._totalNum < maxConcurrency && _this._totalNumThisPeriod < maxRequestsPerFrame) {
                    handler(urlAppendTimestamp(url, _this.appendTimeStamp), options, done);
                    _this._totalNum++;
                    _this._totalNumThisPeriod++;
                  } else {
                    _this._queue.push({
                      id: id,
                      priority: options.priority || 0,
                      url: url,
                      options: options,
                      done: done,
                      handler: handler
                    });

                    _this._queueDirty = true;

                    if (_this._totalNum < maxConcurrency) {
                      _this._handleQueueInNextFrame(maxConcurrency, maxRequestsPerFrame);
                    }
                  }
                };

                var finale = function finale(err, result) {
                  if (!err) {
                    files.add(id, result);
                  }

                  var callbacks = _this._downloading.remove(id);

                  for (var i = 0, l = callbacks.length; i < l; i++) {
                    callbacks[i](err, result);
                  }
                };

                retry(process, maxRetryCount, this.retryInterval, finale);
              };

              _proto.loadSubpackage = function loadSubpackage(name, completeCallback) {
                legacyCC.assetManager.loadBundle(name, null, completeCallback);
              };

              _proto._updateTime = function _updateTime() {
                var now = Date.now();
                var deltaTime = legacyCC.director.getDeltaTime();
                var interval = deltaTime > this._maxInterval ? this._maxInterval : deltaTime;

                if (now - this._lastDate > interval * 1000) {
                  this._totalNumThisPeriod = 0;
                  this._lastDate = now;
                }
              };

              _proto._handleQueue = function _handleQueue(maxConcurrency, maxRequestsPerFrame) {
                this._checkNextPeriod = false;

                this._updateTime();

                while (this._queue.length > 0 && this._totalNum < maxConcurrency && this._totalNumThisPeriod < maxRequestsPerFrame) {
                  if (this._queueDirty) {
                    this._queue.sort(function (a, b) {
                      return a.priority - b.priority;
                    });

                    this._queueDirty = false;
                  }

                  var request = this._queue.pop();

                  if (!request) {
                    break;
                  }

                  this._totalNum++;
                  this._totalNumThisPeriod++;
                  request.handler(urlAppendTimestamp(request.url, this.appendTimeStamp), request.options, request.done);
                }

                this._handleQueueInNextFrame(maxConcurrency, maxRequestsPerFrame);
              };

              _proto._handleQueueInNextFrame = function _handleQueueInNextFrame(maxConcurrency, maxRequestsPerFrame) {
                if (!this._checkNextPeriod && this._queue.length > 0) {
                  callInNextTick(this._handleQueue.bind(this), maxConcurrency, maxRequestsPerFrame);
                  this._checkNextPeriod = true;
                }
              };

              _createClass(Downloader, [{
                key: "remoteServerAddress",
                get: function get() {
                  return this._remoteServerAddress;
                }
              }]);

              return Downloader;
            }();
            var downloader = new Downloader();

            function createImageAsset(id, data, options, onComplete) {
              var out = null;
              var err = null;

              try {
                out = new ImageAsset();
                out._nativeUrl = id;
                out._nativeAsset = data;
              } catch (e) {
                err = e;
              }

              onComplete(err, out);
            }

            function createJsonAsset(id, data, options, onComplete) {
              var out = new JsonAsset();
              out.json = data;
              onComplete(null, out);
            }

            function createTextAsset(id, data, options, onComplete) {
              var out = new TextAsset();
              out.text = data;
              onComplete(null, out);
            }

            function createBufferAsset(id, data, options, onComplete) {
              var out = new BufferAsset();
              out._nativeUrl = id;
              out._nativeAsset = data;
              onComplete(null, out);
            }

            function createAsset(id, data, options, onComplete) {
              var out = new Asset();
              out._nativeUrl = id;
              out._nativeAsset = data;
              onComplete(null, out);
            }

            function createBundle(id, data, options, onComplete) {
              var bundle = bundles.get(data.name);

              if (!bundle) {
                bundle = data.name === BuiltinBundleName.RESOURCES ? resources : new Bundle();
                data.base = data.base || id + "/";
                bundle.init(data);
              }

              module.import("virtual:///prerequisite-imports/" + bundle.name).then(function () {
                onComplete(null, bundle);
              })["catch"](onComplete);
            }

            var Factory = function () {
              function Factory() {
                this._creating = new Cache();
                this._producers = {
                  '.png': createImageAsset,
                  '.jpg': createImageAsset,
                  '.bmp': createImageAsset,
                  '.jpeg': createImageAsset,
                  '.gif': createImageAsset,
                  '.ico': createImageAsset,
                  '.tiff': createImageAsset,
                  '.webp': createImageAsset,
                  '.image': createImageAsset,
                  '.pvr': createImageAsset,
                  '.pkm': createImageAsset,
                  '.txt': createTextAsset,
                  '.xml': createTextAsset,
                  '.vsh': createTextAsset,
                  '.fsh': createTextAsset,
                  '.atlas': createTextAsset,
                  '.tmx': createTextAsset,
                  '.tsx': createTextAsset,
                  '.fnt': createTextAsset,
                  '.json': createJsonAsset,
                  '.ExportJson': createJsonAsset,
                  '.binary': createBufferAsset,
                  '.bin': createBufferAsset,
                  '.dbbin': createBufferAsset,
                  '.skel': createBufferAsset,
                  bundle: createBundle,
                  "default": createAsset
                };
              }

              var _proto = Factory.prototype;

              _proto.register = function register(type, handler) {
                if (typeof type === 'object') {
                  js.mixin(this._producers, type);
                } else {
                  this._producers[type] = handler;
                }
              };

              _proto.create = function create(id, data, type, options, onComplete) {
                var _this = this;

                var handler = this._producers[type] || this._producers["default"];
                var asset = assets.get(id);

                if (!options.reloadAsset && asset) {
                  onComplete(null, asset);
                  return;
                }

                var creating = this._creating.get(id);

                if (creating) {
                  creating.push(onComplete);
                  return;
                }

                this._creating.add(id, [onComplete]);

                handler(id, data, options, function (err, result) {
                  if (!err && result instanceof Asset) {
                    result._uuid = id;
                    cache(id, result, options.cacheAsset);
                  }

                  var callbacks = _this._creating.remove(id);

                  for (var i = 0, l = callbacks.length; i < l; i++) {
                    callbacks[i](err, result);
                  }
                });
              };

              return Factory;
            }();
            var factory = new Factory();

            var PackManager = function () {
              function PackManager() {
                this._loading = new Cache();
                this._unpackers = {
                  '.json': this.unpackJson
                };
              }

              var _proto = PackManager.prototype;

              _proto.unpackJson = function unpackJson(pack, json, options, onComplete) {
                var out = js.createMap(true);
                var err = null;

                if (Array.isArray(json)) {
                  json = unpackJSONs(json);

                  if (json.length !== pack.length) {
                    errorID(4915);
                  }

                  for (var i = 0; i < pack.length; i++) {
                    out[pack[i] + "@import"] = json[i];
                  }
                } else {
                  var textureType = js._getClassId(Texture2D);

                  var imageAssetType = js._getClassId(ImageAsset);

                  if (json.type === textureType && json.data) {
                    var datas = json.data;

                    if (datas.length !== pack.length) {
                      errorID(4915);
                    }

                    for (var _i = 0; _i < pack.length; _i++) {
                      out[pack[_i] + "@import"] = packCustomObjData(textureType, {
                        base: datas[_i][0],
                        mipmaps: datas[_i][1]
                      });
                    }
                  } else if (json.type === imageAssetType && json.data) {
                    var _datas = json.data;

                    if (_datas.length !== pack.length) {
                      errorID(4915);
                    }

                    for (var _i2 = 0; _i2 < pack.length; _i2++) {
                      out[pack[_i2] + "@import"] = _datas[_i2];
                    }
                  } else {
                    err = new Error('unmatched type pack!');
                    out = null;
                  }
                }

                onComplete(err, out);
              };

              _proto.init = function init() {
                this._loading.clear();
              };

              _proto.register = function register(type, handler) {
                if (typeof type === 'object') {
                  js.mixin(this._unpackers, type);
                } else {
                  this._unpackers[type] = handler;
                }
              };

              _proto.unpack = function unpack(pack, data, type, options, onComplete) {
                if (!data) {
                  onComplete(new Error('package data is wrong!'));
                  return;
                }

                var unpacker = this._unpackers[type];
                unpacker(pack, data, options, onComplete);
              };

              _proto.load = function load(item, options, onComplete) {
                var _this = this;

                if (item.isNative || !item.info || !item.info.packs) {
                  downloader.download(item.id, item.url, item.ext, item.options, onComplete);
                  return;
                }

                if (files.has(item.id)) {
                  onComplete(null, files.get(item.id));
                  return;
                }

                var packs = item.info.packs;
                var pack = packs.find(function (val) {
                  return _this._loading.has(val.uuid);
                });

                if (pack) {
                  this._loading.get(pack.uuid).push({
                    onComplete: onComplete,
                    id: item.id
                  });

                  return;
                }

                pack = packs[0];

                this._loading.add(pack.uuid, [{
                  onComplete: onComplete,
                  id: item.id
                }]);

                var url = transform(pack.uuid, {
                  ext: pack.ext,
                  bundle: item.config.name
                });
                downloader.download(pack.uuid, url, pack.ext, item.options, function (err, data) {
                  files.remove(pack.uuid);

                  if (err) {
                    error(err.message, err.stack);
                  }

                  _this.unpack(pack.packedUuids, data, pack.ext, item.options, function (err2, result) {
                    if (!err2) {
                      for (var id in result) {
                        files.add(id, result[id]);
                      }
                    }

                    var callbacks = _this._loading.remove(pack.uuid);

                    for (var i = 0, l = callbacks.length; i < l; i++) {
                      var cb = callbacks[i];

                      if (err || err2) {
                        cb.onComplete(err || err2);
                        continue;
                      }

                      var unpackedData = result[cb.id];

                      if (!unpackedData) {
                        cb.onComplete(new Error('can not retrieve data from package'));
                      } else {
                        cb.onComplete(null, unpackedData);
                      }
                    }
                  });
                });
              };

              return PackManager;
            }();
            var packManager = new PackManager();

            function fetch(task, done) {
              var firstTask = false;

              if (!task.progress) {
                task.progress = {
                  finish: 0,
                  total: task.input.length,
                  canInvoke: true
                };
                firstTask = true;
              }

              var options = task.options,
                  progress = task.progress;
              var depends = [];
              var total = progress.total;
              var exclude = options.__exclude__ = options.__exclude__ || Object.create(null);
              task.output = [];
              forEach(task.input, function (item, cb) {
                if (!item.isNative && assets.has(item.uuid)) {
                  var asset = assets.get(item.uuid);
                  item.content = asset.addRef();
                  task.output.push(item);

                  if (progress.canInvoke) {
                    task.dispatch('progress', ++progress.finish, progress.total, item);
                  }

                  cb();
                  return;
                }

                packManager.load(item, task.options, function (err, data) {
                  if (err) {
                    if (!task.isFinish) {
                      if (!legacyCC.assetManager.force || firstTask) {
                        error(err.message, err.stack);
                        progress.canInvoke = false;
                        done(err);
                      } else {
                        task.output.push(item);

                        if (progress.canInvoke) {
                          task.dispatch('progress', ++progress.finish, progress.total, item);
                        }
                      }
                    }
                  } else if (!task.isFinish) {
                    item.file = data;
                    task.output.push(item);

                    if (!item.isNative) {
                      exclude[item.uuid] = true;
                      getDepends(item.uuid, data, exclude, depends, item.config);
                      progress.total = total + depends.length;
                    }

                    if (progress.canInvoke) {
                      task.dispatch('progress', ++progress.finish, progress.total, item);
                    }
                  }

                  cb();
                });
              }, function () {
                if (task.isFinish) {
                  clear$1(task, true);
                  task.dispatch('error');
                  return;
                }

                if (depends.length > 0) {
                  var subTask = Task.create({
                    input: depends,
                    progress: progress,
                    options: options,
                    onProgress: task.onProgress,
                    onError: Task.prototype.recycle,
                    onComplete: function onComplete(err) {
                      if (!err) {
                        var _task$output;

                        (_task$output = task.output).push.apply(_task$output, subTask.output);

                        subTask.recycle();
                      }

                      if (firstTask) {
                        decreaseRef(task);
                      }

                      done(err);
                    }
                  });
                  fetchPipeline.async(subTask);
                  return;
                }

                if (firstTask) {
                  decreaseRef(task);
                }

                done();
              });
            }

            function decreaseRef(task) {
              var output = task.output;

              for (var i = 0, l = output.length; i < l; i++) {
                if (output[i].content) {
                  output[i].content.decRef(false);
                }
              }
            }

            var SAXParser = function () {
              function SAXParser() {
                this._parser = null;

                if (window.DOMParser) {
                  this._parser = new DOMParser();
                }
              }

              var _proto = SAXParser.prototype;

              _proto.parse = function parse(xmlTxt) {
                return this._parseXML(xmlTxt);
              };

              _proto._parseXML = function _parseXML(textxml) {
                if (this._parser) {
                  return this._parser.parseFromString(textxml, 'text/xml');
                }

                throw new Error('Dom parser is not supported in this platform!');
              };

              return SAXParser;
            }();

            var PlistParser = function (_SAXParser) {
              _inheritsLoose(PlistParser, _SAXParser);

              function PlistParser() {
                return _SAXParser.apply(this, arguments) || this;
              }

              var _proto2 = PlistParser.prototype;

              _proto2.parse = function parse(xmlTxt) {
                var xmlDoc = this._parseXML(xmlTxt);

                var plist = xmlDoc.documentElement;

                if (plist.tagName !== 'plist') {
                  warnID(5100);
                  return {};
                }

                var node = null;

                for (var i = 0, len = plist.childNodes.length; i < len; i++) {
                  node = plist.childNodes[i];

                  if (node.nodeType === 1) {
                    break;
                  }
                }

                return this._parseNode(node);
              };

              _proto2._parseNode = function _parseNode(node) {
                var data = null;
                var tagName = node.tagName;

                if (tagName === 'dict') {
                  data = this._parseDict(node);
                } else if (tagName === 'array') {
                  data = this._parseArray(node);
                } else if (tagName === 'string') {
                  if (node.childNodes.length === 1) {
                    data = node.firstChild.nodeValue;
                  } else {
                    data = '';

                    for (var i = 0; i < node.childNodes.length; i++) {
                      data += node.childNodes[i].nodeValue;
                    }
                  }
                } else if (tagName === 'false') {
                  data = false;
                } else if (tagName === 'true') {
                  data = true;
                } else if (tagName === 'real') {
                  data = parseFloat(node.firstChild.nodeValue);
                } else if (tagName === 'integer') {
                  data = parseInt(node.firstChild.nodeValue, 10);
                }

                return data;
              };

              _proto2._parseArray = function _parseArray(node) {
                var data = [];

                for (var i = 0, len = node.childNodes.length; i < len; i++) {
                  var child = node.childNodes[i];

                  if (child.nodeType !== 1) {
                    continue;
                  }

                  data.push(this._parseNode(child));
                }

                return data;
              };

              _proto2._parseDict = function _parseDict(node) {
                var data = {};
                var key = '';

                for (var i = 0, len = node.childNodes.length; i < len; i++) {
                  var child = node.childNodes[i];

                  if (child.nodeType !== 1) {
                    continue;
                  }

                  if (child.tagName === 'key') {
                    key = child.firstChild.nodeValue;
                  } else {
                    data[key] = this._parseNode(child);
                  }
                }

                return data;
              };

              return PlistParser;
            }(SAXParser);

            var plistParser = new PlistParser();

            var PVR_HEADER_LENGTH = 13;
            var PVR_MAGIC = 0x03525650;
            var PVR_HEADER_MAGIC = 0;
            var PVR_HEADER_HEIGHT = 6;
            var PVR_HEADER_WIDTH = 7;
            var PVR_HEADER_METADATA = 12;
            var ETC_PKM_HEADER_SIZE = 16;
            var ETC_PKM_FORMAT_OFFSET = 6;
            var ETC_PKM_ENCODED_WIDTH_OFFSET = 8;
            var ETC_PKM_ENCODED_HEIGHT_OFFSET = 10;
            var ETC_PKM_WIDTH_OFFSET = 12;
            var ETC_PKM_HEIGHT_OFFSET = 14;
            var ETC1_RGB_NO_MIPMAPS = 0;
            var ETC2_RGB_NO_MIPMAPS = 1;
            var ETC2_RGBA_NO_MIPMAPS = 3;
            var ASTC_MAGIC = 0x5CA1AB13;
            var ASTC_HEADER_LENGTH = 16;
            var ASTC_HEADER_MAGIC = 4;
            var ASTC_HEADER_SIZE_X_BEGIN = 7;
            var ASTC_HEADER_SIZE_Y_BEGIN = 10;
            var ASTC_HEADER_SIZE_Z_BEGIN = 13;

            function getASTCFormat(xdim, ydim) {
              if (xdim === 4) {
                return PixelFormat.RGBA_ASTC_4x4;
              }

              if (xdim === 5) {
                if (ydim === 4) {
                  return PixelFormat.RGBA_ASTC_5x4;
                }

                return PixelFormat.RGBA_ASTC_5x5;
              }

              if (xdim === 6) {
                if (ydim === 5) {
                  return PixelFormat.RGBA_ASTC_6x5;
                }

                return PixelFormat.RGBA_ASTC_6x6;
              }

              if (xdim === 8) {
                if (ydim === 5) {
                  return PixelFormat.RGBA_ASTC_8x5;
                }

                if (ydim === 6) {
                  return PixelFormat.RGBA_ASTC_8x6;
                }

                return PixelFormat.RGBA_ASTC_8x8;
              }

              if (xdim === 10) {
                if (ydim === 5) {
                  return PixelFormat.RGBA_ASTC_10x5;
                }

                if (ydim === 6) {
                  return PixelFormat.RGBA_ASTC_10x6;
                }

                if (ydim === 8) {
                  return PixelFormat.RGBA_ASTC_10x8;
                }

                return PixelFormat.RGBA_ASTC_10x10;
              }

              if (ydim === 10) {
                return PixelFormat.RGBA_ASTC_12x10;
              }

              return PixelFormat.RGBA_ASTC_12x12;
            }

            function readBEUint16(header, offset) {
              return header[offset] << 8 | header[offset + 1];
            }

            var Parser$1 = function () {
              function Parser() {
                this._parsing = new Cache();
                this._parsers = {
                  '.png': this.parseImage,
                  '.jpg': this.parseImage,
                  '.bmp': this.parseImage,
                  '.jpeg': this.parseImage,
                  '.gif': this.parseImage,
                  '.ico': this.parseImage,
                  '.tiff': this.parseImage,
                  '.webp': this.parseImage,
                  '.image': this.parseImage,
                  '.pvr': this.parsePVRTex,
                  '.pkm': this.parsePKMTex,
                  '.astc': this.parseASTCTex,
                  '.mp3': this.parseAudio,
                  '.ogg': this.parseAudio,
                  '.wav': this.parseAudio,
                  '.m4a': this.parseAudio,
                  '.plist': this.parsePlist,
                  "import": this.parseImport
                };
              }

              var _proto = Parser.prototype;

              _proto.parseImage = function parseImage(file, options, onComplete) {
                if (file instanceof HTMLImageElement) {
                  onComplete(null, file);
                  return;
                }

                createImageBitmap(file, {
                  premultiplyAlpha: 'none'
                }).then(function (result) {
                  onComplete(null, result);
                }, function (err) {
                  onComplete(err, null);
                });
              };

              _proto.parseAudio = function parseAudio(file, options, onComplete) {
                if (file instanceof ArrayBuffer) {
                  sys.__audioSupport.context.decodeAudioData(file, function (buffer) {
                    onComplete(null, buffer);
                  }, function (e) {
                    onComplete(new Error("Error with decoding audio data" + e.err), null);
                  });
                } else {
                  onComplete(null, file);
                }
              };

              _proto.parsePVRTex = function parsePVRTex(file, options, onComplete) {
                var err = null;
                var out = null;

                try {
                  var buffer = file instanceof ArrayBuffer ? file : file.buffer;
                  var header = new Int32Array(buffer, 0, PVR_HEADER_LENGTH);

                  if (header[PVR_HEADER_MAGIC] === PVR_MAGIC) {
                    var width = header[PVR_HEADER_WIDTH];
                    var height = header[PVR_HEADER_HEIGHT];
                    var dataOffset = header[PVR_HEADER_METADATA] + 52;
                    var pvrtcData = new Uint8Array(buffer, dataOffset);
                    out = {
                      _data: pvrtcData,
                      _compressed: true,
                      width: width,
                      height: height,
                      format: 0
                    };
                  } else if (header[11] === 0x21525650) {
                    var headerLength = header[0];
                    var _height = header[1];
                    var _width = header[2];

                    var _pvrtcData = new Uint8Array(buffer, headerLength);

                    out = {
                      _data: _pvrtcData,
                      _compressed: true,
                      width: _width,
                      height: _height,
                      format: 0
                    };
                  } else {
                    throw new Error('Invalid magic number in PVR header');
                  }
                } catch (e) {
                  err = e;
                }

                onComplete(err, out);
              };

              _proto.parsePKMTex = function parsePKMTex(file, options, onComplete) {
                var err = null;
                var out = null;

                try {
                  var buffer = file instanceof ArrayBuffer ? file : file.buffer;
                  var header = new Uint8Array(buffer);
                  var format = readBEUint16(header, ETC_PKM_FORMAT_OFFSET);

                  if (format !== ETC1_RGB_NO_MIPMAPS && format !== ETC2_RGB_NO_MIPMAPS && format !== ETC2_RGBA_NO_MIPMAPS) {
                    throw new Error('Invalid magic number in ETC header');
                  }

                  var width = readBEUint16(header, ETC_PKM_WIDTH_OFFSET);
                  var height = readBEUint16(header, ETC_PKM_HEIGHT_OFFSET);
                  var encodedWidth = readBEUint16(header, ETC_PKM_ENCODED_WIDTH_OFFSET);
                  var encodedHeight = readBEUint16(header, ETC_PKM_ENCODED_HEIGHT_OFFSET);
                  var etcData = new Uint8Array(buffer, ETC_PKM_HEADER_SIZE);
                  out = {
                    _data: etcData,
                    _compressed: true,
                    width: width,
                    height: height,
                    format: 0
                  };
                } catch (e) {
                  err = e;
                }

                onComplete(err, out);
              };

              _proto.parseASTCTex = function parseASTCTex(file, options, onComplete) {
                var err = null;
                var out = null;

                try {
                  var buffer = file instanceof ArrayBuffer ? file : file.buffer;
                  var header = new Uint8Array(buffer);
                  var magicval = header[0] + (header[1] << 8) + (header[2] << 16) + (header[3] << 24);

                  if (magicval !== ASTC_MAGIC) {
                    throw new Error('Invalid magic number in ASTC header');
                  }

                  var xdim = header[ASTC_HEADER_MAGIC];
                  var ydim = header[ASTC_HEADER_MAGIC + 1];
                  var zdim = header[ASTC_HEADER_MAGIC + 2];

                  if ((xdim < 3 || xdim > 6 || ydim < 3 || ydim > 6 || zdim < 3 || zdim > 6) && (xdim < 4 || xdim === 7 || xdim === 9 || xdim === 11 || xdim > 12 || ydim < 4 || ydim === 7 || ydim === 9 || ydim === 11 || ydim > 12 || zdim !== 1)) {
                    throw new Error('Invalid block number in ASTC header');
                  }

                  var format = getASTCFormat(xdim, ydim);
                  var xsize = header[ASTC_HEADER_SIZE_X_BEGIN] + (header[ASTC_HEADER_SIZE_X_BEGIN + 1] << 8) + (header[ASTC_HEADER_SIZE_X_BEGIN + 2] << 16);
                  var ysize = header[ASTC_HEADER_SIZE_Y_BEGIN] + (header[ASTC_HEADER_SIZE_Y_BEGIN + 1] << 8) + (header[ASTC_HEADER_SIZE_Y_BEGIN + 2] << 16);
                  var zsize = header[ASTC_HEADER_SIZE_Z_BEGIN] + (header[ASTC_HEADER_SIZE_Z_BEGIN + 1] << 8) + (header[ASTC_HEADER_SIZE_Z_BEGIN + 2] << 16);
                  var astcData = new Uint8Array(buffer, ASTC_HEADER_LENGTH);
                  out = {
                    _data: astcData,
                    _compressed: true,
                    width: xsize,
                    height: ysize,
                    format: format
                  };
                } catch (e) {
                  err = e;
                }

                onComplete(err, out);
              };

              _proto.parsePlist = function parsePlist(file, options, onComplete) {
                var err = null;
                var result = plistParser.parse(file);

                if (!result) {
                  err = new Error('parse failed');
                }

                onComplete(err, result);
              };

              _proto.parseImport = function parseImport(file, options, onComplete) {
                if (!file) {
                  onComplete(new Error("The json file of asset " + options.__uuid__ + " is empty or missing"));
                  return;
                }

                var result = null;
                var err = null;

                try {
                  result = deserialize$1(file, options);
                } catch (e) {
                  err = e;
                }

                onComplete(err, result);
              };

              _proto.init = function init() {
                this._parsing.clear();
              };

              _proto.register = function register(type, handler) {
                if (typeof type === 'object') {
                  mixin(this._parsers, type);
                } else {
                  this._parsers[type] = handler;
                }
              };

              _proto.parse = function parse(id, file, type, options, onComplete) {
                var _this = this;

                var parsedAsset = parsed.get(id);

                if (parsedAsset) {
                  onComplete(null, parsedAsset);
                  return;
                }

                var parsing = this._parsing.get(id);

                if (parsing) {
                  parsing.push(onComplete);
                  return;
                }

                var parseHandler = this._parsers[type];

                if (!parseHandler) {
                  onComplete(null, file);
                  return;
                }

                this._parsing.add(id, [onComplete]);

                parseHandler(file, options, function (err, data) {
                  if (err) {
                    files.remove(id);
                  } else if (!isScene(data)) {
                    parsed.add(id, data);
                  }

                  var callbacks = _this._parsing.remove(id);

                  for (var i = 0, l = callbacks.length; i < l; i++) {
                    callbacks[i](err, data);
                  }
                });
              };

              return Parser;
            }();
            var parser = new Parser$1();

            function load(task, done) {
              var firstTask = false;

              if (!task.progress) {
                task.progress = {
                  finish: 0,
                  total: task.input.length,
                  canInvoke: true
                };
                firstTask = true;
              }

              var options = task.options,
                  progress = task.progress;
              options.__exclude__ = options.__exclude__ || Object.create(null);
              task.output = [];
              forEach(task.input, function (item, cb) {
                var subTask = Task.create({
                  input: item,
                  onProgress: task.onProgress,
                  options: options,
                  progress: progress,
                  onComplete: function onComplete(err, result) {
                    if (err && !task.isFinish) {
                      if (!legacyCC.assetManager.force || firstTask) {
                        {
                          error(err.message, err.stack);
                        }

                        progress.canInvoke = false;
                        done(err);
                      } else if (progress.canInvoke) {
                        task.dispatch('progress', ++progress.finish, progress.total, item);
                      }
                    }

                    task.output.push(result);
                    subTask.recycle();
                    cb(null);
                  }
                });
                loadOneAssetPipeline.async(subTask);
              }, function () {
                options.__exclude__ = null;

                if (task.isFinish) {
                  clear$1(task, true);
                  task.dispatch('error');
                  return;
                }

                gatherAsset(task);
                clear$1(task, true);
                done();
              });
            }
            var loadOneAssetPipeline = new Pipeline('loadOneAsset', [function fetch(task, done) {
              var item = task.output = task.input;
              var options = item.options,
                  isNative = item.isNative,
                  uuid = item.uuid,
                  file = item.file;
              var reloadAsset = options.reloadAsset;

              if (file || !reloadAsset && !isNative && assets.has(uuid)) {
                done();
                return;
              }

              packManager.load(item, task.options, function (err, data) {
                item.file = data;
                done(err);
              });
            }, function parse(task, done) {
              var item = task.output = task.input;
              var progress = task.progress;
              var exclude = task.options.__exclude__;
              var id = item.id,
                  file = item.file,
                  options = item.options;

              if (item.isNative) {
                parser.parse(id, file, item.ext, options, function (err, asset) {
                  if (err) {
                    done(err);
                    return;
                  }

                  item.content = asset;

                  if (progress.canInvoke) {
                    task.dispatch('progress', ++progress.finish, progress.total, item);
                  }

                  files.remove(id);
                  parsed.remove(id);
                  done();
                });
              } else {
                var uuid = item.uuid;

                if (uuid in exclude) {
                  var _exclude$uuid = exclude[uuid],
                      finish = _exclude$uuid.finish,
                      content = _exclude$uuid.content,
                      err = _exclude$uuid.err,
                      callbacks = _exclude$uuid.callbacks;

                  if (progress.canInvoke) {
                    task.dispatch('progress', ++progress.finish, progress.total, item);
                  }

                  if (finish || checkCircleReference(uuid, uuid, exclude)) {
                    if (content) {
                      content.addRef();
                    }

                    item.content = content;
                    done(err);
                  } else {
                    callbacks.push({
                      done: done,
                      item: item
                    });
                  }
                } else if (!options.reloadAsset && assets.has(uuid)) {
                  var asset = assets.get(uuid);
                  item.content = asset.addRef();

                  if (progress.canInvoke) {
                    task.dispatch('progress', ++progress.finish, progress.total, item);
                  }

                  done();
                } else {
                  options.__uuid__ = uuid;
                  parser.parse(id, file, 'import', options, function (err, asset) {
                    if (err) {
                      done(err);
                      return;
                    }

                    loadDepends(task, asset, done);
                  });
                }
              }
            }]);

            function loadDepends(task, asset, done) {
              var item = task.input,
                  progress = task.progress;
              var _ref = item,
                  uuid = _ref.uuid,
                  id = _ref.id,
                  options = _ref.options,
                  config = _ref.config;
              var cacheAsset = options.cacheAsset;
              var depends = [];

              if (asset.addRef) {
                asset.addRef();
              }

              getDepends(uuid, asset, Object.create(null), depends, config);

              if (progress.canInvoke) {
                task.dispatch('progress', ++progress.finish, progress.total += depends.length, item);
              }

              var repeatItem = task.options.__exclude__[uuid] = {
                content: asset,
                finish: false,
                callbacks: [{
                  done: done,
                  item: item
                }]
              };
              var subTask = Task.create({
                input: depends,
                options: task.options,
                onProgress: task.onProgress,
                onError: Task.prototype.recycle,
                progress: progress,
                onComplete: function onComplete(err) {
                  if (asset.decRef) {
                    asset.decRef(false);
                  }

                  repeatItem.finish = true;
                  repeatItem.err = err;

                  if (!err) {
                    var output = Array.isArray(subTask.output) ? subTask.output : [subTask.output];
                    var map = Object.create(null);

                    for (var _iterator = _createForOfIteratorHelperLoose(output), _step; !(_step = _iterator()).done;) {
                      var dependAsset = _step.value;

                      if (!dependAsset) {
                        continue;
                      }

                      map[dependAsset instanceof Asset ? dependAsset._uuid + "@import" : uuid + "@native"] = dependAsset;
                    }

                    setProperties(uuid, asset, map);

                    try {
                      if (typeof asset.onLoaded === 'function' && !asset.__onLoadedInvoked__ && !asset.__nativeDepend__) {
                        asset.onLoaded();
                        asset.__onLoadedInvoked__ = true;
                      }
                    } catch (e) {
                      error("The asset " + uuid + " is invalid for some reason, detail message: " + e.message + ", stack: " + e.stack);
                    }

                    files.remove(id);
                    parsed.remove(id);

                    cache(uuid, asset, cacheAsset);
                    subTask.recycle();
                  }

                  var callbacks = repeatItem.callbacks;

                  for (var i = 0, l = callbacks.length; i < l; i++) {
                    var cb = callbacks[i];

                    if (asset.addRef) {
                      asset.addRef();
                    }

                    cb.item.content = asset;
                    cb.done(err);
                  }

                  callbacks.length = 0;
                }
              });
              pipeline.async(subTask);
            }

            function preprocess(task, done) {
              var options = task.options;
              var subOptions = Object.create(null);
              var leftOptions = Object.create(null);

              for (var op in options) {
                switch (op) {
                  case RequestType.PATH:
                  case RequestType.UUID:
                  case RequestType.DIR:
                  case RequestType.SCENE:
                  case RequestType.URL:
                    break;

                  case '__requestType__':
                  case '__isNative__':
                  case 'ext':
                  case 'type':
                  case '__nativeName__':
                  case 'audioLoadMode':
                  case 'bundle':
                    subOptions[op] = options[op];
                    break;

                  case '__exclude__':
                  case '__outputAsArray__':
                    leftOptions[op] = options[op];
                    break;

                  default:
                    subOptions[op] = options[op];
                    leftOptions[op] = options[op];
                    break;
                }
              }

              task.options = leftOptions;
              var subTask = Task.create({
                input: task.input,
                options: subOptions
              });
              var err = null;

              try {
                task.output = task.source = transformPipeline.sync(subTask);
              } catch (e) {
                err = e;

                for (var i = 0, l = subTask.output.length; i < l; i++) {
                  subTask.output[i].recycle();
                }
              }

              subTask.recycle();
              done(err);
            }

            var RequestItem = function () {
              function RequestItem() {
                this.uuid = '';
                this.url = '';
                this.ext = '.json';
                this.content = null;
                this.file = null;
                this.info = null;
                this.config = null;
                this.isNative = false;
                this.options = Object.create(null);
                this._id = '';
              }

              RequestItem.create = function create() {
                var out;

                if (RequestItem._deadPool.length !== 0) {
                  out = RequestItem._deadPool.pop();
                } else {
                  out = new RequestItem();
                }

                return out;
              };

              var _proto = RequestItem.prototype;

              _proto.recycle = function recycle() {
                if (RequestItem._deadPool.length === RequestItem.MAX_DEAD_NUM) {
                  return;
                }

                this._id = '';
                this.uuid = '';
                this.url = '';
                this.ext = '.json';
                this.content = null;
                this.file = null;
                this.info = null;
                this.config = null;
                this.isNative = false;
                this.options = Object.create(null);

                RequestItem._deadPool.push(this);
              };

              _createClass(RequestItem, [{
                key: "id",
                get: function get() {
                  if (!this._id) {
                    this._id = this.uuid + "@" + (this.isNative ? 'native' : 'import');
                  }

                  return this._id;
                }
              }]);

              return RequestItem;
            }();

            RequestItem.MAX_DEAD_NUM = 500;
            RequestItem._deadPool = [];

            var infos = [];
            function parse(task) {
              var options = task.options;
              var input = Array.isArray(task.input) ? task.input : [task.input];
              task.output = [];

              var _loop = function _loop(i) {
                var item = input[i];
                var out = RequestItem.create();
                var config = null;
                var info = null;

                if (typeof item === 'string') {
                  item = Object.create(null);
                  item[options.__requestType__ || RequestType.UUID] = input[i];
                }

                if (typeof item === 'object') {
                  addon(item, options);

                  if (item.preset) {
                    addon(item, presets[item.preset]);
                  }

                  for (var key in item) {
                    switch (key) {
                      case RequestType.UUID:
                        {
                          var _ret2 = function () {
                            var uuid = out.uuid = decodeUuid(item.uuid);

                            if (!item.bundle) {
                              var bundle = bundles.find(function (bundle) {
                                return !!bundle.getAssetInfo(uuid);
                              });
                              item.bundle = bundle && bundle.name;
                            }

                            if (bundles.has(item.bundle)) {
                              config = bundles.get(item.bundle).config;
                              info = config.getAssetInfo(uuid);

                              if (info && info.redirect) {
                                if (!bundles.has(info.redirect)) {
                                  throw new Error("Please load bundle " + info.redirect + " first");
                                }

                                config = bundles.get(info.redirect).config;
                                info = config.getAssetInfo(uuid);
                              }

                              out.config = config;
                              out.info = info;
                            }

                            out.ext = item.ext || '.json';
                            return "break";
                          }();

                          if (_ret2 === "break") break;
                        }

                      case '__requestType__':
                      case 'ext':
                      case 'bundle':
                      case 'preset':
                      case 'type':
                        break;

                      case RequestType.DIR:
                        if (bundles.has(item.bundle)) {
                          bundles.get(item.bundle).config.getDirWithPath(item.dir, item.type, infos);

                          for (var _iterator = _createForOfIteratorHelperLoose(infos), _step; !(_step = _iterator()).done;) {
                            var assetInfo = _step.value;
                            input.push({
                              uuid: assetInfo.uuid,
                              __isNative__: false,
                              ext: '.json',
                              bundle: item.bundle
                            });
                          }

                          infos.length = 0;
                        }

                        out.recycle();
                        out = null;
                        break;

                      case RequestType.PATH:
                        if (bundles.has(item.bundle)) {
                          config = bundles.get(item.bundle).config;
                          info = config.getInfoWithPath(item.path, item.type);

                          if (info && info.redirect) {
                            if (!bundles.has(info.redirect)) {
                              throw new Error("you need to load bundle " + info.redirect + " first");
                            }

                            config = bundles.get(info.redirect).config;
                            info = config.getAssetInfo(info.uuid);
                          }

                          if (!info) {
                            out.recycle();
                            throw new Error("Bundle " + item.bundle + " doesn't contain " + item.path);
                          }

                          out.config = config;
                          out.uuid = info.uuid;
                          out.info = info;
                        }

                        out.ext = item.ext || '.json';
                        break;

                      case RequestType.SCENE:
                        if (!item.bundle) {
                          var bundle = bundles.find(function (bundle) {
                            return !!bundle.getSceneInfo(item.scene);
                          });
                          item.bundle = bundle && bundle.name;
                        }

                        if (bundles.has(item.bundle)) {
                          config = bundles.get(item.bundle).config;
                          info = config.getSceneInfo(item.scene);

                          if (info && info.redirect) {
                            if (!bundles.has(info.redirect)) {
                              throw new Error("you need to load bundle " + info.redirect + " first");
                            }

                            config = bundles.get(info.redirect).config;
                            info = config.getAssetInfo(info.uuid);
                          }

                          if (!info) {
                            out.recycle();
                            throw new Error("Bundle " + config.name + " doesn't contain scene " + item.scene);
                          }

                          out.config = config;
                          out.uuid = info.uuid;
                          out.info = info;
                        }

                        break;

                      case '__isNative__':
                        out.isNative = item.__isNative__;
                        break;

                      case RequestType.URL:
                        out.url = item.url;
                        out.uuid = item.uuid || item.url;
                        out.ext = item.ext || extname(item.url);
                        out.isNative = item.__isNative__ !== undefined ? item.__isNative__ : true;
                        break;

                      default:
                        out.options[key] = item[key];
                    }

                    if (!out) {
                      break;
                    }
                  }
                }

                if (!out) {
                  return "continue";
                }

                task.output.push(out);

                if (!out.uuid && !out.url) {
                  throw new Error("Can not parse this input:" + JSON.stringify(item));
                }
              };

              for (var i = 0; i < input.length; i++) {
                var _ret = _loop(i);

                if (_ret === "continue") continue;
              }

              return null;
            }
            function combine(task) {
              var input = task.output = task.input;

              for (var i = 0; i < input.length; i++) {
                var item = input[i];

                if (item.url) {
                  continue;
                }

                var url = '';
                var base = '';
                var config = item.config;

                if (item.isNative) {
                  base = config && config.nativeBase ? config.base + config.nativeBase : legacyCC.assetManager.generalNativeBase;
                } else {
                  base = config && config.importBase ? config.base + config.importBase : legacyCC.assetManager.generalImportBase;
                }

                var uuid = item.uuid;
                var ver = '';

                if (item.info) {
                  if (item.isNative) {
                    ver = item.info.nativeVer ? "." + item.info.nativeVer : '';
                  } else {
                    ver = item.info.ver ? "." + item.info.ver : '';
                  }
                }

                if (item.ext === '.ttf') {
                  url = base + "/" + uuid.slice(0, 2) + "/" + uuid + ver + "/" + item.options.__nativeName__;
                } else {
                  url = base + "/" + uuid.slice(0, 2) + "/" + uuid + ver + item.ext;
                }

                item.url = url;
              }

              return null;
            }

            var AssetManager = exports('AssetManager', function () {
              function AssetManager() {
                this.pipeline = pipeline.append(preprocess).append(load);
                this.fetchPipeline = fetchPipeline.append(preprocess).append(fetch);
                this.transformPipeline = transformPipeline.append(parse).append(combine);
                this.bundles = bundles;
                this.assets = assets;
                this.generalImportBase = '';
                this.generalNativeBase = '';
                this.dependUtil = dependUtil;
                this.force =  PREVIEW;
                this.allowImageBitmap = !sys.isMobile;
                this.utils = helper;
                this.downloader = downloader;
                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 ;
              }

              var _proto = AssetManager.prototype;

              _proto.init = function init(options) {
                if (options === void 0) {
                  options = {};
                }

                this._files.clear();

                this._parsed.clear();

                this._releaseManager.init();

                this.assets.clear();
                this.bundles.clear();
                this.packManager.init();
                this.downloader.init(options.server, options.bundleVers, options.remoteBundles);
                this.parser.init();
                this.dependUtil.init();
                var importBase = options.importBase || '';

                if (importBase && importBase.endsWith('/')) {
                  importBase = importBase.substr(0, importBase.length - 1);
                }

                var nativeBase = options.nativeBase || '';

                if (nativeBase && nativeBase.endsWith('/')) {
                  nativeBase = nativeBase.substr(0, nativeBase.length - 1);
                }

                this.generalImportBase = importBase;
                this.generalNativeBase = nativeBase;
              };

              _proto.getBundle = function getBundle(name) {
                return bundles.get(name) || null;
              };

              _proto.removeBundle = function removeBundle(bundle) {
                bundle._destroy();

                bundles.remove(bundle.name);
              };

              _proto.loadAny = function loadAny(requests, options, onProgress, onComplete) {
                var _parseParameters = parseParameters(options, onProgress, onComplete),
                    opts = _parseParameters.options,
                    onProg = _parseParameters.onProgress,
                    onComp = _parseParameters.onComplete;

                opts.preset = opts.preset || 'default';
                requests = Array.isArray(requests) ? requests.slice() : requests;
                var task = Task.create({
                  input: requests,
                  onProgress: onProg,
                  onComplete: asyncify(onComp),
                  options: opts
                });
                pipeline.async(task);
              };

              _proto.preloadAny = function preloadAny(requests, options, onProgress, onComplete) {
                var _parseParameters2 = parseParameters(options, onProgress, onComplete),
                    opts = _parseParameters2.options,
                    onProg = _parseParameters2.onProgress,
                    onComp = _parseParameters2.onComplete;

                opts.preset = opts.preset || 'preload';
                requests = Array.isArray(requests) ? requests.slice() : requests;
                var task = Task.create({
                  input: requests,
                  onProgress: onProg,
                  onComplete: asyncify(onComp),
                  options: opts
                });
                fetchPipeline.async(task);
              };

              _proto.postLoadNative = function postLoadNative(asset, options, onComplete) {
                var _parseParameters3 = parseParameters(options, undefined, onComplete),
                    opts = _parseParameters3.options,
                    onComp = _parseParameters3.onComplete;

                if (!asset._native || !asset.__nativeDepend__) {
                  asyncify(onComp)(null);
                  return;
                }

                var depend = dependUtil.getNativeDep(asset._uuid);

                if (!depend) {
                  return;
                }

                if (!bundles.has(depend.bundle)) {
                  var bundle = bundles.find(function (b) {
                    return !!b.getAssetInfo(asset._uuid);
                  });

                  if (bundle) {
                    depend.bundle = bundle.name;
                  }
                }

                this.loadAny(depend, opts, function (err, _native) {
                  if (!err) {
                    if (asset.isValid && asset.__nativeDepend__) {
                      asset._nativeAsset = _native;
                      asset.__nativeDepend__ = false;
                    }
                  } else {
                    error(err.message, err.stack);
                  }

                  if (onComp) {
                    onComp(err);
                  }
                });
              };

              _proto.loadRemote = function loadRemote(url, options, onComplete) {
                var _parseParameters4 = parseParameters(options, undefined, onComplete),
                    opts = _parseParameters4.options,
                    onComp = _parseParameters4.onComplete;

                if (!opts.reloadAsset && this.assets.has(url)) {
                  asyncify(onComp)(null, this.assets.get(url));
                  return;
                }

                opts.__isNative__ = true;
                opts.preset = opts.preset || 'remote';
                this.loadAny({
                  url: url
                }, opts, null, function (err, data) {
                  if (err) {
                    error(err.message, err.stack);

                    if (onComp) {
                      onComp(err, data);
                    }
                  } else {
                    factory.create(url, data, opts.ext || extname(url), opts, function (p1, p2) {
                      if (onComp) {
                        onComp(p1, p2);
                      }
                    });
                  }
                });
              };

              _proto.loadBundle = function loadBundle(nameOrUrl, options, onComplete) {
                var _parseParameters5 = parseParameters(options, undefined, onComplete),
                    opts = _parseParameters5.options,
                    onComp = _parseParameters5.onComplete;

                var bundleName = basename(nameOrUrl);

                if (this.bundles.has(bundleName)) {
                  asyncify(onComp)(null, this.getBundle(bundleName));
                  return;
                }

                opts.preset = opts.preset || 'bundle';
                opts.ext = 'bundle';
                opts.__isNative__ = true;
                this.loadAny({
                  url: nameOrUrl
                }, opts, null, function (err, data) {
                  if (err) {
                    error(err.message, err.stack);

                    if (onComp) {
                      onComp(err, data);
                    }
                  } else {
                    factory.create(nameOrUrl, data, 'bundle', opts, function (p1, p2) {
                      if (onComp) {
                        onComp(p1, p2);
                      }
                    });
                  }
                });
              };

              _proto.releaseAsset = function releaseAsset(asset) {
                releaseManager.tryRelease(asset, true);
              };

              _proto.releaseUnusedAssets = function releaseUnusedAssets() {
                assets.forEach(function (asset) {
                  releaseManager.tryRelease(asset);
                });
              };

              _proto.releaseAll = function releaseAll() {
                assets.forEach(function (asset) {
                  releaseManager.tryRelease(asset, true);
                });
              };

              _proto.loadWithJson = function loadWithJson(json, options, onProgress, onComplete) {
                {
                  throw new Error('Only valid in Editor');
                }
              };

              _createClass(AssetManager, [{
                key: "main",
                get: function get() {
                  return bundles.get(BuiltinBundleName.MAIN) || null;
                }
              }, {
                key: "resources",
                get: function get() {
                  return bundles.get(BuiltinBundleName.RESOURCES) || null;
                }
              }]);

              return AssetManager;
            }());
            AssetManager.Pipeline = Pipeline;
            AssetManager.Task = Task;
            AssetManager.Cache = Cache;
            AssetManager.RequestItem = RequestItem;
            AssetManager.Bundle = Bundle;
            AssetManager.BuiltinBundleName = BuiltinBundleName;
            var assetManager = exports('assetManager', legacyCC.assetManager = new AssetManager());
            legacyCC.AssetManager = AssetManager;

            var ImageFmts = ['.png', '.jpg', '.bmp', '.jpeg', '.gif', '.ico', '.tiff', '.webp', '.image', '.pvr', '.pkm', '.astc'];
            var AudioFmts = ['.mp3', '.ogg', '.wav', '.m4a'];

            function GetTrue() {
              return true;
            }

            var md5Pipe = {
              transformURL: function transformURL(url) {
                var uuid = getUuidFromURL(url);

                if (!uuid) {
                  return url;
                }

                var bundle = bundles.find(function (b) {
                  return !!b.getAssetInfo(uuid);
                });

                if (!bundle) {
                  return url;
                }

                var hashValue = '';
                var 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;
                }

                var hashPatchInFolder = false;

                if (extname(url) === '.ttf') {
                  hashPatchInFolder = true;
                }

                if (hashPatchInFolder) {
                  var dirname$1 = dirname(url);
                  var basename$1 = basename(url);
                  url = dirname$1 + "." + hashValue + "/" + basename$1;
                } else {
                  url = url.replace(/.*[/\\][0-9a-fA-F]{2}[/\\]([0-9a-fA-F-@]{8,}).*/, function (match, uuid) {
                    return match + "." + hashValue;
                  });
                }

                return url;
              }
            };
            var CCLoader = exports('CCLoader', function () {
              function CCLoader() {
                this._autoReleaseSetting = Object.create(null);
                this._parseLoadResArgs = parseLoadResArgs;
              }

              var _proto = CCLoader.prototype;

              _proto.load = function load(res, progressCallback, completeCallback) {
                if (completeCallback === undefined) {
                  if (progressCallback !== undefined) {
                    completeCallback = progressCallback;
                    progressCallback = null;
                  }
                }

                var requests = Array.isArray(res) ? res : [res];

                for (var i = 0; i < requests.length; i++) {
                  var _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;
                    }
                  }
                }

                var images = [];
                var audios = [];
                assetManager.loadAny(requests, null, function (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);
                  }
                }, function (err, _native) {
                  var out = null;

                  if (!err) {
                    _native = Array.isArray(_native) ? _native : [_native];

                    var _loop = function _loop(_i) {
                      var item = _native[_i];

                      if (!(item instanceof Asset)) {
                        var _asset = item;
                        var _url = requests[_i].url;

                        if (images.includes(_asset)) {
                          factory.create(_url, item, '.png', {}, function (err, image) {
                            _asset = _native[_i] = image;
                          });
                        } else if (audios.includes(_asset)) {
                          factory.create(_url, item, '.mp3', {}, function (err, audio) {
                            _asset = _native[_i] = audio;
                          });
                        }

                        assets.add(_url, _asset);
                      }
                    };

                    for (var _i = 0; _i < _native.length; _i++) {
                      _loop(_i);
                    }

                    if (_native.length > 1) {
                      var map = Object.create(null);

                      _native.forEach(function (asset) {
                        map[asset._uuid] = asset;
                      });

                      out = {
                        isCompleted: GetTrue,
                        _map: map
                      };
                    } else {
                      out = _native[0];
                    }
                  }

                  if (completeCallback) {
                    completeCallback(err, out);
                  }
                });
              };

              _proto.getXMLHttpRequest = function getXMLHttpRequest() {
                return new XMLHttpRequest();
              };

              _proto.getItem = function getItem(id) {
                return assetManager.assets.has(id) ? {
                  content: assetManager.assets.get(id)
                } : null;
              };

              _proto.loadRes = function loadRes(url, type, progressCallback, completeCallback) {
                var _this$_parseLoadResAr = this._parseLoadResArgs(type, progressCallback, completeCallback),
                    _type = _this$_parseLoadResAr.type,
                    onProgress = _this$_parseLoadResAr.onProgress,
                    onComplete = _this$_parseLoadResAr.onComplete;

                var extname$1 = extname(url);

                if (extname$1 && !resources.getInfoWithPath(url, _type)) {
                  url = url.slice(0, -extname$1.length);
                }

                resources.load(url, _type, onProgress, onComplete);
              };

              _proto.loadResArray = function loadResArray(urls, type, progressCallback, completeCallback) {
                var _this$_parseLoadResAr2 = this._parseLoadResArgs(type, progressCallback, completeCallback),
                    _type = _this$_parseLoadResAr2.type,
                    onProgress = _this$_parseLoadResAr2.onProgress,
                    onComplete = _this$_parseLoadResAr2.onComplete;

                urls.forEach(function (url, i) {
                  var 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);
              };

              _proto.loadResDir = function loadResDir(url, type, progressCallback, completeCallback) {
                var _this$_parseLoadResAr3 = this._parseLoadResArgs(type, progressCallback, completeCallback),
                    _type = _this$_parseLoadResAr3.type,
                    onProgress = _this$_parseLoadResAr3.onProgress,
                    onComplete = _this$_parseLoadResAr3.onComplete;

                resources.loadDir(url, _type, onProgress, function (err, out) {
                  var urls = [];

                  if (!err) {
                    var infos = resources.getDirWithPath(url, _type);
                    urls = infos.map(function (info) {
                      return info.path;
                    });
                  }

                  if (onComplete) {
                    onComplete(err, out, urls);
                  }
                });
              };

              _proto.getRes = function getRes(url, type) {
                return assets.has(url) ? assets.get(url) : resources.get(url, type);
              };

              _proto.getResCount = function getResCount() {
                return assets.count;
              };

              _proto.getDependsRecursively = function getDependsRecursively(owner) {
                if (!owner) {
                  return [];
                }

                var uuid = typeof owner === 'string' ? owner : owner._uuid;
                return dependUtil.getDepsRecursively(uuid).concat([uuid]);
              };

              _proto.addDownloadHandlers = function addDownloadHandlers(extMap) {
                var handler = Object.create(null);

                var _loop2 = function _loop2(_type2) {
                  var func = extMap[_type2];

                  handler["." + _type2] = function (url, options, onComplete) {
                    func({
                      url: url
                    }, onComplete);
                  };
                };

                for (var _type2 in extMap) {
                  _loop2(_type2);
                }

                downloader.register(handler);
              };

              _proto.addLoadHandlers = function addLoadHandlers(extMap) {
                var handler = Object.create(null);

                var _loop3 = function _loop3(_type3) {
                  var func = extMap[_type3];

                  handler["." + _type3] = function (file, options, onComplete) {
                    func({
                      content: file
                    }, onComplete);
                  };
                };

                for (var _type3 in extMap) {
                  _loop3(_type3);
                }

                parser.register(handler);
              };

              _proto.release = function release(asset) {
                if (Array.isArray(asset)) {
                  for (var i = 0; i < asset.length; i++) {
                    var 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);
                }
              };

              _proto.releaseAsset = function releaseAsset(asset) {
                assetManager.releaseAsset(asset);
              };

              _proto.releaseRes = function releaseRes(res, type) {
                resources.release(res, type);
              };

              _proto.releaseAll = function releaseAll() {
                assetManager.releaseAll();
                assets.clear();
              };

              _proto.removeItem = function removeItem(id) {
                return !!assets.remove(id);
              };

              _proto.setAutoRelease = function setAutoRelease(asset, autoRelease) {
                if (typeof asset === 'object') {
                  asset = asset._uuid;
                }

                this._autoReleaseSetting[asset] = !!autoRelease;
              };

              _proto.setAutoReleaseRecursively = function setAutoReleaseRecursively(asset, autoRelease) {
                if (typeof asset === 'object') {
                  asset = asset._uuid;
                }

                autoRelease = !!autoRelease;
                this._autoReleaseSetting[asset] = autoRelease;
                var depends = dependUtil.getDepsRecursively(asset);

                for (var i = 0; i < depends.length; i++) {
                  this._autoReleaseSetting[depends[i]] = autoRelease;
                }
              };

              _proto.isAutoRelease = function isAutoRelease(asset) {
                if (typeof asset === 'object') {
                  asset = asset._uuid;
                }

                return !!this._autoReleaseSetting[asset];
              };

              _createClass(CCLoader, [{
                key: "onProgress",
                set: function set(val) {
                  setDefaultProgressCallback(val);
                }
              }, {
                key: "_cache",
                get: function get() {
                  return assets._map;
                }
              }, {
                key: "md5Pipe",
                get: function get() {
                  return md5Pipe;
                }
              }, {
                key: "downloader",
                get: function get() {
                  return downloader;
                }
              }, {
                key: "loader",
                get: function get() {
                  return assetManager.parser;
                }
              }]);

              return CCLoader;
            }());
            var loader = exports('loader', new CCLoader());
            var AssetLibrary = exports('AssetLibrary', {
              init: function 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: BuiltinBundleName.RESOURCES,
                    importBase: options.importBase,
                    nativeBase: options.nativeBase,
                    paths: options.rawAssets.assets,
                    uuids: Object.keys(options.rawAssets.assets)
                  });
                }
              },
              loadAsset: function loadAsset(uuid, callback, options) {
                assetManager.loadAny(uuid, callback);
              }
            });
            var url = exports('url', {});
            replaceProperty(url, 'url', [{
              name: 'normalize',
              target: assetManager.utils,
              targetName: 'assetManager.utils',
              newName: 'normalize'
            }, {
              name: 'raw',
              targetName: 'Asset.prototype',
              newName: 'nativeUrl',
              customFunction: function customFunction(url) {
                if (url.startsWith('resources/')) {
                  return transform({
                    path: changeExtname(url.substr(10)),
                    bundle: BuiltinBundleName.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 cc.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: 'cc.loader.assetLoader was removed, assetLoader and md5Pipe were merged into cc.assetManager.transformPipeline'
            }]);
            replaceProperty(legacyCC, 'cc', [{
              name: 'loader',
              newName: 'assetManager',
              logTimes: 1,
              customGetter: function customGetter() {
                return loader;
              }
            }, {
              name: 'AssetLibrary',
              newName: 'assetManager',
              logTimes: 1,
              customGetter: function customGetter() {
                return AssetLibrary;
              }
            }, {
              name: 'Pipeline',
              target: AssetManager,
              targetName: 'AssetManager',
              newName: 'Pipeline',
              logTimes: 1
            }, {
              name: 'url',
              targetName: 'assetManager',
              newName: 'utils',
              logTimes: 1,
              customGetter: function customGetter() {
                return url;
              }
            }]);
            removeProperty(legacyCC, 'cc', [{
              name: 'LoadingItems',
              suggest: getError(1400, 'cc.LoadingItems', 'cc.AssetManager.Task')
            }]);
            replaceProperty(macro, 'macro', [{
              name: 'DOWNLOAD_MAX_CONCURRENT',
              target: downloader,
              targetName: 'assetManager.downloader',
              newName: 'maxConcurrency'
            }]);
            replaceProperty(director, 'director', [{
              name: '_getSceneUuid',
              targetName: 'assetManager.main',
              newName: 'getSceneInfo',
              customFunction: function 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 '';
              }
            }]);
            replaceProperty(game, 'game', [{
              name: '_sceneInfos',
              targetName: 'assetManager.main',
              newName: 'getSceneInfo',
              customGetter: function customGetter() {
                var scenes = [];

                if (assetManager.main) {
                  assetManager.main.config.scenes.forEach(function (val) {
                    scenes.push(val);
                  });
                }

                return scenes;
              }
            }]);
            var _autoRelease = releaseManager._autoRelease;

            releaseManager._autoRelease = function (oldScene, newScene, persistNodes) {
              _autoRelease.call(releaseManager, oldScene, newScene, persistNodes);

              var releaseSettings = loader._autoReleaseSetting;
              var keys = Object.keys(releaseSettings);

              for (var i = 0; i < keys.length; i++) {
                var key = keys[i];

                if (releaseSettings[key] === true) {
                  var _asset2 = assets.get(key);

                  if (_asset2) {
                    releaseManager.tryRelease(_asset2);
                  }
                }
              }
            };

            var _dec$E, _dec2$k, _dec3$g, _dec4$b, _dec5$8, _dec6$4, _class$E, _class2$C, _descriptor$u, _descriptor2$j, _descriptor3$c, _descriptor4$a, _descriptor5$7, _temp$D;
            var EventHandler = exports('EventHandler', (_dec$E = ccclass('cc.ClickEvent'), _dec2$k = type(legacyCC.Node), _dec3$g = tooltip(), _dec4$b = tooltip(), _dec5$8 = tooltip(), _dec6$4 = tooltip(), _dec$E(_class$E = (_class2$C = (_temp$D = function () {
              function EventHandler() {
                _initializerDefineProperty(this, "target", _descriptor$u, this);

                _initializerDefineProperty(this, "component", _descriptor2$j, this);

                _initializerDefineProperty(this, "_componentId", _descriptor3$c, this);

                _initializerDefineProperty(this, "handler", _descriptor4$a, this);

                _initializerDefineProperty(this, "customEventData", _descriptor5$7, this);
              }

              EventHandler.emitEvents = function emitEvents(events) {
                for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
                  args[_key - 1] = arguments[_key];
                }

                for (var i = 0, l = events.length; i < l; i++) {
                  var event = events[i];

                  if (!(event instanceof EventHandler)) {
                    continue;
                  }

                  event.emit(args);
                }
              };

              var _proto = EventHandler.prototype;

              _proto.emit = function emit(params) {
                var target = this.target;

                if (!legacyCC.isValid(target)) {
                  return;
                }

                this._genCompIdIfNeeded();

                var compType = legacyCC.js._getClassById(this._componentId);

                var comp = target.getComponent(compType);

                if (!legacyCC.isValid(comp)) {
                  return;
                }

                var handler = comp[this.handler];

                if (typeof handler !== 'function') {
                  return;
                }

                if (this.customEventData != null && this.customEventData !== '') {
                  params = params.slice();
                  params.push(this.customEventData);
                }

                handler.apply(comp, params);
              };

              _proto._compName2Id = function _compName2Id(compName) {
                var comp = legacyCC.js.getClassByName(compName);
                return legacyCC.js._getClassId(comp);
              };

              _proto._compId2Name = function _compId2Name(compId) {
                var comp = legacyCC.js._getClassById(compId);

                return legacyCC.js.getClassName(comp);
              };

              _proto._genCompIdIfNeeded = function _genCompIdIfNeeded() {
                if (!this._componentId) {
                  this._componentName = this.component;
                  this.component = '';
                }
              };

              _createClass(EventHandler, [{
                key: "_componentName",
                get: function get() {
                  this._genCompIdIfNeeded();

                  return this._compId2Name(this._componentId);
                },
                set: function set(value) {
                  this._componentId = this._compName2Id(value);
                }
              }]);

              return EventHandler;
            }(), _temp$D), (_descriptor$u = _applyDecoratedDescriptor(_class2$C.prototype, "target", [serializable, _dec2$k, _dec3$g], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor2$j = _applyDecoratedDescriptor(_class2$C.prototype, "component", [serializable, editable, _dec4$b], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return '';
              }
            }), _descriptor3$c = _applyDecoratedDescriptor(_class2$C.prototype, "_componentId", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return '';
              }
            }), _descriptor4$a = _applyDecoratedDescriptor(_class2$C.prototype, "handler", [serializable, editable, _dec5$8], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return '';
              }
            }), _descriptor5$7 = _applyDecoratedDescriptor(_class2$C.prototype, "customEventData", [serializable, editable, _dec6$4], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return '';
              }
            })), _class2$C)) || _class$E));
            legacyCC.Component.EventHandler = EventHandler;

            var _dec$F, _dec2$l, _dec3$h, _dec4$c, _dec5$9, _dec6$5, _dec7$3, _dec8$3, _dec9$3, _dec10$3, _dec11$3, _dec12$3, _dec13$3, _dec14$3, _dec15$3, _dec16$3, _dec17$3, _dec18$3, _dec19$3, _dec20$3, _dec21$3, _dec22$3, _dec23$3, _dec24$3, _dec25$3, _dec26$3, _dec27$2, _dec28$2, _dec29$2, _dec30$2, _dec31$2, _dec32$1, _dec33$1, _dec34$1, _dec35$1, _dec36$1, _dec37$1, _dec38$1, _dec39$1, _dec40$1, _dec41$1, _dec42$1, _dec43$1, _dec44$1, _dec45$1, _class$F, _class2$D, _descriptor$v, _descriptor2$k, _descriptor3$d, _descriptor4$b, _descriptor5$8, _descriptor6$4, _descriptor7$4, _descriptor8$4, _descriptor9$3, _descriptor10$3, _descriptor11$3, _descriptor12$3, _descriptor13$3, _descriptor14$3, _descriptor15$3, _descriptor16$3, _descriptor17$3, _descriptor18$3, _class3$e, _temp$E;

            var _temp_vec3_1 = new Vec3();

            var ProjectionType = Enum(CameraProjection);
            var FOVAxis = Enum(CameraFOVAxis);
            var Aperture = Enum(CameraAperture);
            var Shutter = Enum(CameraShutter);
            var ISO = Enum(CameraISO);
            var ClearFlag = Enum({
              SKYBOX: SKYBOX_FLAG | ClearFlagBit.DEPTH_STENCIL,
              SOLID_COLOR: ClearFlagBit.ALL,
              DEPTH_ONLY: ClearFlagBit.DEPTH_STENCIL,
              DONT_CLEAR: ClearFlagBit.NONE
            });
            var Camera$1 = function (v) { return exports({ Camera: v, CameraComponent: v }), v; }((_dec$F = ccclass('cc.Camera'), _dec2$l = help(), _dec3$h = menu(), _dec4$c = displayOrder(), _dec5$9 = tooltip(), _dec6$5 = type(Layers.BitMask), _dec7$3 = displayOrder(), _dec8$3 = tooltip(), _dec9$3 = type(ClearFlag), _dec10$3 = displayOrder(), _dec11$3 = tooltip(), _dec12$3 = displayOrder(), _dec13$3 = tooltip(), _dec14$3 = displayOrder(), _dec15$3 = tooltip(), _dec16$3 = displayOrder(), _dec17$3 = tooltip(), _dec18$3 = type(ProjectionType), _dec19$3 = displayOrder(), _dec20$3 = tooltip(), _dec21$3 = type(FOVAxis), _dec22$3 = displayOrder(), _dec23$3 = tooltip(), _dec24$3 = displayOrder(), _dec25$3 = tooltip(), _dec26$3 = displayOrder(), _dec27$2 = tooltip(), _dec28$2 = displayOrder(), _dec29$2 = tooltip(), _dec30$2 = displayOrder(), _dec31$2 = tooltip(), _dec32$1 = type(Aperture), _dec33$1 = displayOrder(), _dec34$1 = tooltip(), _dec35$1 = type(Shutter), _dec36$1 = displayOrder(), _dec37$1 = tooltip(), _dec38$1 = type(ISO), _dec39$1 = displayOrder(), _dec40$1 = tooltip(), _dec41$1 = displayOrder(), _dec42$1 = tooltip(), _dec43$1 = type(RenderTexture), _dec44$1 = displayOrder(), _dec45$1 = tooltip(), _dec$F(_class$F = _dec2$l(_class$F = _dec3$h(_class$F = executeInEditMode(_class$F = (_class2$D = (_temp$E = _class3$e = function (_Component) {
              _inheritsLoose(Camera, _Component);

              function Camera() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Component.call.apply(_Component, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "_projection", _descriptor$v, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_priority", _descriptor2$k, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_fov", _descriptor3$d, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_fovAxis", _descriptor4$b, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_orthoHeight", _descriptor5$8, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_near", _descriptor6$4, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_far", _descriptor7$4, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_color", _descriptor8$4, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_depth", _descriptor9$3, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_stencil", _descriptor10$3, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_clearFlags", _descriptor11$3, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_rect", _descriptor12$3, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_aperture", _descriptor13$3, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_shutter", _descriptor14$3, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_iso", _descriptor15$3, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_screenScale", _descriptor16$3, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_visibility", _descriptor17$3, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_targetTexture", _descriptor18$3, _assertThisInitialized(_this));

                _this._camera = null;
                _this._inEditorMode = false;
                _this._flows = undefined;
                return _this;
              }

              var _proto = Camera.prototype;

              _proto.onLoad = function onLoad() {
                this._createCamera();
              };

              _proto.onEnable = function onEnable() {
                this.node.hasChangedFlags |= TransformBit.POSITION;

                if (this._camera) {
                  this._attachToScene();
                }
              };

              _proto.onDisable = function onDisable() {
                if (this._camera) {
                  this._detachFromScene();
                }
              };

              _proto.onDestroy = function onDestroy() {
                if (this._camera) {
                  this._camera.destroy();

                  this._camera = null;
                }

                if (this._targetTexture) {
                  this._targetTexture.off('resize');
                }
              };

              _proto.screenPointToRay = function screenPointToRay(x, y, out) {
                if (!out) {
                  out = Ray.create();
                }

                if (this._camera) {
                  this._camera.screenPointToRay(out, x, y);
                }

                return out;
              };

              _proto.worldToScreen = function worldToScreen(worldPos, out) {
                if (!out) {
                  out = new Vec3();
                }

                if (this._camera) {
                  this._camera.worldToScreen(out, worldPos);
                }

                return out;
              };

              _proto.screenToWorld = function screenToWorld(screenPos, out) {
                if (!out) {
                  out = this.node.getWorldPosition();
                }

                if (this._camera) {
                  this._camera.screenToWorld(out, screenPos);
                }

                return out;
              };

              _proto.convertToUINode = function convertToUINode(wpos, uiNode, out) {
                if (!out) {
                  out = new Vec3();
                }

                if (!this._camera) {
                  return out;
                }

                this.worldToScreen(wpos, _temp_vec3_1);
                var cmp = uiNode.getComponent('cc.UITransform');
                var designSize = view.getVisibleSize();
                var xoffset = _temp_vec3_1.x - this._camera.width * 0.5;
                var yoffset = _temp_vec3_1.y - this._camera.height * 0.5;
                _temp_vec3_1.x = xoffset / legacyCC.view.getScaleX() + designSize.width * 0.5;
                _temp_vec3_1.y = yoffset / legacyCC.view.getScaleY() + designSize.height * 0.5;

                if (cmp) {
                  cmp.convertToNodeSpaceAR(_temp_vec3_1, out);
                }

                return out;
              };

              _proto._createCamera = function _createCamera() {
                if (!this._camera) {
                  this._camera = legacyCC.director.root.createCamera();

                  this._camera.initialize({
                    name: this.node.name,
                    node: this.node,
                    projection: this._projection,
                    window: this._inEditorMode ? legacyCC.director.root && legacyCC.director.root.mainWindow : legacyCC.director.root && legacyCC.director.root.tempWindow,
                    priority: this._priority
                  });

                  this._camera.viewport = 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._updateTargetTexture();
              };

              _proto._attachToScene = function _attachToScene() {
                if (!this.node.scene || !this._camera) {
                  return;
                }

                if (this._camera && this._camera.scene) {
                  this._camera.scene.removeCamera(this._camera);
                }

                var rs = this._getRenderScene();

                rs.addCamera(this._camera);
              };

              _proto._detachFromScene = function _detachFromScene() {
                if (this._camera && this._camera.scene) {
                  this._camera.scene.removeCamera(this._camera);
                }
              };

              _proto._chechTargetTextureEvent = function _chechTargetTextureEvent(old) {
                var _this2 = this;

                var resizeFunc = function resizeFunc(window) {
                  if (_this2._camera) {
                    _this2._camera.setFixedSize(window.width, window.height);
                  }
                };

                if (old) {
                  old.off('resize');
                }

                if (this._targetTexture) {
                  this._targetTexture.on('resize', resizeFunc, this);
                }
              };

              _proto._updateTargetTexture = function _updateTargetTexture() {
                if (!this._camera) {
                  return;
                }

                if (this._targetTexture) {
                  var window = this._targetTexture.window;

                  this._camera.changeTargetWindow(window);

                  this._camera.setFixedSize(window.width, window.height);
                }
              };

              _createClass(Camera, [{
                key: "camera",
                get: function get() {
                  return this._camera;
                }
              }, {
                key: "priority",
                get: function get() {
                  return this._priority;
                },
                set: function set(val) {
                  this._priority = val;

                  if (this._camera) {
                    this._camera.priority = val;
                  }
                }
              }, {
                key: "visibility",
                get: function get() {
                  return this._visibility;
                },
                set: function set(val) {
                  this._visibility = val;

                  if (this._camera) {
                    this._camera.visibility = val;
                  }
                }
              }, {
                key: "clearFlags",
                get: function get() {
                  return this._clearFlags;
                },
                set: function set(val) {
                  this._clearFlags = val;

                  if (this._camera) {
                    this._camera.clearFlag = val;
                  }
                }
              }, {
                key: "clearColor",
                get: function get() {
                  return this._color;
                },
                set: function set(val) {
                  this._color.set(val);

                  if (this._camera) {
                    this._camera.clearColor = this._color;
                  }
                }
              }, {
                key: "clearDepth",
                get: function get() {
                  return this._depth;
                },
                set: function set(val) {
                  this._depth = val;

                  if (this._camera) {
                    this._camera.clearDepth = val;
                  }
                }
              }, {
                key: "clearStencil",
                get: function get() {
                  return this._stencil;
                },
                set: function set(val) {
                  this._stencil = val;

                  if (this._camera) {
                    this._camera.clearStencil = val;
                  }
                }
              }, {
                key: "projection",
                get: function get() {
                  return this._projection;
                },
                set: function set(val) {
                  this._projection = val;

                  if (this._camera) {
                    this._camera.projectionType = val;
                  }
                }
              }, {
                key: "fovAxis",
                get: function get() {
                  return this._fovAxis;
                },
                set: function set(val) {
                  if (val === this._fovAxis) {
                    return;
                  }

                  this._fovAxis = val;

                  if (this._camera) {
                    this._camera.fovAxis = val;

                    if (val === CameraFOVAxis.VERTICAL) {
                      this.fov = this._fov * this._camera.aspect;
                    } else {
                      this.fov = this._fov / this._camera.aspect;
                    }
                  }
                }
              }, {
                key: "fov",
                get: function get() {
                  return this._fov;
                },
                set: function set(val) {
                  this._fov = val;

                  if (this._camera) {
                    this._camera.fov = toRadian(val);
                  }
                }
              }, {
                key: "orthoHeight",
                get: function get() {
                  return this._orthoHeight;
                },
                set: function set(val) {
                  this._orthoHeight = val;

                  if (this._camera) {
                    this._camera.orthoHeight = val;
                  }
                }
              }, {
                key: "near",
                get: function get() {
                  return this._near;
                },
                set: function set(val) {
                  this._near = val;

                  if (this._camera) {
                    this._camera.nearClip = val;
                  }
                }
              }, {
                key: "far",
                get: function get() {
                  return this._far;
                },
                set: function set(val) {
                  this._far = val;

                  if (this._camera) {
                    this._camera.farClip = val;
                  }
                }
              }, {
                key: "aperture",
                get: function get() {
                  return this._aperture;
                },
                set: function set(val) {
                  this._aperture = val;

                  if (this._camera) {
                    this._camera.aperture = val;
                  }
                }
              }, {
                key: "shutter",
                get: function get() {
                  return this._shutter;
                },
                set: function set(val) {
                  this._shutter = val;

                  if (this._camera) {
                    this._camera.shutter = val;
                  }
                }
              }, {
                key: "iso",
                get: function get() {
                  return this._iso;
                },
                set: function set(val) {
                  this._iso = val;

                  if (this._camera) {
                    this._camera.iso = val;
                  }
                }
              }, {
                key: "rect",
                get: function get() {
                  return this._rect;
                },
                set: function set(val) {
                  this._rect = val;

                  if (this._camera) {
                    this._camera.viewport = val;
                  }
                }
              }, {
                key: "targetTexture",
                get: function get() {
                  return this._targetTexture;
                },
                set: function set(value) {
                  if (this._targetTexture === value) {
                    return;
                  }

                  var old = this._targetTexture;
                  this._targetTexture = value;

                  this._chechTargetTextureEvent(old);

                  this._updateTargetTexture();

                  if (!value && this._camera) {
                    this._camera.changeTargetWindow( null);

                    this._camera.isWindowSize = true;
                  }
                }
              }, {
                key: "screenScale",
                get: function get() {
                  return this._screenScale;
                },
                set: function set(val) {
                  this._screenScale = val;

                  if (this._camera) {
                    this._camera.screenScale = val;
                  }
                }
              }, {
                key: "inEditorMode",
                get: function get() {
                  return this._inEditorMode;
                },
                set: function set(value) {
                  this._inEditorMode = value;

                  if (this._camera) {
                    this._camera.changeTargetWindow(value ? legacyCC.director.root && legacyCC.director.root.mainWindow : legacyCC.director.root && legacyCC.director.root.tempWindow);
                  }
                }
              }]);

              return Camera;
            }(Component), _class3$e.ProjectionType = ProjectionType, _class3$e.FOVAxis = FOVAxis, _class3$e.ClearFlag = ClearFlag, _class3$e.Aperture = Aperture, _class3$e.Shutter = Shutter, _class3$e.ISO = ISO, _temp$E), (_descriptor$v = _applyDecoratedDescriptor(_class2$D.prototype, "_projection", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return ProjectionType.PERSPECTIVE;
              }
            }), _descriptor2$k = _applyDecoratedDescriptor(_class2$D.prototype, "_priority", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor3$d = _applyDecoratedDescriptor(_class2$D.prototype, "_fov", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 45;
              }
            }), _descriptor4$b = _applyDecoratedDescriptor(_class2$D.prototype, "_fovAxis", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return FOVAxis.VERTICAL;
              }
            }), _descriptor5$8 = _applyDecoratedDescriptor(_class2$D.prototype, "_orthoHeight", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 10;
              }
            }), _descriptor6$4 = _applyDecoratedDescriptor(_class2$D.prototype, "_near", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1;
              }
            }), _descriptor7$4 = _applyDecoratedDescriptor(_class2$D.prototype, "_far", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1000;
              }
            }), _descriptor8$4 = _applyDecoratedDescriptor(_class2$D.prototype, "_color", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new Color('#333333');
              }
            }), _descriptor9$3 = _applyDecoratedDescriptor(_class2$D.prototype, "_depth", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1;
              }
            }), _descriptor10$3 = _applyDecoratedDescriptor(_class2$D.prototype, "_stencil", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor11$3 = _applyDecoratedDescriptor(_class2$D.prototype, "_clearFlags", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return ClearFlag.SOLID_COLOR;
              }
            }), _descriptor12$3 = _applyDecoratedDescriptor(_class2$D.prototype, "_rect", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new Rect(0, 0, 1, 1);
              }
            }), _descriptor13$3 = _applyDecoratedDescriptor(_class2$D.prototype, "_aperture", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return Aperture.F16_0;
              }
            }), _descriptor14$3 = _applyDecoratedDescriptor(_class2$D.prototype, "_shutter", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return Shutter.D125;
              }
            }), _descriptor15$3 = _applyDecoratedDescriptor(_class2$D.prototype, "_iso", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return ISO.ISO100;
              }
            }), _descriptor16$3 = _applyDecoratedDescriptor(_class2$D.prototype, "_screenScale", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1;
              }
            }), _descriptor17$3 = _applyDecoratedDescriptor(_class2$D.prototype, "_visibility", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return CAMERA_DEFAULT_MASK;
              }
            }), _descriptor18$3 = _applyDecoratedDescriptor(_class2$D.prototype, "_targetTexture", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _applyDecoratedDescriptor(_class2$D.prototype, "priority", [_dec4$c, _dec5$9], Object.getOwnPropertyDescriptor(_class2$D.prototype, "priority"), _class2$D.prototype), _applyDecoratedDescriptor(_class2$D.prototype, "visibility", [_dec6$5, _dec7$3, _dec8$3], Object.getOwnPropertyDescriptor(_class2$D.prototype, "visibility"), _class2$D.prototype), _applyDecoratedDescriptor(_class2$D.prototype, "clearFlags", [_dec9$3, _dec10$3, _dec11$3], Object.getOwnPropertyDescriptor(_class2$D.prototype, "clearFlags"), _class2$D.prototype), _applyDecoratedDescriptor(_class2$D.prototype, "clearColor", [_dec12$3, _dec13$3], Object.getOwnPropertyDescriptor(_class2$D.prototype, "clearColor"), _class2$D.prototype), _applyDecoratedDescriptor(_class2$D.prototype, "clearDepth", [_dec14$3, _dec15$3], Object.getOwnPropertyDescriptor(_class2$D.prototype, "clearDepth"), _class2$D.prototype), _applyDecoratedDescriptor(_class2$D.prototype, "clearStencil", [_dec16$3, _dec17$3], Object.getOwnPropertyDescriptor(_class2$D.prototype, "clearStencil"), _class2$D.prototype), _applyDecoratedDescriptor(_class2$D.prototype, "projection", [_dec18$3, _dec19$3, _dec20$3], Object.getOwnPropertyDescriptor(_class2$D.prototype, "projection"), _class2$D.prototype), _applyDecoratedDescriptor(_class2$D.prototype, "fovAxis", [_dec21$3, _dec22$3, _dec23$3], Object.getOwnPropertyDescriptor(_class2$D.prototype, "fovAxis"), _class2$D.prototype), _applyDecoratedDescriptor(_class2$D.prototype, "fov", [_dec24$3, _dec25$3], Object.getOwnPropertyDescriptor(_class2$D.prototype, "fov"), _class2$D.prototype), _applyDecoratedDescriptor(_class2$D.prototype, "orthoHeight", [_dec26$3, _dec27$2], Object.getOwnPropertyDescriptor(_class2$D.prototype, "orthoHeight"), _class2$D.prototype), _applyDecoratedDescriptor(_class2$D.prototype, "near", [_dec28$2, _dec29$2], Object.getOwnPropertyDescriptor(_class2$D.prototype, "near"), _class2$D.prototype), _applyDecoratedDescriptor(_class2$D.prototype, "far", [_dec30$2, _dec31$2], Object.getOwnPropertyDescriptor(_class2$D.prototype, "far"), _class2$D.prototype), _applyDecoratedDescriptor(_class2$D.prototype, "aperture", [_dec32$1, _dec33$1, _dec34$1], Object.getOwnPropertyDescriptor(_class2$D.prototype, "aperture"), _class2$D.prototype), _applyDecoratedDescriptor(_class2$D.prototype, "shutter", [_dec35$1, _dec36$1, _dec37$1], Object.getOwnPropertyDescriptor(_class2$D.prototype, "shutter"), _class2$D.prototype), _applyDecoratedDescriptor(_class2$D.prototype, "iso", [_dec38$1, _dec39$1, _dec40$1], Object.getOwnPropertyDescriptor(_class2$D.prototype, "iso"), _class2$D.prototype), _applyDecoratedDescriptor(_class2$D.prototype, "rect", [_dec41$1, _dec42$1], Object.getOwnPropertyDescriptor(_class2$D.prototype, "rect"), _class2$D.prototype), _applyDecoratedDescriptor(_class2$D.prototype, "targetTexture", [_dec43$1, _dec44$1, _dec45$1], Object.getOwnPropertyDescriptor(_class2$D.prototype, "targetTexture"), _class2$D.prototype)), _class2$D)) || _class$F) || _class$F) || _class$F) || _class$F));
            legacyCC.Camera = Camera$1;

            var _dec$G, _dec2$m, _dec3$i, _dec4$d, _dec5$a, _class$G, _class2$E, _descriptor$w, _descriptor2$l, _temp$F;
            var _matInsInfo = {
              parent: null,
              owner: null,
              subModelIdx: 0
            };
            var RenderableComponent = exports('RenderableComponent', (_dec$G = ccclass('cc.RenderableComponent'), _dec2$m = type([Material]), _dec3$i = type(Material), _dec4$d = displayOrder(), _dec5$a = displayName(), _dec$G(_class$G = (_class2$E = (_temp$F = function (_Component) {
              _inheritsLoose(RenderableComponent, _Component);

              function RenderableComponent() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Component.call.apply(_Component, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "_materials", _descriptor$w, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_visFlags", _descriptor2$l, _assertThisInitialized(_this));

                _this._materialInstances = [];
                _this._models = [];
                return _this;
              }

              var _proto = RenderableComponent.prototype;

              _proto.getMaterial = function getMaterial(idx) {
                if (idx < 0 || idx >= this._materials.length) {
                  return null;
                }

                return this._materials[idx];
              };

              _proto.setMaterial = function setMaterial(material, index) {
                if (material && material instanceof MaterialInstance) {
                  console.error('Can\'t set a material instance to a sharedMaterial slot');
                }

                this._materials[index] = material;
                var inst = this._materialInstances[index];

                if (inst) {
                  if (inst.parent !== this._materials[index]) {
                    inst.destroy();
                    this._materialInstances[index] = null;

                    this._onMaterialModified(index, this._materials[index]);
                  }
                } else {
                  this._onMaterialModified(index, this._materials[index]);
                }
              };

              _proto.getMaterialInstance = function getMaterialInstance(idx) {
                var mat = this._materials[idx];

                if (!mat) {
                  return null;
                }

                if (!this._materialInstances[idx]) {
                  _matInsInfo.parent = this._materials[idx];
                  _matInsInfo.owner = this;
                  _matInsInfo.subModelIdx = idx;
                  var instantiated = new MaterialInstance(_matInsInfo);
                  this.setMaterialInstance(idx, instantiated);
                }

                return this._materialInstances[idx];
              };

              _proto.setMaterialInstance = function setMaterialInstance(index, matInst) {
                if (matInst && matInst.parent) {
                  if (matInst !== this._materialInstances[index]) {
                    this._materialInstances[index] = matInst;

                    this._onMaterialModified(index, matInst);
                  }
                } else if (matInst !== this._materials[index]) {
                  this.setMaterial(matInst, index);
                }
              };

              _proto.getRenderMaterial = function getRenderMaterial(index) {
                return this._materialInstances[index] || this._materials[index];
              };

              _proto._collectModels = function _collectModels() {
                return this._models;
              };

              _proto._attachToScene = function _attachToScene() {};

              _proto._detachFromScene = function _detachFromScene() {};

              _proto._onMaterialModified = function _onMaterialModified(index, material) {};

              _proto._onRebuildPSO = function _onRebuildPSO(index, material) {};

              _proto._clearMaterials = function _clearMaterials() {};

              _proto._onVisibilityChange = function _onVisibilityChange(val) {};

              _createClass(RenderableComponent, [{
                key: "visibility",
                get: function get() {
                  return this._visFlags;
                },
                set: function set(val) {
                  this._visFlags = val;

                  this._onVisibilityChange(val);
                }
              }, {
                key: "sharedMaterials",
                get: function get() {
                  return  this._materials;
                },
                set: function set(val) {
                  for (var i = 0; i < val.length; i++) {
                    if (val[i] !== this._materials[i]) {
                      this.setMaterial(val[i], i);
                    }
                  }

                  if (val.length < this._materials.length) {
                    for (var _i = val.length; _i < this._materials.length; _i++) {
                      this.setMaterial(null, _i);
                    }

                    this._materials.splice(val.length);
                  }
                }
              }, {
                key: "materials",
                get: function get() {
                  for (var i = 0; i < this._materials.length; i++) {
                    this._materialInstances[i] = this.getMaterialInstance(i);
                  }

                  return this._materialInstances;
                },
                set: function set(val) {
                  var dLen = val.length - this._materials.length;

                  if (dLen > 0) {
                    this._materials.length = val.length;
                    this._materialInstances.length = val.length;
                  } else if (dLen < 0) {
                    for (var i = this._materials.length - dLen; i < this._materials.length; ++i) {
                      this.setMaterialInstance(i, null);
                    }
                  }

                  for (var _i2 = 0; _i2 < this._materialInstances.length; _i2++) {
                    if (this._materialInstances[_i2] != val[_i2]) {
                      this.setMaterialInstance(_i2, val[_i2]);
                    }
                  }
                }
              }, {
                key: "sharedMaterial",
                get: function get() {
                  return this.getMaterial(0);
                }
              }, {
                key: "material",
                get: function get() {
                  return this.getMaterialInstance(0);
                },
                set: function set(val) {
                  if (this._materials.length === 1 && this._materials[0] === val) {
                    return;
                  }

                  this.setMaterialInstance(0, val);
                }
              }]);

              return RenderableComponent;
            }(Component), _temp$F), (_descriptor$w = _applyDecoratedDescriptor(_class2$E.prototype, "_materials", [_dec2$m], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor2$l = _applyDecoratedDescriptor(_class2$E.prototype, "_visFlags", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return Layers.Enum.NONE;
              }
            }), _applyDecoratedDescriptor(_class2$E.prototype, "sharedMaterials", [_dec3$i, _dec4$d, _dec5$a], Object.getOwnPropertyDescriptor(_class2$E.prototype, "sharedMaterials"), _class2$E.prototype)), _class2$E)) || _class$G));
            legacyCC.RenderableComponent = RenderableComponent;

            replaceProperty(Camera$1, 'Camera', [{
              name: 'CameraClearFlag',
              newName: 'ClearFlag'
            }]);
            replaceProperty(Camera$1.prototype, 'Camera.prototype', [{
              name: 'color',
              newName: 'clearColor'
            }, {
              name: 'depth',
              newName: 'clearDepth'
            }, {
              name: 'stencil',
              newName: 'clearStencil'
            }]);
            legacyCC.CameraComponent = Camera$1;
            js.setClassAlias(Camera$1, 'cc.CameraComponent');

            var _dec$H, _class$H, _class2$F, _descriptor$x, _temp$G, _dec2$n, _class4$3, _class5$3, _descriptor2$m, _temp2$3;
            function isPropertyPath(path) {
              return typeof path === 'string' || typeof path === 'number';
            }
            function isCustomPath(path, constructor) {
              return path instanceof constructor;
            }
            var HierarchyPath = (_dec$H = ccclass('cc.animation.HierarchyPath'), _dec$H(_class$H = (_class2$F = (_temp$G = function () {
              function HierarchyPath(path) {
                _initializerDefineProperty(this, "path", _descriptor$x, this);

                this.path = path || '';
              }

              var _proto = HierarchyPath.prototype;

              _proto.get = function get(target) {
                if (!(target instanceof Node$1)) {
                  warn("Target of hierarchy path should be of type Node.");
                  return null;
                }

                var result = target.getChildByPath(this.path);

                if (!result) {
                  warn("Node \"" + target.name + "\" has no path \"" + this.path + "\"");
                  return null;
                }

                return result;
              };

              return HierarchyPath;
            }(), _temp$G), (_descriptor$x = _applyDecoratedDescriptor(_class2$F.prototype, "path", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return '';
              }
            })), _class2$F)) || _class$H);
            var ComponentPath = (_dec2$n = ccclass('cc.animation.ComponentPath'), _dec2$n(_class4$3 = (_class5$3 = (_temp2$3 = function () {
              function ComponentPath(component) {
                _initializerDefineProperty(this, "component", _descriptor2$m, this);

                this.component = component || '';
              }

              var _proto2 = ComponentPath.prototype;

              _proto2.get = function get(target) {
                if (!(target instanceof Node$1)) {
                  warn("Target of component path should be of type Node.");
                  return null;
                }

                var result = target.getComponent(this.component);

                if (!result) {
                  warn("Node \"" + target.name + "\" has no component \"" + this.component + "\"");
                  return null;
                }

                return result;
              };

              return ComponentPath;
            }(), _temp2$3), (_descriptor2$m = _applyDecoratedDescriptor(_class5$3.prototype, "component", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return '';
              }
            })), _class5$3)) || _class4$3);
            function evaluatePath(root) {
              var result = root;

              for (var iPath = 0; iPath < (arguments.length <= 1 ? 0 : arguments.length - 1); ++iPath) {
                var path = iPath + 1 < 1 || arguments.length <= iPath + 1 ? undefined : arguments[iPath + 1];

                if (isPropertyPath(path)) {
                  if (!(path in result)) {
                    warn("Target object has no property \"" + path + "\"");
                    return null;
                  } else {
                    result = result[path];
                  }
                } else {
                  result = path.get(result);
                }

                if (result === null) {
                  break;
                }
              }

              return result;
            }

            var _dec$I, _class$I, _class2$G, _descriptor$y, _descriptor2$n, _descriptor3$e, _temp$H;
            var UniformProxyFactory = (_dec$I = ccclass('cc.animation.UniformProxyFactory'), _dec$I(_class$I = (_class2$G = (_temp$H = function () {
              function UniformProxyFactory(uniformName, passIndex) {
                _initializerDefineProperty(this, "passIndex", _descriptor$y, this);

                _initializerDefineProperty(this, "uniformName", _descriptor2$n, this);

                _initializerDefineProperty(this, "channelIndex", _descriptor3$e, this);

                this.passIndex = passIndex || 0;
                this.uniformName = uniformName || '';
              }

              var _proto = UniformProxyFactory.prototype;

              _proto.forTarget = function forTarget(target) {
                var pass = target.passes[this.passIndex];
                var handle = pass.getHandle(this.uniformName);

                if (!handle) {
                  throw new Error("Material \"" + target.name + "\" has no uniform \"" + this.uniformName + "\"");
                }

                var propertyType = Pass.getPropertyTypeFromHandle(handle);

                if (propertyType === PropertyType.BUFFER) {
                  var realHandle = this.channelIndex === undefined ? handle : pass.getHandle(this.uniformName, this.channelIndex, Type.FLOAT);

                  if (!realHandle) {
                    throw new Error("Uniform \"" + this.uniformName + " (in material " + target.name + ") has no channel " + this.channelIndex + "\"");
                  }

                  if (isUniformArray(pass, this.uniformName)) {
                    return {
                      set: function set(value) {
                        pass.setUniformArray(realHandle, value);
                      }
                    };
                  }

                  return {
                    set: function set(value) {
                      pass.setUniform(realHandle, value);
                    }
                  };
                }

                if (propertyType === PropertyType.TEXTURE) {
                  var binding = Pass.getBindingFromHandle(handle);
                  var prop = pass.properties[this.uniformName];
                  var texName = prop && prop.value ? prop.value + "-texture" : getDefaultFromType(prop.type);
                  var dftTex = builtinResMgr.get(texName);

                  if (!dftTex) {
                    warn("Illegal texture default value: " + texName + ".");
                    dftTex = builtinResMgr.get('default-texture');
                  }

                  return {
                    set: function set(value) {
                      if (!value) {
                        value = dftTex;
                      }

                      var texture = value.getGFXTexture();

                      if (!texture || !texture.width || !texture.height) {
                        return;
                      }

                      pass.bindTexture(binding, texture);

                      if (value instanceof TextureBase) {
                        pass.bindSampler(binding, samplerLib.getSampler(legacyCC.game._gfxDevice, value.getSamplerHash()));
                      }
                    }
                  };
                }

                throw new Error("Animations are not available for uniforms with property type " + propertyType + ".");
              };

              return UniformProxyFactory;
            }(), _temp$H), (_descriptor$y = _applyDecoratedDescriptor(_class2$G.prototype, "passIndex", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor2$n = _applyDecoratedDescriptor(_class2$G.prototype, "uniformName", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return '';
              }
            }), _descriptor3$e = _applyDecoratedDescriptor(_class2$G.prototype, "channelIndex", [_float], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return undefined;
              }
            })), _class2$G)) || _class$I);

            function isUniformArray(pass, name) {
              for (var _iterator = _createForOfIteratorHelperLoose(pass.shaderInfo.blocks), _step; !(_step = _iterator()).done;) {
                var block = _step.value;

                for (var _iterator2 = _createForOfIteratorHelperLoose(block.members), _step2; !(_step2 = _iterator2()).done;) {
                  var uniform = _step2.value;

                  if (uniform.name === name) {
                    return uniform.count > 1;
                  }
                }
              }

              return false;
            }

            var _dec$J, _class$J, _class2$H, _descriptor$z, _temp$I, _dec2$o, _class4$4;
            var MorphWeightsValueProxy = (_dec$J = ccclass('cc.animation.MorphWeightsValueProxy'), _dec$J(_class$J = (_class2$H = (_temp$I = function () {
              function MorphWeightsValueProxy() {
                _initializerDefineProperty(this, "subMeshIndex", _descriptor$z, this);
              }

              var _proto = MorphWeightsValueProxy.prototype;

              _proto.forTarget = function forTarget(target) {
                var _this = this;

                return {
                  set: function set(value) {
                    target.setWeights(value, _this.subMeshIndex);
                  }
                };
              };

              return MorphWeightsValueProxy;
            }(), _temp$I), (_descriptor$z = _applyDecoratedDescriptor(_class2$H.prototype, "subMeshIndex", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            })), _class2$H)) || _class$J);
            var MorphWeightsAllValueProxy = (_dec2$o = ccclass('cc.animation.MorphWeightsAllValueProxy'), _dec2$o(_class4$4 = function () {
              function MorphWeightsAllValueProxy() {}

              var _proto2 = MorphWeightsAllValueProxy.prototype;

              _proto2.forTarget = function forTarget(target) {
                return {
                  set: function set(value) {
                    var _target$mesh$struct$p, _target$mesh;

                    var nSubMeshes = (_target$mesh$struct$p = (_target$mesh = target.mesh) === null || _target$mesh === void 0 ? void 0 : _target$mesh.struct.primitives.length) !== null && _target$mesh$struct$p !== void 0 ? _target$mesh$struct$p : 0;

                    for (var iSubMesh = 0; iSubMesh < nSubMeshes; ++iSubMesh) {
                      target.setWeights(value, iSubMesh);
                    }
                  }
                };
              };

              return MorphWeightsAllValueProxy;
            }()) || _class4$4);

            var _dec2$p, _class4$5, _class5$4, _descriptor4$c, _descriptor5$9, _descriptor6$5, _temp2$4;

            function makeCubicSplineValueConstructor(name, constructorX, scaleFx, scaleAndAdd) {
              var _dec, _class, _class2, _descriptor, _descriptor2, _descriptor3, _temp;

              var tempValue = new constructorX();
              var m0 = new constructorX();
              var m1 = new constructorX();
              var CubicSplineValueClass = (_dec = ccclass(name), _dec(_class = (_class2 = (_temp = function () {
                function CubicSplineValueClass(dataPoint, inTangent, outTangent) {
                  _initializerDefineProperty(this, "dataPoint", _descriptor, this);

                  _initializerDefineProperty(this, "inTangent", _descriptor2, this);

                  _initializerDefineProperty(this, "outTangent", _descriptor3, this);

                  this.dataPoint = dataPoint || new constructorX();
                  this.inTangent = inTangent || new constructorX();
                  this.outTangent = outTangent || new constructorX();
                }

                var _proto = CubicSplineValueClass.prototype;

                _proto.lerp = function lerp(to, t, dt) {
                  var p0 = this.dataPoint;
                  var p1 = to.dataPoint;
                  m0 = scaleFx(m0, this.inTangent, dt);
                  m1 = scaleFx(m1, to.outTangent, dt);
                  var t_3 = t * t * t;
                  var t_2 = t * t;
                  var f_0 = 2 * t_3 - 3 * t_2 + 1;
                  var f_1 = t_3 - 2 * t_2 + t;
                  var f_2 = -2 * t_3 + 3 * t_2;
                  var f_3 = t_3 - t_2;
                  tempValue = scaleFx(tempValue, p0, f_0);
                  tempValue = scaleAndAdd(tempValue, tempValue, m0, f_1);
                  tempValue = scaleAndAdd(tempValue, tempValue, p1, f_2);
                  tempValue = scaleAndAdd(tempValue, tempValue, m1, f_3);
                  return tempValue;
                };

                _proto.getNoLerp = function getNoLerp() {
                  return this.dataPoint;
                };

                return CubicSplineValueClass;
              }(), _temp), (_descriptor = _applyDecoratedDescriptor(_class2.prototype, "dataPoint", [serializable], {
                configurable: true,
                enumerable: true,
                writable: true,
                initializer: function initializer() {
                  return new constructorX();
                }
              }), _descriptor2 = _applyDecoratedDescriptor(_class2.prototype, "inTangent", [serializable], {
                configurable: true,
                enumerable: true,
                writable: true,
                initializer: function initializer() {
                  return new constructorX();
                }
              }), _descriptor3 = _applyDecoratedDescriptor(_class2.prototype, "outTangent", [serializable], {
                configurable: true,
                enumerable: true,
                writable: true,
                initializer: function initializer() {
                  return new constructorX();
                }
              })), _class2)) || _class);

              if (constructorX === Quat) {
                var _lerp = CubicSplineValueClass.prototype.lerp;

                CubicSplineValueClass.prototype.lerp = function (to, t, dt) {
                  var result = _lerp.call(this, to, t, dt);

                  Quat.normalize(result, result);
                  return result;
                };
              }

              return CubicSplineValueClass;
            }

            var CubicSplineVec2Value = exports('CubicSplineVec2Value', makeCubicSplineValueConstructor('cc.CubicSplineVec2Value', Vec2, Vec2.multiplyScalar, Vec2.scaleAndAdd));
            legacyCC.CubicSplineVec2Value = CubicSplineVec2Value;
            var CubicSplineVec3Value = exports('CubicSplineVec3Value', makeCubicSplineValueConstructor('cc.CubicSplineVec3Value', Vec3, Vec3.multiplyScalar, Vec3.scaleAndAdd));
            legacyCC.CubicSplineVec3Value = CubicSplineVec3Value;
            var CubicSplineVec4Value = exports('CubicSplineVec4Value', makeCubicSplineValueConstructor('cc.CubicSplineVec4Value', Vec4, Vec4.multiplyScalar, Vec4.scaleAndAdd));
            legacyCC.CubicSplineVec4Value = CubicSplineVec4Value;
            var CubicSplineQuatValue = exports('CubicSplineQuatValue', makeCubicSplineValueConstructor('cc.CubicSplineQuatValue', Quat, Quat.multiplyScalar, Quat.scaleAndAdd));
            legacyCC.CubicSplineQuatValue = CubicSplineQuatValue;
            var CubicSplineNumberValue = exports('CubicSplineNumberValue', (_dec2$p = ccclass('cc.CubicSplineNumberValue'), _dec2$p(_class4$5 = (_class5$4 = (_temp2$4 = function () {
              function CubicSplineNumberValue(dataPoint, inTangent, outTangent) {
                _initializerDefineProperty(this, "dataPoint", _descriptor4$c, this);

                _initializerDefineProperty(this, "inTangent", _descriptor5$9, this);

                _initializerDefineProperty(this, "outTangent", _descriptor6$5, this);

                this.dataPoint = dataPoint;
                this.inTangent = inTangent;
                this.outTangent = outTangent;
              }

              var _proto2 = CubicSplineNumberValue.prototype;

              _proto2.lerp = function lerp(to, t, dt) {
                var p0 = this.dataPoint;
                var p1 = to.dataPoint;
                var m0 = this.outTangent * dt;
                var m1 = to.inTangent * dt;
                var t_3 = t * t * t;
                var t_2 = t * t;
                var f_0 = 2 * t_3 - 3 * t_2 + 1;
                var f_1 = t_3 - 2 * t_2 + t;
                var f_2 = -2 * t_3 + 3 * t_2;
                var f_3 = t_3 - t_2;
                return p0 * f_0 + m0 * f_1 + p1 * f_2 + m1 * f_3;
              };

              _proto2.getNoLerp = function getNoLerp() {
                return this.dataPoint;
              };

              return CubicSplineNumberValue;
            }(), _temp2$4), (_descriptor4$c = _applyDecoratedDescriptor(_class5$4.prototype, "dataPoint", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor5$9 = _applyDecoratedDescriptor(_class5$4.prototype, "inTangent", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor6$5 = _applyDecoratedDescriptor(_class5$4.prototype, "outTangent", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            })), _class5$4)) || _class4$5));
            legacyCC.CubicSplineNumberValue = CubicSplineNumberValue;

            var animation = /*#__PURE__*/Object.freeze({
                __proto__: null,
                UniformProxyFactory: UniformProxyFactory,
                MorphWeightsValueProxy: MorphWeightsValueProxy,
                MorphWeightsAllValueProxy: MorphWeightsAllValueProxy,
                isPropertyPath: isPropertyPath,
                isCustomPath: isCustomPath,
                HierarchyPath: HierarchyPath,
                ComponentPath: ComponentPath,
                evaluatePath: evaluatePath,
                CubicSplineVec2Value: CubicSplineVec2Value,
                CubicSplineVec3Value: CubicSplineVec3Value,
                CubicSplineVec4Value: CubicSplineVec4Value,
                CubicSplineQuatValue: CubicSplineQuatValue,
                CubicSplineNumberValue: CubicSplineNumberValue
            });
            exports('animation', animation);

            function binarySearchEpsilon(array, value, EPSILON) {
              if (EPSILON === void 0) {
                EPSILON = 1e-6;
              }

              var low = 0;
              var high = array.length - 1;
              var middle = high >>> 1;

              for (; low <= high; middle = low + high >>> 1) {
                var test = array[middle];

                if (test > value + EPSILON) {
                  high = middle - 1;
                } else if (test < value - EPSILON) {
                  low = middle + 1;
                } else {
                  return middle;
                }
              }

              return ~low;
            }

            function bezier(C1, C2, C3, C4, t) {
              var t1 = 1 - t;
              return t1 * (t1 * (C1 + (C2 * 3 - C1) * t) + C3 * 3 * t * t) + C4 * t * t * t;
            }
            legacyCC.bezier = bezier;
            var cos = Math.cos;
            var acos = Math.acos;
            var max$2 = Math.max;
            var pi = Math.PI;
            var tau = 2 * pi;
            var sqrt = Math.sqrt;

            function crt(v) {
              if (v < 0) {
                return -Math.pow(-v, 1 / 3);
              } else {
                return Math.pow(v, 1 / 3);
              }
            }

            function cardano(curve, x) {
              var pa = x - 0;
              var pb = x - curve[0];
              var pc = x - curve[2];
              var pd = x - 1;
              var pa3 = pa * 3;
              var pb3 = pb * 3;
              var pc3 = pc * 3;
              var d = -pa + pb3 - pc3 + pd;
              var rd = 1 / d;
              var r3 = 1 / 3;
              var a = (pa3 - 6 * pb + pc3) * rd;
              var a3 = a * r3;
              var b = (-pa3 + pb3) * rd;
              var c = pa * rd;
              var p = (3 * b - a * a) * r3;
              var p3 = p * r3;
              var q = (2 * a * a * a - 9 * a * b + 27 * c) / 27;
              var q2 = q / 2;
              var discriminant = q2 * q2 + p3 * p3 * p3;
              var u1;
              var v1;
              var x1;
              var x2;
              var x3;

              if (discriminant < 0) {
                var mp3 = -p * r3;
                var mp33 = mp3 * mp3 * mp3;
                var r = sqrt(mp33);
                var t = -q / (2 * r);
                var cosphi = t < -1 ? -1 : t > 1 ? 1 : t;
                var phi = acos(cosphi);
                var crtr = crt(r);
                var t1 = 2 * crtr;
                x1 = t1 * cos(phi * r3) - a3;
                x2 = t1 * cos((phi + tau) * r3) - a3;
                x3 = t1 * cos((phi + 2 * tau) * r3) - a3;

                if (x1 >= 0 && x1 <= 1) {
                  if (x2 >= 0 && x2 <= 1) {
                    if (x3 >= 0 && x3 <= 1) {
                      return max$2(x1, x2, x3);
                    } else {
                      return max$2(x1, x2);
                    }
                  } else if (x3 >= 0 && x3 <= 1) {
                    return max$2(x1, x3);
                  } else {
                    return x1;
                  }
                } else if (x2 >= 0 && x2 <= 1) {
                  if (x3 >= 0 && x3 <= 1) {
                    return max$2(x2, x3);
                  } else {
                    return x2;
                  }
                } else {
                  return x3;
                }
              } else if (discriminant === 0) {
                u1 = q2 < 0 ? crt(-q2) : -crt(q2);
                x1 = 2 * u1 - a3;
                x2 = -u1 - a3;

                if (x1 >= 0 && x1 <= 1) {
                  if (x2 >= 0 && x2 <= 1) {
                    return max$2(x1, x2);
                  } else {
                    return x1;
                  }
                } else {
                  return x2;
                }
              } else {
                  var sd = sqrt(discriminant);
                  u1 = crt(-q2 + sd);
                  v1 = crt(q2 + sd);
                  x1 = u1 - v1 - a3;
                  return x1;
                }
            }

            function bezierByTime(controlPoints, x) {
              var percent = cardano(controlPoints, x);
              var p1y = controlPoints[1];
              var p2y = controlPoints[3];
              return ((1 - percent) * (p1y + (p2y - p1y) * percent) * 3 + percent * percent) * percent;
            }
            legacyCC.bezierByTime = bezierByTime;

            var RatioSampler = exports('RatioSampler', function () {
              function RatioSampler(ratios) {
                this.ratios = void 0;
                this._findRatio = void 0;
                this.ratios = ratios;
                var currRatioDif;
                var lastRatioDif;
                var canOptimize = true;
                var EPSILON = 1e-6;

                for (var i = 1, l = ratios.length; i < l; i++) {
                  currRatioDif = ratios[i] - ratios[i - 1];

                  if (i === 1) {
                    lastRatioDif = currRatioDif;
                  } else if (Math.abs(currRatioDif - lastRatioDif) > EPSILON) {
                    canOptimize = false;
                    break;
                  }
                }

                this._findRatio = canOptimize ? quickFindIndex : binarySearchEpsilon;
              }

              var _proto = RatioSampler.prototype;

              _proto.sample = function sample(ratio) {
                return this._findRatio(this.ratios, ratio);
              };

              return RatioSampler;
            }());
            legacyCC.RatioSampler = RatioSampler;
            var AnimCurve = exports('AnimCurve', function () {
              AnimCurve.Bezier = function Bezier(controlPoints) {
                return controlPoints;
              };

              function AnimCurve(propertyCurveData, duration) {
                this.types = undefined;
                this.type = null;
                this._values = [];
                this._lerp = undefined;
                this._duration = void 0;
                this._array = void 0;
                this._duration = duration;
                this._values = propertyCurveData.values;

                var getCurveType = function getCurveType(easingMethod) {
                  if (typeof easingMethod === 'string') {
                    return easingMethod;
                  } else if (Array.isArray(easingMethod)) {
                    if (easingMethod[0] === easingMethod[1] && easingMethod[2] === easingMethod[3]) {
                      return AnimCurve.Linear;
                    } else {
                      return AnimCurve.Bezier(easingMethod);
                    }
                  } else {
                    return AnimCurve.Linear;
                  }
                };

                if (propertyCurveData.easingMethod !== undefined) {
                  this.type = getCurveType(propertyCurveData.easingMethod);
                } else if (Array.isArray(propertyCurveData.easingMethods)) {
                  this.types = propertyCurveData.easingMethods.map(getCurveType);
                } else if (propertyCurveData.easingMethods !== undefined) {
                  this.types = new Array(this._values.length).fill(null);

                  for (var _i = 0, _Object$keys = Object.keys(propertyCurveData.easingMethods); _i < _Object$keys.length; _i++) {
                    var index = _Object$keys[_i];
                    this.types[index] = getCurveType(propertyCurveData.easingMethods[index]);
                  }
                } else {
                  this.type = null;
                }

                var firstValue = propertyCurveData.values[0];
                var interpolate = propertyCurveData.interpolate === undefined ? true : propertyCurveData.interpolate;

                if (interpolate) {
                  this._lerp = selectLerpFx(firstValue);
                }

                if (propertyCurveData._arrayLength !== undefined) {
                  this._array = new Array(propertyCurveData._arrayLength);
                }
              }

              var _proto2 = AnimCurve.prototype;

              _proto2.hasLerp = function hasLerp() {
                return !!this._lerp;
              };

              _proto2.valueAt = function valueAt(index) {
                if (this._array === undefined) {
                  var value = this._values[index];

                  if (value && value.getNoLerp) {
                    return value.getNoLerp();
                  } else {
                    return value;
                  }
                } else {
                  for (var i = 0; i < this._array.length; ++i) {
                    this._array[i] = this._values[this._array.length * index + i];
                  }

                  return this._array;
                }
              };

              _proto2.valueBetween = function valueBetween(ratio, from, fromRatio, to, toRatio) {
                if (this._lerp) {
                  var type = this.types ? this.types[from] : this.type;
                  var dRatio = toRatio - fromRatio;
                  var ratioBetweenFrames = (ratio - fromRatio) / dRatio;

                  if (type) {
                    ratioBetweenFrames = computeRatioByType(ratioBetweenFrames, type);
                  }

                  if (this._array === undefined) {
                    var fromVal = this._values[from];
                    var toVal = this._values[to];

                    var value = this._lerp(fromVal, toVal, ratioBetweenFrames, dRatio * this._duration);

                    return value;
                  } else {
                    for (var i = 0; i < this._array.length; ++i) {
                      var _fromVal = this._values[this._array.length * from + i];
                      var _toVal = this._values[this._array.length * to + i];
                      this._array[i] = this._lerp(_fromVal, _toVal, ratioBetweenFrames, dRatio * this._duration);
                    }

                    return this._array;
                  }
                } else if (this._array === undefined) {
                  return this.valueAt(from);
                } else {
                  for (var _i2 = 0; _i2 < this._array.length; ++_i2) {
                    this._array[_i2] = this._values[this._array.length * from + _i2];
                  }

                  return this._array;
                }
              };

              _proto2.empty = function empty() {
                return this._values.length === 0;
              };

              _proto2.constant = function constant() {
                return this._values.length === 1;
              };

              return AnimCurve;
            }());
            AnimCurve.Linear = null;
            legacyCC.AnimCurve = AnimCurve;
            var EventInfo = exports('EventInfo', function () {
              function EventInfo() {
                this.events = [];
              }

              var _proto3 = EventInfo.prototype;

              _proto3.add = function add(func, params) {
                this.events.push({
                  func: func || '',
                  params: params || []
                });
              };

              return EventInfo;
            }());
            function sampleAnimationCurve(curve, sampler, ratio) {
              var index = sampler.sample(ratio);

              if (index < 0) {
                index = ~index;

                if (index <= 0) {
                  index = 0;
                } else if (index >= sampler.ratios.length) {
                  index = sampler.ratios.length - 1;
                } else {
                  return curve.valueBetween(ratio, index - 1, sampler.ratios[index - 1], index, sampler.ratios[index]);
                }
              }

              return curve.valueAt(index);
            }
            legacyCC.sampleAnimationCurve = sampleAnimationCurve;
            function computeRatioByType(ratio, type) {
              if (typeof type === 'string') {
                var func = easing[type];

                if (func) {
                  ratio = func(ratio);
                } else {
                  errorID(3906, type);
                }
              } else if (Array.isArray(type)) {
                ratio = bezierByTime(type, ratio);
              }

              return ratio;
            }

            function quickFindIndex(ratios, ratio) {
              var length = ratios.length - 1;

              if (length === 0) {
                return 0;
              }

              var start = ratios[0];

              if (ratio < start) {
                return 0;
              }

              var end = ratios[length];

              if (ratio > end) {
                return length;
              }

              ratio = (ratio - start) / (end - start);
              var eachLength = 1 / length;
              var index = ratio / eachLength;
              var floorIndex = index | 0;
              var EPSILON = 1e-6;

              if (index - floorIndex < EPSILON) {
                return floorIndex;
              } else if (floorIndex + 1 - index < EPSILON) {
                return floorIndex + 1;
              }

              return ~(floorIndex + 1);
            }

            var selectLerpFx = function () {
              function makeValueTypeLerpFx(constructor) {
                var tempValue = new constructor();
                return function (from, to, ratio) {
                  constructor.lerp(tempValue, from, to, ratio);
                  return tempValue;
                };
              }

              function callLerpable(from, to, t, dt) {
                return from.lerp(to, t, dt);
              }

              function makeQuatSlerpFx() {
                var tempValue = new Quat();
                return function (from, to, t, dt) {
                  return Quat.slerp(tempValue, from, to, t);
                };
              }

              return function (value) {
                if (value === null) {
                  return undefined;
                }

                if (typeof value === 'number') {
                  return lerp;
                } else if (typeof value === 'object' && value.constructor) {
                  if (value instanceof Quat) {
                    return makeQuatSlerpFx();
                  } else if (value instanceof ValueType) {
                    return makeValueTypeLerpFx(value.constructor);
                  } else if (value.constructor === Number) {
                    return lerp;
                  } else if (isLerpable(value)) {
                    return callLerpable;
                  }
                }

                return undefined;
              };
            }();

            var SkelAnimDataHub = function () {
              function SkelAnimDataHub() {}

              SkelAnimDataHub.getOrExtract = function getOrExtract(clip) {
                var data = SkelAnimDataHub.pool.get(clip);

                if (!data || data.info.sample !== clip.sample) {
                  if (data) {
                    legacyCC.director.root.dataPoolManager.releaseAnimationClip(clip);
                  }

                  data = convertToSkeletalCurves(clip);
                  SkelAnimDataHub.pool.set(clip, data);
                }

                return data;
              };

              SkelAnimDataHub.destroy = function destroy(clip) {
                SkelAnimDataHub.pool["delete"](clip);
              };

              return SkelAnimDataHub;
            }();
            SkelAnimDataHub.pool = new Map();

            function convertToSkeletalCurves(clip) {
              var data = {};
              clip.curves.forEach(function (curve) {
                if (!curve.valueAdapter && isCustomPath(curve.modifiers[0], HierarchyPath) && isPropertyPath(curve.modifiers[1])) {
                  var path = curve.modifiers[0].path;
                  var cs = data[path];

                  if (!cs) {
                    cs = data[path] = {};
                  }

                  var property = curve.modifiers[1];
                  cs[property] = {
                    values: curve.data.values,
                    keys: curve.data.keys
                  };
                }
              });
              var frames = Math.ceil(clip.sample * clip.duration) + 1;

              var _loop = function _loop() {
                var path = _Object$keys[_i];
                var props = data[path];

                if (!props) {
                  return "continue";
                }

                Object.defineProperty(props, 'worldMatrix', {
                  get: function get() {
                    if (!props._worldMatrix) {
                      var position = props.position,
                          rotation = props.rotation,
                          scale = props.scale;
                      convertToUniformSample(clip, position, frames);
                      convertToUniformSample(clip, rotation, frames);
                      convertToUniformSample(clip, scale, frames);
                      convertToWorldSpace(data, path, props);
                    }

                    return props._worldMatrix;
                  }
                });
              };

              for (var _i = 0, _Object$keys = Object.keys(data); _i < _Object$keys.length; _i++) {
                var _ret = _loop();

                if (_ret === "continue") continue;
              }

              var info = {
                frames: frames,
                sample: clip.sample
              };
              return {
                info: info,
                data: data
              };
            }

            function convertToUniformSample(clip, curve, frames) {
              var keys = clip.keys[curve.keys];
              var values = [];

              if (!keys || keys.length === 1) {
                for (var i = 0; i < frames; i++) {
                  values[i] = curve.values[0].clone();
                }
              } else {
                var isQuat = curve.values[0] instanceof Quat;

                for (var _i2 = 0, idx = 0; _i2 < frames; _i2++) {
                  var time = _i2 / clip.sample;

                  while (keys[idx] <= time) {
                    idx++;
                  }

                  if (idx > keys.length - 1) {
                    idx = keys.length - 1;
                    time = keys[idx];
                  } else if (idx === 0) {
                    idx = 1;
                  }

                  var from = curve.values[idx - 1].clone();
                  var denom = keys[idx] - keys[idx - 1];
                  var ratio = denom ? clamp01((time - keys[idx - 1]) / denom) : 1;

                  if (isQuat) {
                    from.slerp(curve.values[idx], ratio);
                  } else {
                    from.lerp(curve.values[idx], ratio);
                  }

                  values[_i2] = from;
                }
              }

              curve.values = values;
            }

            function convertToWorldSpace(convertedProps, path, props) {
              var oPos = props.position.values;
              var oRot = props.rotation.values;
              var oScale = props.scale.values;
              var matrix = oPos.map(function () {
                return new Mat4();
              });
              var idx = path.lastIndexOf('/');
              var pMatrix = null;

              if (idx > 0) {
                var name = path.substring(0, idx);
                var data = convertedProps[name];

                if (!data) {
                  console.warn('no data for parent bone?');
                  return;
                }

                pMatrix = data.worldMatrix.values;
              }

              for (var i = 0; i < oPos.length; i++) {
                var oT = oPos[i];
                var oR = oRot[i];
                var oS = oScale[i];
                var m = matrix[i];
                Mat4.fromRTS(m, oR, oT, oS);

                if (pMatrix) {
                  Mat4.multiply(m, pMatrix[i], m);
                }
              }

              Object.keys(props).forEach(function (k) {
                return delete props[k];
              });
              props._worldMatrix = {
                keys: 0,
                interpolate: false,
                values: matrix
              };
            }

            var _dec$K, _class$K, _class2$I, _descriptor$A, _descriptor2$o, _descriptor3$f, _descriptor4$d, _descriptor5$a, _descriptor6$6, _descriptor7$5, _descriptor8$5, _descriptor9$4, _descriptor10$4, _descriptor11$4, _class3$f, _temp$J;
            var AnimationClip = exports('AnimationClip', (_dec$K = ccclass('cc.AnimationClip'), _dec$K(_class$K = (_class2$I = (_temp$J = _class3$f = function (_Asset) {
              _inheritsLoose(AnimationClip, _Asset);

              function AnimationClip() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "sample", _descriptor$A, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "speed", _descriptor2$o, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "wrapMode", _descriptor3$f, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "events", _descriptor4$d, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "enableTrsBlending", _descriptor5$a, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_duration", _descriptor6$6, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_keys", _descriptor7$5, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_stepness", _descriptor8$5, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_curves", _descriptor9$4, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_commonTargets", _descriptor10$4, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_hash", _descriptor11$4, _assertThisInitialized(_this));

                _this.frameRate = 0;
                _this._ratioSamplers = [];
                _this._runtimeCurves = void 0;
                _this._runtimeEvents = void 0;
                _this._data = null;
                return _this;
              }

              AnimationClip.createWithSpriteFrames = function createWithSpriteFrames(spriteFrames, sample) {
                if (!Array.isArray(spriteFrames)) {
                  errorID(3905);
                  return null;
                }

                var clip = new AnimationClip();
                clip.sample = sample || clip.sample;
                clip.duration = spriteFrames.length / clip.sample;
                var step = 1 / clip.sample;
                var keys = new Array(spriteFrames.length);
                var values = new Array(keys.length);

                for (var i = 0; i < spriteFrames.length; i++) {
                  keys[i] = i * step;
                  values[i] = spriteFrames[i];
                }

                clip.keys = [keys];
                clip.curves = [{
                  modifiers: [new ComponentPath('cc.Sprite'), 'spriteFrame'],
                  data: {
                    keys: 0,
                    values: values
                  }
                }];
                return clip;
              };

              var _proto = AnimationClip.prototype;

              _proto.onLoaded = function onLoaded() {
                this.frameRate = this.sample;

                this._decodeCVTAs();
              };

              _proto.getPropertyCurves = function getPropertyCurves() {
                if (!this._runtimeCurves) {
                  this._createPropertyCurves();
                }

                return this._runtimeCurves;
              };

              _proto.updateEventDatas = function updateEventDatas() {
                delete this._runtimeEvents;
              };

              _proto.getEventGroupIndexAtRatio = function getEventGroupIndexAtRatio(ratio) {
                if (!this._runtimeEvents) {
                  this._createRuntimeEvents();
                }

                var result = binarySearchEpsilon(this._runtimeEvents.ratios, ratio);
                return result;
              };

              _proto.hasEvents = function hasEvents() {
                return this.events.length !== 0;
              };

              _proto.destroy = function destroy() {
                if (legacyCC.director.root.dataPoolManager) {
                  legacyCC.director.root.dataPoolManager.releaseAnimationClip(this);
                }

                SkelAnimDataHub.destroy(this);
                return _Asset.prototype.destroy.call(this);
              };

              _proto._createPropertyCurves = function _createPropertyCurves() {
                var _this2 = this;

                this._ratioSamplers = this._keys.map(function (keys) {
                  return new RatioSampler(keys.map(function (key) {
                    return key / _this2._duration;
                  }));
                });
                this._runtimeCurves = this._curves.map(function (targetCurve) {
                  return {
                    curve: new AnimCurve(targetCurve.data, _this2._duration),
                    modifiers: targetCurve.modifiers,
                    valueAdapter: targetCurve.valueAdapter,
                    sampler: _this2._ratioSamplers[targetCurve.data.keys],
                    commonTarget: targetCurve.commonTarget
                  };
                });

                this._applyStepness();
              };

              _proto._createRuntimeEvents = function _createRuntimeEvents() {
                var _this3 = this;

                var ratios = [];
                var eventGroups = [];
                var events = this.events.sort(function (a, b) {
                  return a.frame - b.frame;
                });

                var _loop = function _loop() {
                  var eventData = _step.value;
                  var ratio = eventData.frame / _this3._duration;
                  var i = ratios.findIndex(function (r) {
                    return r === ratio;
                  });

                  if (i < 0) {
                    i = ratios.length;
                    ratios.push(ratio);
                    eventGroups.push({
                      events: []
                    });
                  }

                  eventGroups[i].events.push({
                    functionName: eventData.func,
                    parameters: eventData.params
                  });
                };

                for (var _iterator = _createForOfIteratorHelperLoose(events), _step; !(_step = _iterator()).done;) {
                  _loop();
                }

                this._runtimeEvents = {
                  ratios: ratios,
                  eventGroups: eventGroups
                };
              };

              _proto._applyStepness = function _applyStepness() {};

              _proto._decodeCVTAs = function _decodeCVTAs() {
                var binaryBuffer = ArrayBuffer.isView(this._nativeAsset) ? this._nativeAsset.buffer : this._nativeAsset;

                if (!binaryBuffer) {
                  return;
                }

                var maybeCompressedKeys = this._keys;

                for (var iKey = 0; iKey < maybeCompressedKeys.length; ++iKey) {
                  var keys = maybeCompressedKeys[iKey];

                  if (keys instanceof CompactValueTypeArray) {
                    maybeCompressedKeys[iKey] = keys.decompress(binaryBuffer);
                  }
                }

                for (var iCurve = 0; iCurve < this._curves.length; ++iCurve) {
                  var curve = this._curves[iCurve];

                  if (curve.data.values instanceof CompactValueTypeArray) {
                    curve.data.values = curve.data.values.decompress(binaryBuffer);
                  }
                }
              };

              _proto.validate = function validate() {
                return this.keys.length > 0 && this.curves.length > 0;
              };

              _createClass(AnimationClip, [{
                key: "duration",
                get: function get() {
                  return this._duration;
                },
                set: function set(value) {
                  this._duration = value;
                }
              }, {
                key: "keys",
                get: function get() {
                  return this._keys;
                },
                set: function set(value) {
                  this._keys = value;
                }
              }, {
                key: "eventGroups",
                get: function get() {
                  if (!this._runtimeEvents) {
                    this._createRuntimeEvents();
                  }

                  return this._runtimeEvents.eventGroups;
                }
              }, {
                key: "stepness",
                get: function get() {
                  return this._stepness;
                },
                set: function set(value) {
                  this._stepness = value;

                  this._applyStepness();
                }
              }, {
                key: "hash",
                get: function get() {
                  if (this._hash) {
                    return this._hash;
                  }

                  var data = this._nativeAsset;
                  var buffer = new Uint8Array(ArrayBuffer.isView(data) ? data.buffer : data);
                  return this._hash = murmurhash2_32_gc(buffer, 666);
                }
              }, {
                key: "curves",
                get: function get() {
                  return this._curves;
                },
                set: function set(value) {
                  this._curves = value;
                  delete this._runtimeCurves;
                }
              }, {
                key: "data",
                get: function get() {
                  return this._data;
                }
              }, {
                key: "commonTargets",
                get: function get() {
                  return this._commonTargets;
                },
                set: function set(value) {
                  this._commonTargets = value;
                }
              }]);

              return AnimationClip;
            }(Asset), _class3$f.WrapMode = WrapMode, _temp$J), (_descriptor$A = _applyDecoratedDescriptor(_class2$I.prototype, "sample", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 60;
              }
            }), _descriptor2$o = _applyDecoratedDescriptor(_class2$I.prototype, "speed", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1;
              }
            }), _descriptor3$f = _applyDecoratedDescriptor(_class2$I.prototype, "wrapMode", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return WrapMode.Normal;
              }
            }), _descriptor4$d = _applyDecoratedDescriptor(_class2$I.prototype, "events", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor5$a = _applyDecoratedDescriptor(_class2$I.prototype, "enableTrsBlending", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor6$6 = _applyDecoratedDescriptor(_class2$I.prototype, "_duration", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor7$5 = _applyDecoratedDescriptor(_class2$I.prototype, "_keys", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor8$5 = _applyDecoratedDescriptor(_class2$I.prototype, "_stepness", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor9$4 = _applyDecoratedDescriptor(_class2$I.prototype, "_curves", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor10$4 = _applyDecoratedDescriptor(_class2$I.prototype, "_commonTargets", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor11$4 = _applyDecoratedDescriptor(_class2$I.prototype, "_hash", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            })), _class2$I)) || _class$K));
            legacyCC.AnimationClip = AnimationClip;

            function createBoundTarget(target, modifiers, valueAdapter) {
              var lastPath = modifiers[modifiers.length - 1];

              if (modifiers.length !== 0 && isPropertyPath(lastPath) && !valueAdapter) {
                var resultTarget = evaluatePath.apply(void 0, [target].concat(modifiers.slice(0, modifiers.length - 1)));

                if (resultTarget === null) {
                  return null;
                }

                return new PropertyAccessTarget(resultTarget, lastPath);
              } else if (!valueAdapter) {
                error("Empty animation curve.");
                return null;
              } else {
                var _resultTarget = evaluatePath.apply(void 0, [target].concat(modifiers));

                if (_resultTarget === null) {
                  return null;
                }

                var proxy = valueAdapter.forTarget(_resultTarget);
                return new ProxyTarget(proxy);
              }
            }
            function createBufferedTarget(boundTarget) {
              if (boundTarget === null) {
                return null;
              }

              var value = boundTarget.getValue();
              var copyable = getBuiltinCopy(value);

              if (!copyable) {
                error("Value is not copyable!");
                return null;
              }

              var buffer = copyable.createBuffer();
              var copy = copyable.copy;
              return Object.assign(boundTarget, {
                peek: function peek() {
                  return buffer;
                },
                pull: function pull() {
                  var value = boundTarget.getValue();
                  copy(buffer, value);
                },
                push: function push() {
                  boundTarget.setValue(buffer);
                }
              });
            }

            function SizeCopy(out, source) {
              return out.set(source);
            }

            var getBuiltinCopy = function () {
              var map = new Map();
              map.set(Vec2, {
                createBuffer: function createBuffer() {
                  return new Vec2();
                },
                copy: Vec2.copy
              });
              map.set(Vec3, {
                createBuffer: function createBuffer() {
                  return new Vec3();
                },
                copy: Vec3.copy
              });
              map.set(Vec4, {
                createBuffer: function createBuffer() {
                  return new Vec4();
                },
                copy: Vec4.copy
              });
              map.set(Color, {
                createBuffer: function createBuffer() {
                  return new Color();
                },
                copy: Color.copy
              });
              map.set(Size, {
                createBuffer: function createBuffer() {
                  return new Size();
                },
                copy: SizeCopy
              });
              return function (value) {
                return map.get(value === null || value === void 0 ? void 0 : value.constructor);
              };
            }();

            var PropertyAccessTarget = function () {
              function PropertyAccessTarget(object, propertyName) {
                this._object = void 0;
                this._propertyName = void 0;
                this._object = object;
                this._propertyName = propertyName;
              }

              var _proto = PropertyAccessTarget.prototype;

              _proto.setValue = function setValue(value) {
                this._object[this._propertyName] = value;
              };

              _proto.getValue = function getValue() {
                return this._object[this._propertyName];
              };

              return PropertyAccessTarget;
            }();

            var ProxyTarget = function () {
              function ProxyTarget(proxy) {
                this._proxy = void 0;
                this._proxy = proxy;
              }

              var _proto2 = ProxyTarget.prototype;

              _proto2.setValue = function setValue(value) {
                this._proxy.set(value);
              };

              _proto2.getValue = function getValue() {
                var proxy = this._proxy;

                if (!proxy.get) {
                  error("Target doesn't provide a get method.");
                  return null;
                } else {
                  return proxy.get();
                }
              };

              return ProxyTarget;
            }();

            var Playable = function () {
              function Playable() {
                this._isPlaying = false;
                this._isPaused = false;
                this._stepOnce = false;
              }

              var _proto = Playable.prototype;

              _proto.play = function play() {
                if (this._isPlaying) {
                  if (this._isPaused) {
                    this._isPaused = false;
                    this.onResume();
                  } else {
                    this.onError(getError(3912));
                  }
                } else {
                  this._isPlaying = true;
                  this.onPlay();
                }
              };

              _proto.stop = function stop() {
                if (this._isPlaying) {
                  this._isPlaying = false;
                  this.onStop();
                  this._isPaused = false;
                }
              };

              _proto.pause = function pause() {
                if (this._isPlaying && !this._isPaused) {
                  this._isPaused = true;
                  this.onPause();
                }
              };

              _proto.resume = function resume() {
                if (this._isPlaying && this._isPaused) {
                  this._isPaused = false;
                  this.onResume();
                }
              };

              _proto.step = function step() {
                this.pause();
                this._stepOnce = true;

                if (!this._isPlaying) {
                  this.play();
                }
              };

              _proto.update = function update(deltaTime) {};

              _proto.onPlay = function onPlay() {};

              _proto.onPause = function onPause() {};

              _proto.onResume = function onResume() {};

              _proto.onStop = function onStop() {};

              _proto.onError = function onError(message) {};

              _createClass(Playable, [{
                key: "isPlaying",
                get: function get() {
                  return this._isPlaying;
                }
              }, {
                key: "isPaused",
                get: function get() {
                  return this._isPaused;
                }
              }, {
                key: "isMotionless",
                get: function get() {
                  return !this.isPlaying || this.isPaused;
                }
              }]);

              return Playable;
            }();

            var EventType;

            (function (EventType) {
              EventType["PLAY"] = "play";
              EventType["STOP"] = "stop";
              EventType["PAUSE"] = "pause";
              EventType["RESUME"] = "resume";
              EventType["LASTFRAME"] = "lastframe";
              EventType["FINISHED"] = "finished";
            })(EventType || (EventType = {}));

            ccenum(EventType);
            var ICurveInstance = function () {
              function ICurveInstance(runtimeCurve, target, boundTarget) {
                this.commonTargetIndex = -1;
                this._curve = void 0;
                this._boundTarget = void 0;
                this._curveDetail = void 0;
                this._curve = runtimeCurve.curve;
                this._curveDetail = runtimeCurve;
                this._boundTarget = boundTarget;
                this._shouldLerp = runtimeCurve.curve.hasLerp();
              }

              var _proto = ICurveInstance.prototype;

              _proto.applySample = function applySample(ratio, index, inBetween, samplerResultCache, weight) {
                var value;

                if (!this._shouldLerp || !inBetween) {
                  value = this._curve.valueAt(index);
                } else {
                  value = this._curve.valueBetween(ratio, samplerResultCache.from, samplerResultCache.fromRatio, samplerResultCache.to, samplerResultCache.toRatio);
                }

                this._setValue(value, weight);
              };

              _proto._setValue = function _setValue(value, weight) {
                this._boundTarget.setValue(value);
              };

              _createClass(ICurveInstance, [{
                key: "propertyName",
                get: function get() {
                  return '';
                }
              }, {
                key: "curveDetail",
                get: function get() {
                  return this._curveDetail;
                }
              }]);

              return ICurveInstance;
            }();

            function makeSamplerSharedGroup(sampler) {
              return {
                sampler: sampler,
                curves: [],
                samplerResultCache: {
                  from: 0,
                  fromRatio: 0,
                  to: 0,
                  toRatio: 0
                }
              };
            }

            var InvalidIndex = -1;
            var AnimationState = exports('AnimationState', function (_Playable) {
              _inheritsLoose(AnimationState, _Playable);

              function AnimationState(clip, name) {
                var _this;

                if (name === void 0) {
                  name = '';
                }

                _this = _Playable.call(this) || this;
                _this.duration = 1.0;
                _this.speed = 1.0;
                _this.time = 0.0;
                _this.frameRate = 0;
                _this._targetNode = null;
                _this._curveLoaded = false;
                _this._clip = void 0;
                _this._useSimpleProcess = false;
                _this._samplerSharedGroups = [];
                _this._target = null;
                _this._ignoreIndex = InvalidIndex;
                _this._commonTargetStatuses = [];
                _this._wrapMode = WrapMode.Normal;
                _this._repeatCount = 1;
                _this._delay = 0.0;
                _this._delayTime = 0.0;
                _this._currentFramePlayed = false;
                _this._lastIterations = NaN;
                _this._lastWrapInfo = null;
                _this._lastWrapInfoEvent = null;
                _this._wrappedInfo = new WrappedInfo();
                _this._blendStateBuffer = null;
                _this._blendStateWriters = [];
                _this._allowLastFrame = false;
                _this._blendStateWriterHost = {
                  weight: 0.0
                };
                _this._playbackDuration = 0.0;
                _this._invDuration = 1.0;
                _this._weight = 0.0;
                _this._clipHasEvent = false;
                _this._clip = clip;
                _this._name = name || clip && clip.name;
                _this._playbackRange = {
                  min: 0.0,
                  max: clip.duration
                };
                _this._playbackDuration = clip.duration;

                if (!clip.duration) {
                  debug("Clip " + clip.name + " has zero duration.");
                }

                return _this;
              }

              var _proto2 = AnimationState.prototype;

              _proto2.initialize = function initialize(root, propertyCurves) {
                var _legacyCC$director$ge,
                    _legacyCC$director$ge2,
                    _this2 = this;

                if (this._curveLoaded) {
                  return;
                }

                this._curveLoaded = true;

                this._destroyBlendStateWriters();

                this._samplerSharedGroups.length = 0;
                this._blendStateBuffer = (_legacyCC$director$ge = (_legacyCC$director$ge2 = legacyCC.director.getAnimationManager()) === null || _legacyCC$director$ge2 === void 0 ? void 0 : _legacyCC$director$ge2.blendState) !== null && _legacyCC$director$ge !== void 0 ? _legacyCC$director$ge : null;
                this._targetNode = root;
                var clip = this._clip;
                this.duration = clip.duration;
                this._invDuration = 1.0 / this.duration;
                this.speed = clip.speed;
                this.wrapMode = clip.wrapMode;
                this.frameRate = clip.sample;
                this._playbackRange.min = 0.0;
                this._playbackRange.max = clip.duration;
                this._playbackDuration = clip.duration;
                this._clipHasEvent = clip.hasEvents();

                if ((this.wrapMode & WrapModeMask.Loop) === WrapModeMask.Loop) {
                  this.repeatCount = Infinity;
                } else {
                  this.repeatCount = 1;
                }

                var createBoundTargetOptimized = function createBoundTargetOptimized(rootTarget, path, valueAdapter, isConstant) {
                  if (!clip.enableTrsBlending || !isTargetingTRS(path) || !_this2._blendStateBuffer) {
                    return createBoundTarget(rootTarget, path, valueAdapter);
                  } else {
                    var targetNode = evaluatePath.apply(void 0, [rootTarget].concat(path.slice(0, path.length - 1)));

                    if (targetNode !== null && targetNode instanceof Node$1) {
                      var propertyName = path[path.length - 1];

                      var blendStateWriter = _this2._blendStateBuffer.createWriter(targetNode, propertyName, _this2._blendStateWriterHost, isConstant);

                      _this2._blendStateWriters.push(blendStateWriter);

                      return blendStateWriter;
                    }
                  }

                  return null;
                };

                this._commonTargetStatuses = clip.commonTargets.map(function (commonTarget, index) {
                  var boundTarget = createBoundTargetOptimized(root, commonTarget.modifiers, commonTarget.valueAdapter, false);

                  if (!boundTarget) {
                    return null;
                  }

                  var target = createBufferedTarget(boundTarget);

                  if (target === null) {
                    return null;
                  } else {
                    return {
                      target: target,
                      changed: false
                    };
                  }
                });

                if (!propertyCurves) {
                  propertyCurves = clip.getPropertyCurves();
                }

                var _loop = function _loop(iPropertyCurve) {
                  var propertyCurve = propertyCurves[iPropertyCurve];

                  if (propertyCurve.curve.empty()) {
                    return "continue";
                  }

                  var samplerSharedGroup = _this2._samplerSharedGroups.find(function (value) {
                    return value.sampler === propertyCurve.sampler;
                  });

                  if (!samplerSharedGroup) {
                    samplerSharedGroup = makeSamplerSharedGroup(propertyCurve.sampler);

                    _this2._samplerSharedGroups.push(samplerSharedGroup);
                  }

                  var rootTarget = void 0;

                  if (typeof propertyCurve.commonTarget === 'undefined') {
                    rootTarget = root;
                  } else {
                    var commonTargetStatus = _this2._commonTargetStatuses[propertyCurve.commonTarget];

                    if (!commonTargetStatus) {
                      return "continue";
                    }

                    rootTarget = commonTargetStatus.target.peek();
                  }

                  var boundTarget = createBoundTargetOptimized(rootTarget, propertyCurve.modifiers, propertyCurve.valueAdapter, propertyCurve.curve.constant());

                  if (boundTarget === null) ; else {
                    var _propertyCurve$common;

                    var curveInstance = new ICurveInstance(propertyCurve, rootTarget, boundTarget);
                    curveInstance.commonTargetIndex = (_propertyCurve$common = propertyCurve.commonTarget) !== null && _propertyCurve$common !== void 0 ? _propertyCurve$common : -1;
                    samplerSharedGroup.curves.push(curveInstance);
                  }
                };

                for (var iPropertyCurve = 0; iPropertyCurve < propertyCurves.length; ++iPropertyCurve) {
                  var _ret = _loop(iPropertyCurve);

                  if (_ret === "continue") continue;
                }
              };

              _proto2.destroy = function destroy() {
                this._destroyBlendStateWriters();
              };

              _proto2.emit = function emit() {
                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                legacyCC.director.getAnimationManager().pushDelayEvent(this._emit, this, args);
              };

              _proto2.on = function on(type, callback, target) {
                if (this._target && this._target.isValid) {
                  return this._target.on(type, callback, target);
                } else {
                  return null;
                }
              };

              _proto2.once = function once(type, callback, target) {
                if (this._target && this._target.isValid) {
                  return this._target.once(type, callback, target);
                } else {
                  return null;
                }
              };

              _proto2.off = function off(type, callback, target) {
                if (this._target && this._target.isValid) {
                  this._target.off(type, callback, target);
                }
              };

              _proto2.allowLastFrameEvent = function allowLastFrameEvent(allowed) {
                this._allowLastFrame = allowed;
              };

              _proto2._setEventTarget = function _setEventTarget(target) {
                this._target = target;
              };

              _proto2.setTime = function setTime(time) {
                this._currentFramePlayed = false;
                this.time = time || 0.0;

                {
                  this._lastWrapInfoEvent = null;
                  this._ignoreIndex = InvalidIndex;
                  var info = this.getWrappedInfo(time, this._wrappedInfo);
                  var direction = info.direction;

                  var frameIndex = this._clip.getEventGroupIndexAtRatio(info.ratio);

                  if (frameIndex < 0) {
                    frameIndex = ~frameIndex - 1;

                    if (direction < 0) {
                      frameIndex += 1;
                    }

                    this._ignoreIndex = frameIndex;
                  }
                }
              };

              _proto2.update = function update(delta) {
                if (this._delayTime > 0.0) {
                  this._delayTime -= delta;

                  if (this._delayTime > 0.0) {
                    return;
                  }
                }

                if (this._currentFramePlayed) {
                  this.time += delta * this.speed;
                } else {
                  this._currentFramePlayed = true;
                }

                this._process();
              };

              _proto2.sample = function sample() {
                var info = this.getWrappedInfo(this.time, this._wrappedInfo);

                this._sampleCurves(info.ratio);

                {
                  this._sampleEvents(info);
                }

                return info;
              };

              _proto2.onPlay = function onPlay() {
                this.setTime(0.0);
                this._delayTime = this._delay;

                this._onReplayOrResume();

                this.emit(EventType.PLAY, this);
              };

              _proto2.onStop = function onStop() {
                if (!this.isPaused) {
                  this._onPauseOrStop();
                }

                this.emit(EventType.STOP, this);
              };

              _proto2.onResume = function onResume() {
                this._onReplayOrResume();

                this.emit(EventType.RESUME, this);
              };

              _proto2.onPause = function onPause() {
                this._onPauseOrStop();

                this.emit(EventType.PAUSE, this);
              };

              _proto2._sampleCurves = function _sampleCurves(ratio) {
                var weight = this.weight;
                var commonTargetStatuses = this._commonTargetStatuses;

                for (var iCommonTarget = 0, length = commonTargetStatuses.length; iCommonTarget < length; ++iCommonTarget) {
                  var commonTargetStatus = commonTargetStatuses[iCommonTarget];

                  if (!commonTargetStatus) {
                    continue;
                  }

                  commonTargetStatus.target.pull();
                  commonTargetStatus.changed = false;
                }

                var samplerSharedGroups = this._samplerSharedGroups;
                samplerSharedGroups.forEach(function (samplerSharedGroup) {
                  var sampler = samplerSharedGroup.sampler,
                      samplerResultCache = samplerSharedGroup.samplerResultCache;
                  var index = 0;
                  var lerpRequired = false;

                  if (!sampler) {
                    index = 0;
                  } else {
                    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 {
                        lerpRequired = true;
                        samplerResultCache.from = index - 1;
                        samplerResultCache.fromRatio = sampler.ratios[samplerResultCache.from];
                        samplerResultCache.to = index;
                        samplerResultCache.toRatio = sampler.ratios[samplerResultCache.to];
                        index = samplerResultCache.from;
                      }
                    }
                  }

                  var curves = samplerSharedGroup.curves;

                  for (var iCurveInstance = 0, szCurves = curves.length; iCurveInstance < szCurves; ++iCurveInstance) {
                    var curveInstance = curves[iCurveInstance];
                    curveInstance.applySample(ratio, index, lerpRequired, samplerResultCache, weight);

                    if (curveInstance.commonTargetIndex >= 0) {
                      var _commonTargetStatus = commonTargetStatuses[curveInstance.commonTargetIndex];

                      if (_commonTargetStatus) {
                        _commonTargetStatus.changed = true;
                      }
                    }
                  }
                });

                for (var _iCommonTarget = 0, _length = commonTargetStatuses.length; _iCommonTarget < _length; ++_iCommonTarget) {
                  var _commonTargetStatus2 = commonTargetStatuses[_iCommonTarget];

                  if (!_commonTargetStatus2) {
                    continue;
                  }

                  if (_commonTargetStatus2.changed) {
                    _commonTargetStatus2.target.push();
                  }
                }
              };

              _proto2._process = function _process() {
                if (this._useSimpleProcess) {
                  this.simpleProcess();
                } else {
                  this.process();
                }
              };

              _proto2.process = function process() {
                var info = this.sample();

                if (this._allowLastFrame) {
                  var lastInfo;

                  if (!this._lastWrapInfo) {
                    lastInfo = this._lastWrapInfo = new WrappedInfo(info);
                  } else {
                    lastInfo = this._lastWrapInfo;
                  }

                  if (this.repeatCount > 1 && (info.iterations | 0) > (lastInfo.iterations | 0)) {
                    this.emit(EventType.LASTFRAME, this);
                  }

                  lastInfo.set(info);
                }

                if (info.stopped) {
                  this.stop();
                  this.emit(EventType.FINISHED, this);
                }
              };

              _proto2.simpleProcess = function simpleProcess() {
                var playbackStart = this._playbackRange.min;
                var playbackDuration = this._playbackDuration;
                var time = this.time % playbackDuration;

                if (time < 0.0) {
                  time += playbackDuration;
                }

                var ratio = (playbackStart + time) * this._invDuration;

                this._sampleCurves(ratio);

                {
                  if (this._clipHasEvent) {
                    this._sampleEvents(this.getWrappedInfo(this.time, this._wrappedInfo));
                  }
                }

                if (this._allowLastFrame) {
                  if (Number.isNaN(this._lastIterations)) {
                    this._lastIterations = ratio;
                  }

                  if (this.time > 0 && this._lastIterations > ratio || this.time < 0 && this._lastIterations < ratio) {
                    this.emit(EventType.LASTFRAME, this);
                  }

                  this._lastIterations = ratio;
                }
              };

              _proto2.cache = function cache(frames) {};

              _proto2._needReverse = function _needReverse(currentIterations) {
                var wrapMode = this.wrapMode;
                var needReverse = false;

                if ((wrapMode & WrapModeMask.PingPong) === WrapModeMask.PingPong) {
                  var isEnd = currentIterations - (currentIterations | 0) === 0;

                  if (isEnd && currentIterations > 0) {
                    currentIterations -= 1;
                  }

                  var isOddIteration = currentIterations & 1;

                  if (isOddIteration) {
                    needReverse = !needReverse;
                  }
                }

                if ((wrapMode & WrapModeMask.Reverse) === WrapModeMask.Reverse) {
                  needReverse = !needReverse;
                }

                return needReverse;
              };

              _proto2.getWrappedInfo = function getWrappedInfo(time, info) {
                info = info || new WrappedInfo();

                var playbackStart = this._getPlaybackStart();

                var playbackEnd = this._getPlaybackEnd();

                var playbackDuration = playbackEnd - playbackStart;
                var stopped = false;
                var repeatCount = this.repeatCount;
                var currentIterations = time > 0 ? time / playbackDuration : -(time / playbackDuration);

                if (currentIterations >= repeatCount) {
                  currentIterations = repeatCount;
                  stopped = true;
                  var tempRatio = repeatCount - (repeatCount | 0);

                  if (tempRatio === 0) {
                    tempRatio = 1;
                  }

                  time = tempRatio * playbackDuration * (time > 0 ? 1 : -1);
                }

                if (time > playbackDuration) {
                  var tempTime = time % playbackDuration;
                  time = tempTime === 0 ? playbackDuration : tempTime;
                } else if (time < 0) {
                  time %= playbackDuration;

                  if (time !== 0) {
                    time += playbackDuration;
                  }
                }

                var needReverse = false;
                var shouldWrap = this._wrapMode & WrapModeMask.ShouldWrap;

                if (shouldWrap) {
                  needReverse = this._needReverse(currentIterations);
                }

                var direction = needReverse ? -1 : 1;

                if (this.speed < 0) {
                  direction *= -1;
                }

                if (shouldWrap && needReverse) {
                  time = playbackDuration - time;
                }

                info.time = playbackStart + time;
                info.ratio = info.time / this.duration;
                info.direction = direction;
                info.stopped = stopped;
                info.iterations = currentIterations;
                return info;
              };

              _proto2._getPlaybackStart = function _getPlaybackStart() {
                return this._playbackRange.min;
              };

              _proto2._getPlaybackEnd = function _getPlaybackEnd() {
                return this._playbackRange.max;
              };

              _proto2._sampleEvents = function _sampleEvents(wrapInfo) {
                var length = this._clip.eventGroups.length;
                var direction = wrapInfo.direction;

                var eventIndex = this._clip.getEventGroupIndexAtRatio(wrapInfo.ratio);

                if (eventIndex < 0) {
                  eventIndex = ~eventIndex - 1;

                  if (direction < 0) {
                    eventIndex += 1;
                  }
                }

                if (this._ignoreIndex !== eventIndex) {
                  this._ignoreIndex = InvalidIndex;
                }

                wrapInfo.frameIndex = eventIndex;

                if (!this._lastWrapInfoEvent) {
                  this._fireEvent(eventIndex);

                  this._lastWrapInfoEvent = new WrappedInfo(wrapInfo);
                  return;
                }

                var wrapMode = this.wrapMode;
                var currentIterations = wrapIterations(wrapInfo.iterations);
                var lastWrappedInfo = this._lastWrapInfoEvent;
                var lastIterations = wrapIterations(lastWrappedInfo.iterations);
                var lastIndex = lastWrappedInfo.frameIndex;
                var lastDirection = lastWrappedInfo.direction;
                var iterationsChanged = lastIterations !== -1 && currentIterations !== lastIterations;

                if (lastIndex === eventIndex && iterationsChanged && length === 1) {
                  this._fireEvent(0);
                } else if (lastIndex !== eventIndex || iterationsChanged) {
                  direction = lastDirection;

                  do {
                    if (lastIndex !== eventIndex) {
                      if (direction === -1 && lastIndex === 0 && eventIndex > 0) {
                        if ((wrapMode & WrapModeMask.PingPong) === WrapModeMask.PingPong) {
                          direction *= -1;
                        } else {
                          lastIndex = length;
                        }

                        lastIterations++;
                      } else if (direction === 1 && lastIndex === length - 1 && eventIndex < length - 1) {
                        if ((wrapMode & WrapModeMask.PingPong) === WrapModeMask.PingPong) {
                          direction *= -1;
                        } else {
                          lastIndex = -1;
                        }

                        lastIterations++;
                      }

                      if (lastIndex === eventIndex) {
                        break;
                      }

                      if (lastIterations > currentIterations) {
                        break;
                      }
                    }

                    lastIndex += direction;
                    legacyCC.director.getAnimationManager().pushDelayEvent(this._fireEvent, this, [lastIndex]);
                  } while (lastIndex !== eventIndex && lastIndex > -1 && lastIndex < length);
                }

                this._lastWrapInfoEvent.set(wrapInfo);
              };

              _proto2._emit = function _emit(type, state) {
                if (this._target && this._target.isValid) {
                  this._target.emit(type, type, state);
                }
              };

              _proto2._fireEvent = function _fireEvent(index) {
                if (!this._targetNode || !this._targetNode.isValid) {
                  return;
                }

                var eventGroups = this._clip.eventGroups;

                if (index < 0 || index >= eventGroups.length || this._ignoreIndex === index) {
                  return;
                }

                var eventGroup = eventGroups[index];
                var components = this._targetNode.components;

                for (var _iterator = _createForOfIteratorHelperLoose(eventGroup.events), _step; !(_step = _iterator()).done;) {
                  var event = _step.value;
                  var functionName = event.functionName;

                  for (var _iterator2 = _createForOfIteratorHelperLoose(components), _step2; !(_step2 = _iterator2()).done;) {
                    var component = _step2.value;
                    var fx = component[functionName];

                    if (typeof fx === 'function') {
                      fx.apply(component, event.parameters);
                    }
                  }
                }
              };

              _proto2._onReplayOrResume = function _onReplayOrResume() {
                legacyCC.director.getAnimationManager().addAnimation(this);
              };

              _proto2._onPauseOrStop = function _onPauseOrStop() {
                legacyCC.director.getAnimationManager().removeAnimation(this);
              };

              _proto2._destroyBlendStateWriters = function _destroyBlendStateWriters() {
                if (this._blendStateWriters.length) {
                  assertIsNonNullable(this._blendStateBuffer);
                }

                for (var iBlendStateWriter = 0; iBlendStateWriter < this._blendStateWriters.length; ++iBlendStateWriter) {
                  this._blendStateBuffer.destroyWriter(this._blendStateWriters[iBlendStateWriter]);
                }

                this._blendStateWriters.length = 0;

                if (this._blendStateBuffer) {
                  this._blendStateBuffer = null;
                }
              };

              _createClass(AnimationState, [{
                key: "clip",
                get: function get() {
                  return this._clip;
                }
              }, {
                key: "name",
                get: function get() {
                  return this._name;
                }
              }, {
                key: "length",
                get: function get() {
                  return this.duration;
                }
              }, {
                key: "wrapMode",
                get: function get() {
                  return this._wrapMode;
                },
                set: function set(value) {
                  this._wrapMode = value;

                  this.time = 0;

                  if (value & WrapModeMask.Loop) {
                    this.repeatCount = Infinity;
                  } else {
                    this.repeatCount = 1;
                  }
                }
              }, {
                key: "repeatCount",
                get: function get() {
                  return this._repeatCount;
                },
                set: function set(value) {
                  this._repeatCount = value;
                  var shouldWrap = this._wrapMode & WrapModeMask.ShouldWrap;
                  var reverse = (this.wrapMode & WrapModeMask.Reverse) === WrapModeMask.Reverse;

                  if (value === Infinity && !shouldWrap && !reverse) {
                    this._useSimpleProcess = true;
                  } else {
                    this._useSimpleProcess = false;
                  }
                }
              }, {
                key: "delay",
                get: function get() {
                  return this._delay;
                },
                set: function set(value) {
                  this._delayTime = this._delay = value;
                }
              }, {
                key: "playbackRange",
                get: function get() {
                  return this._playbackRange;
                },
                set: function set(value) {
                  assertIsTrue(value.max > value.min);
                  this._playbackRange.min = Math.max(value.min, 0);
                  this._playbackRange.max = Math.min(value.max, this.duration);
                  this._playbackDuration = this._playbackRange.max - this._playbackRange.min;
                  this.setTime(0.0);
                }
              }, {
                key: "current",
                get: function get() {
                  return this.getWrappedInfo(this.time).time;
                }
              }, {
                key: "ratio",
                get: function get() {
                  return this.current / this.duration;
                }
              }, {
                key: "weight",
                get: function get() {
                  return this._weight;
                },
                set: function set(value) {
                  this._weight = value;
                  this._blendStateWriterHost.weight = value;
                }
              }, {
                key: "curveLoaded",
                get: function get() {
                  return this._curveLoaded;
                }
              }]);

              return AnimationState;
            }(Playable));

            function isTargetingTRS(path) {
              var prs;

              if (path.length === 1 && typeof path[0] === 'string') {
                prs = path[0];
              } else if (path.length > 1) {
                for (var i = 0; i < path.length - 1; ++i) {
                  if (!(path[i] instanceof HierarchyPath)) {
                    return false;
                  }
                }

                prs = path[path.length - 1];
              }

              switch (prs) {
                case 'position':
                case 'scale':
                case 'rotation':
                case 'eulerAngles':
                  return true;

                default:
                  return false;
              }
            }

            function wrapIterations(iterations) {
              if (iterations - (iterations | 0) === 0) {
                iterations -= 1;
              }

              return iterations | 0;
            }

            legacyCC.AnimationState = AnimationState;

            var CrossFade = function (_Playable) {
              _inheritsLoose(CrossFade, _Playable);

              function CrossFade(scheduler) {
                var _this;

                _this = _Playable.call(this) || this;
                _this._managedStates = [];
                _this._fadings = [];
                _this._scheduled = false;
                _this._scheduler = scheduler !== null && scheduler !== void 0 ? scheduler : legacyCC.director.getAnimationManager();
                return _this;
              }

              var _proto = CrossFade.prototype;

              _proto.update = function update(deltaTime) {
                if (this.isMotionless) {
                  return;
                }

                var managedStates = this._managedStates;
                var fadings = this._fadings;

                if (managedStates.length === 1 && fadings.length === 1) {
                  var state = managedStates[0].state;

                  if (state) {
                    state.weight = 1.0;
                  }
                } else {
                  this._calculateWeights(deltaTime);
                }

                if (managedStates.length === 1 && fadings.length === 1) {
                  this._unscheduleThis();
                }
              };

              _proto.crossFade = function crossFade(state, duration) {
                var _target$state;

                if (this._managedStates.length === 0) {
                  duration = 0;
                }

                if (duration === 0) {
                  this.clear();
                }

                var target = this._managedStates.find(function (weightedState) {
                  return weightedState.state === state;
                });

                if (!target) {
                  target = {
                    state: state,
                    reference: 0
                  };

                  if (state) {
                    state.play();
                  }

                  this._managedStates.push(target);
                } else if ((_target$state = target.state) === null || _target$state === void 0 ? void 0 : _target$state.isMotionless) {
                  target.state.play();
                }

                ++target.reference;

                this._fadings.unshift({
                  easeDuration: duration,
                  easeTime: 0,
                  target: target
                });

                if (!this.isMotionless) {
                  this._scheduleThis();
                }
              };

              _proto.clear = function clear() {
                for (var iManagedState = 0; iManagedState < this._managedStates.length; ++iManagedState) {
                  var state = this._managedStates[iManagedState].state;

                  if (state) {
                    state.stop();
                  }
                }

                this._managedStates.length = 0;
                this._fadings.length = 0;
              };

              _proto.onPlay = function onPlay() {
                _Playable.prototype.onPlay.call(this);

                this._scheduleThis();
              };

              _proto.onPause = function onPause() {
                _Playable.prototype.onPause.call(this);

                for (var iManagedState = 0; iManagedState < this._managedStates.length; ++iManagedState) {
                  var state = this._managedStates[iManagedState].state;

                  if (state) {
                    state.pause();
                  }
                }

                this._unscheduleThis();
              };

              _proto.onResume = function onResume() {
                _Playable.prototype.onResume.call(this);

                for (var iManagedState = 0; iManagedState < this._managedStates.length; ++iManagedState) {
                  var state = this._managedStates[iManagedState].state;

                  if (state) {
                    state.resume();
                  }
                }

                this._scheduleThis();
              };

              _proto.onStop = function onStop() {
                _Playable.prototype.onStop.call(this);

                this.clear();
              };

              _proto._calculateWeights = function _calculateWeights(deltaTime) {
                var managedStates = this._managedStates;
                var fadings = this._fadings;

                for (var iManagedState = 0; iManagedState < managedStates.length; ++iManagedState) {
                  var state = managedStates[iManagedState].state;

                  if (state) {
                    state.weight = 0;
                  }
                }

                var absoluteWeight = 1.0;
                var deadFadingBegin = fadings.length;

                for (var iFading = 0; iFading < fadings.length; ++iFading) {
                  var fading = fadings[iFading];
                  fading.easeTime += deltaTime;
                  var relativeWeight = fading.easeDuration === 0 ? 1 : clamp01(fading.easeTime / fading.easeDuration);
                  var weight = relativeWeight * absoluteWeight;
                  absoluteWeight *= 1.0 - relativeWeight;

                  if (fading.target.state) {
                    fading.target.state.weight += weight;
                  }

                  if (fading.easeTime >= fading.easeDuration) {
                    deadFadingBegin = iFading + 1;
                    fading.easeTime = fading.easeDuration;
                    break;
                  }
                }

                if (deadFadingBegin !== fadings.length) {
                  for (var iDeadFading = deadFadingBegin; iDeadFading < fadings.length; ++iDeadFading) {
                    var deadFading = fadings[iDeadFading];
                    --deadFading.target.reference;

                    if (deadFading.target.reference <= 0) {
                      if (deadFading.target.state) {
                        deadFading.target.state.stop();
                      }

                      remove(this._managedStates, deadFading.target);
                    }
                  }

                  fadings.splice(deadFadingBegin);
                }
              };

              _proto._scheduleThis = function _scheduleThis() {
                if (!this._scheduled) {
                  this._scheduler.addCrossFade(this);

                  this._scheduled = true;
                }
              };

              _proto._unscheduleThis = function _unscheduleThis() {
                if (this._scheduled) {
                  this._scheduler.removeCrossFade(this);

                  this._scheduled = false;
                }
              };

              return CrossFade;
            }(Playable);

            var _dec$L, _dec2$q, _dec3$j, _dec4$e, _dec5$b, _dec6$6, _dec7$4, _dec8$4, _dec9$4, _dec10$4, _class$L, _class2$J, _descriptor$B, _descriptor2$p, _descriptor3$g, _class3$g, _temp$K;
            var Animation = function (v) { return exports({ AnimationComponent: v, Animation: v }), v; }((_dec$L = ccclass('cc.Animation'), _dec2$q = help(), _dec3$j = executionOrder(99), _dec4$e = menu(), _dec5$b = type([AnimationClip]), _dec6$6 = tooltip(), _dec7$4 = type(AnimationClip), _dec8$4 = tooltip(), _dec9$4 = tooltip(), _dec10$4 = type([AnimationClip]), _dec$L(_class$L = _dec2$q(_class$L = _dec3$j(_class$L = executeInEditMode(_class$L = _dec4$e(_class$L = (_class2$J = (_temp$K = _class3$g = function (_Eventify) {
              _inheritsLoose(Animation, _Eventify);

              function Animation() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Eventify.call.apply(_Eventify, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "playOnLoad", _descriptor$B, _assertThisInitialized(_this));

                _this._crossFade = new CrossFade();
                _this._nameToState = createMap(true);

                _initializerDefineProperty(_this, "_clips", _descriptor2$p, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_defaultClip", _descriptor3$g, _assertThisInitialized(_this));

                _this._hasBeenPlayed = false;
                return _this;
              }

              var _proto = Animation.prototype;

              _proto.onLoad = function onLoad() {
                this.clips = this._clips;

                for (var stateName in this._nameToState) {
                  var state = this._nameToState[stateName];
                  state.initialize(this.node);
                }
              };

              _proto.start = function start() {
                if ( this.playOnLoad && !this._hasBeenPlayed && this._defaultClip) {
                  this.crossFade(this._defaultClip.name, 0);
                }
              };

              _proto.onEnable = function onEnable() {
                this._crossFade.resume();
              };

              _proto.onDisable = function onDisable() {
                this._crossFade.pause();
              };

              _proto.onDestroy = function onDestroy() {
                this._crossFade.stop();

                for (var name in this._nameToState) {
                  var state = this._nameToState[name];
                  state.destroy();
                }

                this._nameToState = createMap(true);
              };

              _proto.play = function play(name) {
                this._hasBeenPlayed = true;

                if (!name) {
                  if (!this._defaultClip) {
                    return;
                  }

                  name = this._defaultClip.name;
                }

                this.crossFade(name, 0);
              };

              _proto.crossFade = function crossFade(name, duration) {
                if (duration === void 0) {
                  duration = 0.3;
                }

                this._hasBeenPlayed = true;
                var state = this._nameToState[name];

                if (state) {
                  this._crossFade.play();

                  this._crossFade.crossFade(state, duration);
                }
              };

              _proto.pause = function pause() {
                this._crossFade.pause();
              };

              _proto.resume = function resume() {
                this._crossFade.resume();
              };

              _proto.stop = function stop() {
                this._crossFade.stop();
              };

              _proto.getAnimationState = function getAnimationState(name) {
                return this.getState(name);
              };

              _proto.getState = function getState(name) {
                var state = this._nameToState[name];

                if (state && !state.curveLoaded) {
                  state.initialize(this.node);
                }

                return state || null;
              };

              _proto.createState = function createState(clip, name) {
                name = name || clip.name;
                this.removeState(name);
                return this._doCreateState(clip, name);
              };

              _proto.removeState = function removeState(name) {
                var state = this._nameToState[name];

                if (state) {
                  state.allowLastFrameEvent(false);
                  state.stop();
                  delete this._nameToState[name];
                }
              };

              _proto.addClip = function addClip(clip, name) {
                if (!contains(this._clips, clip)) {
                  this._clips.push(clip);
                }

                return this.createState(clip, name);
              };

              _proto.removeClip = function removeClip(clip, force) {
                var removalState;

                for (var name in this._nameToState) {
                  var state = this._nameToState[name];
                  var stateClip = state.clip;

                  if (stateClip === clip) {
                    removalState = state;
                    break;
                  }
                }

                if (clip === this._defaultClip) {
                  if (force) {
                    this._defaultClip = null;
                  } else {
                    {
                      warnID(3902);
                    }

                    return;
                  }
                }

                if (removalState && removalState.isPlaying) {
                  if (force) {
                    removalState.stop();
                  } else {
                    {
                      warnID(3903);
                    }

                    return;
                  }
                }

                this._clips = this._clips.filter(function (item) {
                  return item !== clip;
                });

                if (removalState) {
                  delete this._nameToState[removalState.name];
                }
              };

              _proto.on = function on(type, callback, thisArg, once) {
                var ret = _Eventify.prototype.on.call(this, type, callback, thisArg, once);

                if (type === EventType.LASTFRAME) {
                  this._syncAllowLastFrameEvent();
                }

                return ret;
              };

              _proto.once = function once(type, callback, thisArg) {
                var ret = _Eventify.prototype.once.call(this, type, callback, thisArg);

                if (type === EventType.LASTFRAME) {
                  this._syncAllowLastFrameEvent();
                }

                return ret;
              };

              _proto.off = function off(type, callback, thisArg) {
                _Eventify.prototype.off.call(this, type, callback, thisArg);

                if (type === EventType.LASTFRAME) {
                  this._syncDisallowLastFrameEvent();
                }
              };

              _proto._createState = function _createState(clip, name) {
                return new AnimationState(clip, name);
              };

              _proto._doCreateState = function _doCreateState(clip, name) {
                var state = this._createState(clip, name);

                state._setEventTarget(this);

                state.allowLastFrameEvent(this.hasEventListener(EventType.LASTFRAME));

                if (this.node) {
                  state.initialize(this.node);
                }

                this._nameToState[state.name] = state;
                return state;
              };

              _proto._getStateByNameOrDefaultClip = function _getStateByNameOrDefaultClip(name) {
                if (!name) {
                  if (!this._defaultClip) {
                    return null;
                  }

                  name = this._defaultClip.name;
                }

                var state = this._nameToState[name];

                if (state) {
                  return state;
                }

                return null;
              };

              _proto._removeStateOfAutomaticClip = function _removeStateOfAutomaticClip(clip) {
                for (var name in this._nameToState) {
                  var state = this._nameToState[name];

                  if (equalClips(clip, state.clip)) {
                    state.stop();
                    delete this._nameToState[name];
                  }
                }
              };

              _proto._syncAllowLastFrameEvent = function _syncAllowLastFrameEvent() {
                if (this.hasEventListener(EventType.LASTFRAME)) {
                  for (var stateName in this._nameToState) {
                    this._nameToState[stateName].allowLastFrameEvent(true);
                  }
                }
              };

              _proto._syncDisallowLastFrameEvent = function _syncDisallowLastFrameEvent() {
                if (!this.hasEventListener(EventType.LASTFRAME)) {
                  for (var stateName in this._nameToState) {
                    this._nameToState[stateName].allowLastFrameEvent(false);
                  }
                }
              };

              _createClass(Animation, [{
                key: "clips",
                get: function get() {
                  return this._clips;
                },
                set: function set(value) {
                  var _this2 = this;

                  if (this._crossFade) {
                    this._crossFade.clear();
                  }

                  for (var _iterator = _createForOfIteratorHelperLoose(this._clips), _step; !(_step = _iterator()).done;) {
                    var clip = _step.value;

                    if (clip) {
                      this._removeStateOfAutomaticClip(clip);
                    }
                  }

                  for (var _iterator2 = _createForOfIteratorHelperLoose(value), _step2; !(_step2 = _iterator2()).done;) {
                    var _clip = _step2.value;

                    if (_clip) {
                      this.createState(_clip);
                    }
                  }

                  var newDefaultClip = value.find(function (clip) {
                    return equalClips(clip, _this2._defaultClip);
                  });

                  if (newDefaultClip) {
                    this._defaultClip = newDefaultClip;
                  } else {
                    this._defaultClip = null;
                  }

                  this._clips = value;
                }
              }, {
                key: "defaultClip",
                get: function get() {
                  return this._defaultClip;
                },
                set: function set(value) {
                  this._defaultClip = value;

                  if (!value) {
                    return;
                  }

                  var isBoundedDefaultClip = this._clips.findIndex(function (clip) {
                    return equalClips(clip, value);
                  }) >= 0;

                  if (!isBoundedDefaultClip) {
                    this._clips.push(value);

                    this.createState(value);
                  }
                }
              }]);

              return Animation;
            }(Eventify(Component)), _class3$g.EventType = EventType, _temp$K), (_applyDecoratedDescriptor(_class2$J.prototype, "clips", [_dec5$b, _dec6$6], Object.getOwnPropertyDescriptor(_class2$J.prototype, "clips"), _class2$J.prototype), _applyDecoratedDescriptor(_class2$J.prototype, "defaultClip", [_dec7$4, _dec8$4], Object.getOwnPropertyDescriptor(_class2$J.prototype, "defaultClip"), _class2$J.prototype), _descriptor$B = _applyDecoratedDescriptor(_class2$J.prototype, "playOnLoad", [serializable, _dec9$4], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor2$p = _applyDecoratedDescriptor(_class2$J.prototype, "_clips", [_dec10$4], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor3$g = _applyDecoratedDescriptor(_class2$J.prototype, "_defaultClip", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            })), _class2$J)) || _class$L) || _class$L) || _class$L) || _class$L) || _class$L));

            function equalClips(clip1, clip2) {
              if (clip1 === clip2) {
                return true;
              }

              return !!clip1 && !!clip2 && clip1._uuid === clip2._uuid && clip1._uuid;
            }

            replaceProperty(Animation.prototype, 'Animation', [{
              name: 'getAnimationState',
              newName: 'getState'
            }, {
              name: 'addClip',
              newName: 'createState'
            }, {
              name: 'removeClip',
              newName: 'removeState',
              customFunction: function customFunction() {
                var arg0 = arguments.length <= 0 ? undefined : arguments[0];
                return Animation.prototype.removeState.call(this, arg0.name);
              }
            }]);
            legacyCC.AnimationComponent = Animation;
            js.setClassAlias(Animation, 'cc.AnimationComponent');

            var BlendStateBuffer = function () {
              function BlendStateBuffer() {
                this._nodeBlendStates = new Map();
              }

              var _proto = BlendStateBuffer.prototype;

              _proto.createWriter = function createWriter(node, property, host, constants) {
                var propertyBlendState = this.ref(node, property);
                return new BlendStateWriterInternal(node, property, propertyBlendState, host, constants);
              };

              _proto.destroyWriter = function destroyWriter(writer) {
                var internal = writer;
                this.deRef(internal.node, internal.property);
              };

              _proto.ref = function ref(node, property) {
                var nodeBlendState = this._nodeBlendStates.get(node);

                if (!nodeBlendState) {
                  nodeBlendState = new NodeBlendState();

                  this._nodeBlendStates.set(node, nodeBlendState);
                }

                var propertyBlendState = nodeBlendState.refProperty(property);
                return propertyBlendState;
              };

              _proto.deRef = function deRef(node, property) {
                var nodeBlendState = this._nodeBlendStates.get(node);

                if (!nodeBlendState) {
                  return;
                }

                nodeBlendState.deRefProperty(property);

                if (nodeBlendState.empty) {
                  this._nodeBlendStates["delete"](node);
                }
              };

              _proto.apply = function apply() {
                this._nodeBlendStates.forEach(function (nodeBlendState, node) {
                  nodeBlendState.apply(node);
                });
              };

              return BlendStateBuffer;
            }();

            var BlendStateWriterInternal = function () {
              function BlendStateWriterInternal(_node, _property, _propertyBlendState, _host, _constants) {
                this._node = _node;
                this._property = _property;
                this._propertyBlendState = _propertyBlendState;
                this._host = _host;
                this._constants = _constants;
              }

              var _proto2 = BlendStateWriterInternal.prototype;

              _proto2.getValue = function getValue() {
                return this._node[this._property];
              };

              _proto2.setValue = function setValue(value) {
                var propertyBlendState = this._propertyBlendState,
                    host = this._host;
                var weight = host.weight;
                propertyBlendState.blend(value, weight);
              };

              _createClass(BlendStateWriterInternal, [{
                key: "node",
                get: function get() {
                  return this._node;
                }
              }, {
                key: "property",
                get: function get() {
                  return this._property;
                }
              }]);

              return BlendStateWriterInternal;
            }();

            var PropertyBlendState = function PropertyBlendState(value) {
              this.blendedWeight = 0.0;
              this.blendedValue = void 0;
              this.refCount = 0;
              this.blendedValue = value;
            };

            var Vec3PropertyBlendState = function (_PropertyBlendState) {
              _inheritsLoose(Vec3PropertyBlendState, _PropertyBlendState);

              function Vec3PropertyBlendState() {
                return _PropertyBlendState.call(this, new Vec3()) || this;
              }

              var _proto3 = Vec3PropertyBlendState.prototype;

              _proto3.blend = function blend(value, weight) {
                var blendedValue = this.blendedValue;

                if (weight === 1.0) {
                  Vec3.copy(blendedValue, value);
                } else {
                  Vec3.scaleAndAdd(blendedValue, blendedValue, value, weight);
                }

                this.blendedWeight += weight;
              };

              _proto3.reset = function reset() {
                this.blendedWeight = 0.0;
                Vec3.zero(this.blendedValue);
              };

              return Vec3PropertyBlendState;
            }(PropertyBlendState);

            var QuatPropertyBlendState = function (_PropertyBlendState2) {
              _inheritsLoose(QuatPropertyBlendState, _PropertyBlendState2);

              function QuatPropertyBlendState() {
                return _PropertyBlendState2.call(this, new Quat()) || this;
              }

              var _proto4 = QuatPropertyBlendState.prototype;

              _proto4.blend = function blend(value, weight) {
                if (weight === 0.0) {
                  return;
                }

                var blendedValue = this.blendedValue,
                    blendedWeight = this.blendedWeight;

                if (weight === 1.0) {
                  Quat.copy(blendedValue, value);
                } else {
                  var t = weight / (blendedWeight + weight);
                  Quat.slerp(blendedValue, blendedValue, value, t);
                }

                this.blendedWeight += weight;
              };

              _proto4.reset = function reset() {
                this.blendedWeight = 0.0;
                Quat.identity(this.blendedValue);
              };

              return QuatPropertyBlendState;
            }(PropertyBlendState);

            var NodeBlendState = function () {
              function NodeBlendState() {
                this._properties = {};
              }

              var _proto5 = NodeBlendState.prototype;

              _proto5.refProperty = function refProperty(property) {
                var _properties$property, _properties$property2;

                var properties = this._properties;
                var propertyBlendState;

                switch (property) {
                  default:
                  case 'position':
                  case 'scale':
                  case 'eulerAngles':
                    propertyBlendState = (_properties$property = properties[property]) !== null && _properties$property !== void 0 ? _properties$property : properties[property] = new Vec3PropertyBlendState();
                    break;

                  case 'rotation':
                    propertyBlendState = (_properties$property2 = properties[property]) !== null && _properties$property2 !== void 0 ? _properties$property2 : properties[property] = new QuatPropertyBlendState();
                    break;
                }

                ++propertyBlendState.refCount;
                return propertyBlendState;
              };

              _proto5.deRefProperty = function deRefProperty(property) {
                var properties = this._properties;
                var propertyBlendState = properties[property];

                if (!propertyBlendState) {
                  return;
                }

                --propertyBlendState.refCount;

                if (propertyBlendState.refCount > 0) {
                  return;
                }

                delete properties[property];
              };

              _proto5.apply = function apply(node) {
                var _this$_properties = this._properties,
                    position = _this$_properties.position,
                    scale = _this$_properties.scale,
                    rotation = _this$_properties.rotation,
                    eulerAngles = _this$_properties.eulerAngles;
                var t;
                var s;
                var r;
                var tFlags = false;
                var sFlags = false;
                var rFlags = false;
                var eFlags = false;

                if (position && position.blendedWeight) {
                  tFlags = true;

                  if (position.blendedWeight < 1.0) {
                    position.blend(node.position, 1.0 - position.blendedWeight);
                  }

                  t = position.blendedValue;
                }

                if (scale && scale.blendedWeight) {
                  sFlags = true;

                  if (scale.blendedWeight < 1.0) {
                    scale.blend(node.scale, 1.0 - scale.blendedWeight);
                  }

                  s = scale.blendedValue;
                }

                if (eulerAngles && eulerAngles.blendedWeight) {
                  eFlags = true;

                  if (eulerAngles.blendedWeight < 1.0) {
                    eulerAngles.blend(node.eulerAngles, 1.0 - eulerAngles.blendedWeight);
                  }

                  r = eulerAngles.blendedValue;
                }

                if (rotation && rotation.blendedWeight) {
                  rFlags = true;

                  if (rotation.blendedWeight < 1.0) {
                    rotation.blend(node.rotation, 1.0 - rotation.blendedWeight);
                  }

                  r = rotation.blendedValue;
                }

                if (r || t || s) {
                  node.setRTS(r, t, s);
                }

                if (tFlags) {
                  position.reset();
                }

                if (sFlags) {
                  scale.reset();
                }

                if (rFlags) {
                  rotation.reset();
                }

                if (eFlags) {
                  eulerAngles.reset();
                }
              };

              _createClass(NodeBlendState, [{
                key: "empty",
                get: function get() {
                  var properties = this._properties;
                  return !properties.position && !properties.rotation && !properties.eulerAngles && !properties.scale;
                }
              }]);

              return NodeBlendState;
            }();

            var stack = [];
            var pool = new Map();
            function getWorldMatrix(transform, stamp) {
              var i = 0;
              var res = Mat4.IDENTITY;

              while (transform) {
                if (transform.stamp === stamp || transform.stamp + 1 === stamp && !transform.node.hasChangedFlags) {
                  res = transform.world;
                  transform.stamp = stamp;
                  break;
                }

                transform.stamp = stamp;
                stack[i++] = transform;
                transform = transform.parent;
              }

              while (i > 0) {
                transform = stack[--i];
                var node = transform.node;
                Mat4.fromRTS(transform.local, node.rotation, node.position, node.scale);
                res = Mat4.multiply(transform.world, res, transform.local);
              }

              return res;
            }
            function getTransform(node, root) {
              var joint = null;
              var i = 0;

              while (node !== root) {
                var id = node.uuid;

                if (pool.has(id)) {
                  joint = pool.get(id);
                  break;
                } else {
                  joint = {
                    node: node,
                    local: new Mat4(),
                    world: new Mat4(),
                    stamp: -1,
                    parent: null
                  };
                  pool.set(id, joint);
                }

                stack[i++] = joint;
                node = node.parent;
                joint = null;
              }

              var child;

              while (i > 0) {
                child = stack[--i];
                child.parent = joint;
                joint = child;
              }

              return joint;
            }
            function deleteTransform(node) {
              var transform = pool.get(node.uuid) || null;

              while (transform) {
                pool["delete"](transform.node.uuid);
                transform = transform.parent;
              }
            }

            var _class$M, _class2$K, _temp$L;
            var AnimationManager = exports('AnimationManager', ccclass(_class$M = (_temp$L = _class2$K = function (_System) {
              _inheritsLoose(AnimationManager, _System);

              function AnimationManager() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _System.call.apply(_System, [this].concat(args)) || this;
                _this._anims = new MutableForwardIterator([]);
                _this._crossFades = new MutableForwardIterator([]);
                _this._delayEvents = [];
                _this._blendStateBuffer = new BlendStateBuffer();
                _this._sockets = [];
                return _this;
              }

              var _proto = AnimationManager.prototype;

              _proto.addCrossFade = function addCrossFade(crossFade) {
                var index = this._crossFades.array.indexOf(crossFade);

                if (index === -1) {
                  this._crossFades.push(crossFade);
                }
              };

              _proto.removeCrossFade = function removeCrossFade(crossFade) {
                var index = this._crossFades.array.indexOf(crossFade);

                if (index >= 0) {
                  this._crossFades.fastRemoveAt(index);
                } else {
                  errorID(3907);
                }
              };

              _proto.update = function update(dt) {
                var _delayEvents = this._delayEvents,
                    crossFadesIter = this._crossFades,
                    _sockets = this._sockets;
                {
                  var crossFades = crossFadesIter.array;

                  for (crossFadesIter.i = 0; crossFadesIter.i < crossFades.length; ++crossFadesIter.i) {
                    var crossFade = crossFades[crossFadesIter.i];
                    crossFade.update(dt);
                  }
                }
                var iterator = this._anims;
                var array = iterator.array;

                for (iterator.i = 0; iterator.i < array.length; ++iterator.i) {
                  var anim = array[iterator.i];

                  if (!anim.isMotionless) {
                    anim.update(dt);
                  }
                }

                this._blendStateBuffer.apply();

                var stamp = legacyCC.director.getTotalFrames();

                for (var i = 0, l = _sockets.length; i < l; i++) {
                  var _sockets$i = _sockets[i],
                      target = _sockets$i.target,
                      transform = _sockets$i.transform;
                  target.matrix = getWorldMatrix(transform, stamp);
                }

                for (var _i = 0, _l = _delayEvents.length; _i < _l; _i++) {
                  var event = _delayEvents[_i];
                  event.fn.apply(event.thisArg, event.args);
                }

                _delayEvents.length = 0;
              };

              _proto.destruct = function destruct() {};

              _proto.addAnimation = function addAnimation(anim) {
                var index = this._anims.array.indexOf(anim);

                if (index === -1) {
                  this._anims.push(anim);
                }
              };

              _proto.removeAnimation = function removeAnimation(anim) {
                var index = this._anims.array.indexOf(anim);

                if (index >= 0) {
                  this._anims.fastRemoveAt(index);
                } else {
                  errorID(3907);
                }
              };

              _proto.pushDelayEvent = function pushDelayEvent(fn, thisArg, args) {
                this._delayEvents.push({
                  fn: fn,
                  thisArg: thisArg,
                  args: args
                });
              };

              _proto.addSockets = function addSockets(root, sockets) {
                var _this2 = this;

                var _loop = function _loop(i) {
                  var socket = sockets[i];

                  if (_this2._sockets.find(function (s) {
                    return s.target === socket.target;
                  })) {
                    return "continue";
                  }

                  var targetNode = root.getChildByPath(socket.path);
                  var transform = socket.target && targetNode && getTransform(targetNode, root);

                  if (transform) {
                    _this2._sockets.push({
                      target: socket.target,
                      transform: transform
                    });
                  }
                };

                for (var i = 0; i < sockets.length; ++i) {
                  var _ret = _loop(i);

                  if (_ret === "continue") continue;
                }
              };

              _proto.removeSockets = function removeSockets(root, sockets) {
                for (var i = 0; i < sockets.length; ++i) {
                  var socketToRemove = sockets[i];

                  for (var j = 0; j < this._sockets.length; ++j) {
                    var socket = this._sockets[j];

                    if (socket.target === socketToRemove.target) {
                      deleteTransform(socket.transform.node);
                      this._sockets[j] = this._sockets[this._sockets.length - 1];
                      this._sockets.length--;
                      break;
                    }
                  }
                }
              };

              _createClass(AnimationManager, [{
                key: "blendState",
                get: function get() {
                  return this._blendStateBuffer;
                }
              }]);

              return AnimationManager;
            }(System$1), _class2$K.ID = 'animation', _temp$L)) || _class$M);
            director.on(Director.EVENT_INIT, function () {
              var animationManager = new AnimationManager();
              director.registerSystem(AnimationManager.ID, animationManager, Scheduler.PRIORITY_SYSTEM);
            });
            legacyCC.AnimationManager = AnimationManager;

            var m4_1$2 = new Mat4();
            function getPathFromRoot(target, root) {
              var node = target;
              var path = '';

              while (node !== null && node !== root) {
                path = node.name + "/" + path;
                node = node.parent;
              }

              return path.slice(0, -1);
            }
            function getWorldTransformUntilRoot(target, root, outMatrix) {
              Mat4.identity(outMatrix);

              while (target !== root) {
                Mat4.fromRTS(m4_1$2, target.rotation, target.position, target.scale);
                Mat4.multiply(outMatrix, m4_1$2, outMatrix);
                target = target.parent;
              }

              return outMatrix;
            }

            var _dec$M, _class$N, _dec2$r, _class2$L, _dec3$k, _class3$h, _dec4$f, _class4$6;
            legacyCC.easing = easing;
            var HierachyModifier = exports('HierachyModifier', (_dec$M = ccclass('cc.HierachyModifier'), _dec$M(_class$N = function (_HierarchyPath) {
              _inheritsLoose(HierachyModifier, _HierarchyPath);

              function HierachyModifier() {
                return _HierarchyPath.apply(this, arguments) || this;
              }

              return HierachyModifier;
            }(HierarchyPath)) || _class$N));
            legacyCC.HierachyModifier = HierachyModifier;
            var ComponentModifier = exports('ComponentModifier', (_dec2$r = ccclass('cc.ComponentModifier'), _dec2$r(_class2$L = function (_ComponentPath) {
              _inheritsLoose(ComponentModifier, _ComponentPath);

              function ComponentModifier() {
                return _ComponentPath.apply(this, arguments) || this;
              }

              return ComponentModifier;
            }(ComponentPath)) || _class2$L));
            legacyCC.ComponentModifier = ComponentModifier;
            var CurveValueAdapter = exports('CurveValueAdapter', (_dec3$k = ccclass('cc.CurveValueAdapter'), _dec3$k(_class3$h = function () {
              function CurveValueAdapter() {}

              var _proto = CurveValueAdapter.prototype;

              _proto.forTarget = function forTarget(target) {
                return {
                  set: function set() {}
                };
              };

              return CurveValueAdapter;
            }()) || _class3$h));
            legacyCC.CurveValueAdapter = CurveValueAdapter;
            var UniformCurveValueAdapter = exports('UniformCurveValueAdapter', (_dec4$f = ccclass('cc.UniformCurveValueAdapter'), _dec4$f(_class4$6 = function (_UniformProxyFactory) {
              _inheritsLoose(UniformCurveValueAdapter, _UniformProxyFactory);

              function UniformCurveValueAdapter() {
                return _UniformProxyFactory.apply(this, arguments) || this;
              }

              return UniformCurveValueAdapter;
            }(UniformProxyFactory)) || _class4$6));
            legacyCC.UniformCurveValueAdapter = UniformCurveValueAdapter;
            function isPropertyModifier(path) {
              return typeof path === 'string';
            }
            legacyCC.isPropertyModifier = isPropertyModifier;
            function isElementModifier(path) {
              return typeof path === 'number';
            }
            legacyCC.isElementModifier = isElementModifier;
            function isCustomTargetModifier(path, constructor) {
              return path instanceof constructor;
            }
            legacyCC.isCustomTargetModifier = isCustomTargetModifier;

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

            var NodePool$1 = exports('NodePool', function () {
              function NodePool(poolHandlerComp) {
                this.poolHandlerComp = void 0;
                this._pool = void 0;
                this.poolHandlerComp = poolHandlerComp;
                this._pool = [];
              }

              var _proto = NodePool.prototype;

              _proto.size = function size() {
                return this._pool.length;
              };

              _proto.clear = function clear() {
                var count = this._pool.length;

                for (var i = 0; i < count; ++i) {
                  this._pool[i].destroy();
                }

                this._pool.length = 0;
              };

              _proto.put = function put(obj) {
                if (obj && this._pool.indexOf(obj) === -1) {
                  obj.removeFromParent();
                  var handler = this.poolHandlerComp ? obj.getComponent(this.poolHandlerComp) : null;

                  if (handler && handler.unuse) {
                    handler.unuse();
                  }

                  this._pool.push(obj);
                }
              };

              _proto.get = function get() {
                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                var last = this._pool.length - 1;

                if (last < 0) {
                  return null;
                } else {
                  var obj = this._pool[last];
                  this._pool.length = last;
                  var handler = this.poolHandlerComp ? obj.getComponent(this.poolHandlerComp) : null;

                  if (handler && handler.reuse) {
                    handler.reuse(arguments);
                  }

                  return obj;
                }
              };

              return NodePool;
            }());
            legacyCC.NodePool = NodePool$1;

            legacyCC.renderer = renderer;

            var WebGLDescriptorSet = function (_DescriptorSet) {
              _inheritsLoose(WebGLDescriptorSet, _DescriptorSet);

              function WebGLDescriptorSet() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _DescriptorSet.call.apply(_DescriptorSet, [this].concat(args)) || this;
                _this._gpuDescriptorSet = null;
                return _this;
              }

              var _proto = WebGLDescriptorSet.prototype;

              _proto.initialize = function initialize(info) {
                this._layout = info.layout;
                var _gpuDescriptorSetLayo = info.layout.gpuDescriptorSetLayout,
                    bindings = _gpuDescriptorSetLayo.bindings,
                    descriptorIndices = _gpuDescriptorSetLayo.descriptorIndices,
                    descriptorCount = _gpuDescriptorSetLayo.descriptorCount;
                this._buffers = Array(descriptorCount).fill(null);
                this._textures = Array(descriptorCount).fill(null);
                this._samplers = Array(descriptorCount).fill(null);
                var gpuDescriptors = [];
                this._gpuDescriptorSet = {
                  gpuDescriptors: gpuDescriptors,
                  descriptorIndices: descriptorIndices
                };

                for (var i = 0; i < bindings.length; ++i) {
                  var binding = bindings[i];

                  for (var j = 0; j < binding.count; j++) {
                    gpuDescriptors.push({
                      type: binding.descriptorType,
                      gpuBuffer: null,
                      gpuTexture: null,
                      gpuSampler: null
                    });
                  }
                }

                return true;
              };

              _proto.destroy = function destroy() {
                this._layout = null;
                this._gpuDescriptorSet = null;
              };

              _proto.update = function update() {
                if (this._isDirty && this._gpuDescriptorSet) {
                  var descriptors = this._gpuDescriptorSet.gpuDescriptors;

                  for (var i = 0; i < descriptors.length; ++i) {
                    if (descriptors[i].type & DESCRIPTOR_BUFFER_TYPE) {
                      var buffer = this._buffers[i];

                      if (buffer) {
                        descriptors[i].gpuBuffer = buffer.gpuBuffer || buffer.gpuBufferView;
                      }
                    } else if (descriptors[i].type & DESCRIPTOR_SAMPLER_TYPE) {
                      if (this._textures[i]) {
                        descriptors[i].gpuTexture = this._textures[i].gpuTexture;
                      }

                      if (this._samplers[i]) {
                        descriptors[i].gpuSampler = this._samplers[i].gpuSampler;
                      }
                    }
                  }

                  this._isDirty = false;
                }
              };

              _createClass(WebGLDescriptorSet, [{
                key: "gpuDescriptorSet",
                get: function get() {
                  return this._gpuDescriptorSet;
                }
              }]);

              return WebGLDescriptorSet;
            }(DescriptorSet);

            var WebGLEXT;

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

            function GFXFormatToWebGLType(format, gl) {
              switch (format) {
                case Format.R8:
                  return gl.UNSIGNED_BYTE;

                case Format.R8SN:
                  return gl.BYTE;

                case Format.R8UI:
                  return gl.UNSIGNED_BYTE;

                case Format.R8I:
                  return gl.BYTE;

                case Format.R16F:
                  return WebGLEXT.HALF_FLOAT_OES;

                case Format.R16UI:
                  return gl.UNSIGNED_SHORT;

                case Format.R16I:
                  return gl.SHORT;

                case Format.R32F:
                  return gl.FLOAT;

                case Format.R32UI:
                  return gl.UNSIGNED_INT;

                case Format.R32I:
                  return gl.INT;

                case Format.RG8:
                  return gl.UNSIGNED_BYTE;

                case Format.RG8SN:
                  return gl.BYTE;

                case Format.RG8UI:
                  return gl.UNSIGNED_BYTE;

                case Format.RG8I:
                  return gl.BYTE;

                case Format.RG16F:
                  return WebGLEXT.HALF_FLOAT_OES;

                case Format.RG16UI:
                  return gl.UNSIGNED_SHORT;

                case Format.RG16I:
                  return gl.SHORT;

                case Format.RG32F:
                  return gl.FLOAT;

                case Format.RG32UI:
                  return gl.UNSIGNED_INT;

                case Format.RG32I:
                  return gl.INT;

                case Format.RGB8:
                  return gl.UNSIGNED_BYTE;

                case Format.SRGB8:
                  return gl.UNSIGNED_BYTE;

                case Format.RGB8SN:
                  return gl.BYTE;

                case Format.RGB8UI:
                  return gl.UNSIGNED_BYTE;

                case Format.RGB8I:
                  return gl.BYTE;

                case Format.RGB16F:
                  return WebGLEXT.HALF_FLOAT_OES;

                case Format.RGB16UI:
                  return gl.UNSIGNED_SHORT;

                case Format.RGB16I:
                  return gl.SHORT;

                case Format.RGB32F:
                  return gl.FLOAT;

                case Format.RGB32UI:
                  return gl.UNSIGNED_INT;

                case Format.RGB32I:
                  return gl.INT;

                case Format.BGRA8:
                  return gl.UNSIGNED_BYTE;

                case Format.RGBA8:
                  return gl.UNSIGNED_BYTE;

                case Format.SRGB8_A8:
                  return gl.UNSIGNED_BYTE;

                case Format.RGBA8SN:
                  return gl.BYTE;

                case Format.RGBA8UI:
                  return gl.UNSIGNED_BYTE;

                case Format.RGBA8I:
                  return gl.BYTE;

                case Format.RGBA16F:
                  return WebGLEXT.HALF_FLOAT_OES;

                case Format.RGBA16UI:
                  return gl.UNSIGNED_SHORT;

                case Format.RGBA16I:
                  return gl.SHORT;

                case Format.RGBA32F:
                  return gl.FLOAT;

                case Format.RGBA32UI:
                  return gl.UNSIGNED_INT;

                case Format.RGBA32I:
                  return gl.INT;

                case Format.R5G6B5:
                  return gl.UNSIGNED_SHORT_5_6_5;

                case Format.R11G11B10F:
                  return gl.FLOAT;

                case Format.RGB5A1:
                  return gl.UNSIGNED_SHORT_5_5_5_1;

                case Format.RGBA4:
                  return gl.UNSIGNED_SHORT_4_4_4_4;

                case Format.RGB10A2:
                  return gl.UNSIGNED_BYTE;

                case Format.RGB10A2UI:
                  return gl.UNSIGNED_INT;

                case Format.RGB9E5:
                  return gl.UNSIGNED_BYTE;

                case Format.D16:
                  return gl.UNSIGNED_SHORT;

                case Format.D16S8:
                  return WebGLEXT.UNSIGNED_INT_24_8_WEBGL;

                case Format.D24:
                  return gl.UNSIGNED_INT;

                case Format.D24S8:
                  return WebGLEXT.UNSIGNED_INT_24_8_WEBGL;

                case Format.D32F:
                  return gl.UNSIGNED_INT;

                case Format.D32F_S8:
                  return WebGLEXT.UNSIGNED_INT_24_8_WEBGL;

                case Format.BC1:
                  return gl.UNSIGNED_BYTE;

                case Format.BC1_SRGB:
                  return gl.UNSIGNED_BYTE;

                case Format.BC2:
                  return gl.UNSIGNED_BYTE;

                case Format.BC2_SRGB:
                  return gl.UNSIGNED_BYTE;

                case Format.BC3:
                  return gl.UNSIGNED_BYTE;

                case Format.BC3_SRGB:
                  return gl.UNSIGNED_BYTE;

                case Format.BC4:
                  return gl.UNSIGNED_BYTE;

                case Format.BC4_SNORM:
                  return gl.BYTE;

                case Format.BC5:
                  return gl.UNSIGNED_BYTE;

                case Format.BC5_SNORM:
                  return gl.BYTE;

                case Format.BC6H_SF16:
                  return gl.FLOAT;

                case Format.BC6H_UF16:
                  return gl.FLOAT;

                case Format.BC7:
                  return gl.UNSIGNED_BYTE;

                case Format.BC7_SRGB:
                  return gl.UNSIGNED_BYTE;

                case Format.ETC_RGB8:
                  return gl.UNSIGNED_BYTE;

                case Format.ETC2_RGB8:
                  return gl.UNSIGNED_BYTE;

                case Format.ETC2_SRGB8:
                  return gl.UNSIGNED_BYTE;

                case Format.ETC2_RGB8_A1:
                  return gl.UNSIGNED_BYTE;

                case Format.ETC2_SRGB8_A1:
                  return gl.UNSIGNED_BYTE;

                case Format.EAC_R11:
                  return gl.UNSIGNED_BYTE;

                case Format.EAC_R11SN:
                  return gl.BYTE;

                case Format.EAC_RG11:
                  return gl.UNSIGNED_BYTE;

                case Format.EAC_RG11SN:
                  return gl.BYTE;

                case Format.PVRTC_RGB2:
                  return gl.UNSIGNED_BYTE;

                case Format.PVRTC_RGBA2:
                  return gl.UNSIGNED_BYTE;

                case Format.PVRTC_RGB4:
                  return gl.UNSIGNED_BYTE;

                case Format.PVRTC_RGBA4:
                  return gl.UNSIGNED_BYTE;

                case Format.PVRTC2_2BPP:
                  return gl.UNSIGNED_BYTE;

                case Format.PVRTC2_4BPP:
                  return gl.UNSIGNED_BYTE;

                case Format.ASTC_RGBA_4x4:
                case Format.ASTC_RGBA_5x4:
                case Format.ASTC_RGBA_5x5:
                case Format.ASTC_RGBA_6x5:
                case Format.ASTC_RGBA_6x6:
                case Format.ASTC_RGBA_8x5:
                case Format.ASTC_RGBA_8x6:
                case Format.ASTC_RGBA_8x8:
                case Format.ASTC_RGBA_10x5:
                case Format.ASTC_RGBA_10x6:
                case Format.ASTC_RGBA_10x8:
                case Format.ASTC_RGBA_10x10:
                case Format.ASTC_RGBA_12x10:
                case Format.ASTC_RGBA_12x12:
                case Format.ASTC_SRGBA_4x4:
                case Format.ASTC_SRGBA_5x4:
                case Format.ASTC_SRGBA_5x5:
                case Format.ASTC_SRGBA_6x5:
                case Format.ASTC_SRGBA_6x6:
                case Format.ASTC_SRGBA_8x5:
                case Format.ASTC_SRGBA_8x6:
                case Format.ASTC_SRGBA_8x8:
                case Format.ASTC_SRGBA_10x5:
                case Format.ASTC_SRGBA_10x6:
                case Format.ASTC_SRGBA_10x8:
                case Format.ASTC_SRGBA_10x10:
                case Format.ASTC_SRGBA_12x10:
                case Format.ASTC_SRGBA_12x12:
                  return gl.UNSIGNED_BYTE;

                default:
                  {
                    return gl.UNSIGNED_BYTE;
                  }
              }
            }
            function GFXFormatToWebGLInternalFormat(format, gl) {
              switch (format) {
                case Format.A8:
                  return gl.ALPHA;

                case Format.L8:
                  return gl.LUMINANCE;

                case Format.LA8:
                  return gl.LUMINANCE_ALPHA;

                case Format.RGB8:
                  return gl.RGB;

                case Format.RGB16F:
                  return gl.RGB;

                case Format.RGB32F:
                  return gl.RGB;

                case Format.BGRA8:
                  return gl.RGBA;

                case Format.RGBA8:
                  return gl.RGBA;

                case Format.RGBA16F:
                  return gl.RGBA;

                case Format.RGBA32F:
                  return gl.RGBA;

                case Format.R5G6B5:
                  return gl.RGB565;

                case Format.RGB5A1:
                  return gl.RGB5_A1;

                case Format.RGBA4:
                  return gl.RGBA4;

                case Format.D16:
                  return gl.DEPTH_COMPONENT;

                case Format.D16S8:
                  return gl.DEPTH_STENCIL;

                case Format.D24:
                  return gl.DEPTH_COMPONENT;

                case Format.D24S8:
                  return gl.DEPTH_STENCIL;

                case Format.D32F:
                  return gl.DEPTH_COMPONENT;

                case Format.D32F_S8:
                  return gl.DEPTH_STENCIL;

                case Format.BC1:
                  return WebGLEXT.COMPRESSED_RGB_S3TC_DXT1_EXT;

                case Format.BC1_ALPHA:
                  return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT1_EXT;

                case Format.BC1_SRGB:
                  return WebGLEXT.COMPRESSED_SRGB_S3TC_DXT1_EXT;

                case Format.BC1_SRGB_ALPHA:
                  return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;

                case Format.BC2:
                  return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT3_EXT;

                case Format.BC2_SRGB:
                  return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;

                case Format.BC3:
                  return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT5_EXT;

                case Format.BC3_SRGB:
                  return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;

                case Format.ETC_RGB8:
                  return WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL;

                case Format.ETC2_RGB8:
                  return WebGLEXT.COMPRESSED_RGB8_ETC2;

                case Format.ETC2_SRGB8:
                  return WebGLEXT.COMPRESSED_SRGB8_ETC2;

                case Format.ETC2_RGB8_A1:
                  return WebGLEXT.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2;

                case Format.ETC2_SRGB8_A1:
                  return WebGLEXT.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2;

                case Format.ETC2_RGBA8:
                  return WebGLEXT.COMPRESSED_RGBA8_ETC2_EAC;

                case Format.ETC2_SRGB8_A8:
                  return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC;

                case Format.EAC_R11:
                  return WebGLEXT.COMPRESSED_R11_EAC;

                case Format.EAC_R11SN:
                  return WebGLEXT.COMPRESSED_SIGNED_R11_EAC;

                case Format.EAC_RG11:
                  return WebGLEXT.COMPRESSED_RG11_EAC;

                case Format.EAC_RG11SN:
                  return WebGLEXT.COMPRESSED_SIGNED_RG11_EAC;

                case Format.PVRTC_RGB2:
                  return WebGLEXT.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;

                case Format.PVRTC_RGBA2:
                  return WebGLEXT.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;

                case Format.PVRTC_RGB4:
                  return WebGLEXT.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;

                case Format.PVRTC_RGBA4:
                  return WebGLEXT.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;

                case Format.ASTC_RGBA_4x4:
                  return WebGLEXT.COMPRESSED_RGBA_ASTC_4x4_KHR;

                case Format.ASTC_RGBA_5x4:
                  return WebGLEXT.COMPRESSED_RGBA_ASTC_5x4_KHR;

                case Format.ASTC_RGBA_5x5:
                  return WebGLEXT.COMPRESSED_RGBA_ASTC_5x5_KHR;

                case Format.ASTC_RGBA_6x5:
                  return WebGLEXT.COMPRESSED_RGBA_ASTC_6x5_KHR;

                case Format.ASTC_RGBA_6x6:
                  return WebGLEXT.COMPRESSED_RGBA_ASTC_6x6_KHR;

                case Format.ASTC_RGBA_8x5:
                  return WebGLEXT.COMPRESSED_RGBA_ASTC_8x5_KHR;

                case Format.ASTC_RGBA_8x6:
                  return WebGLEXT.COMPRESSED_RGBA_ASTC_8x6_KHR;

                case Format.ASTC_RGBA_8x8:
                  return WebGLEXT.COMPRESSED_RGBA_ASTC_8x8_KHR;

                case Format.ASTC_RGBA_10x5:
                  return WebGLEXT.COMPRESSED_RGBA_ASTC_10x5_KHR;

                case Format.ASTC_RGBA_10x6:
                  return WebGLEXT.COMPRESSED_RGBA_ASTC_10x6_KHR;

                case Format.ASTC_RGBA_10x8:
                  return WebGLEXT.COMPRESSED_RGBA_ASTC_10x8_KHR;

                case Format.ASTC_RGBA_10x10:
                  return WebGLEXT.COMPRESSED_RGBA_ASTC_10x10_KHR;

                case Format.ASTC_RGBA_12x10:
                  return WebGLEXT.COMPRESSED_RGBA_ASTC_12x10_KHR;

                case Format.ASTC_RGBA_12x12:
                  return WebGLEXT.COMPRESSED_RGBA_ASTC_12x12_KHR;

                case Format.ASTC_SRGBA_4x4:
                  return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;

                case Format.ASTC_SRGBA_5x4:
                  return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR;

                case Format.ASTC_SRGBA_5x5:
                  return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR;

                case Format.ASTC_SRGBA_6x5:
                  return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR;

                case Format.ASTC_SRGBA_6x6:
                  return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR;

                case Format.ASTC_SRGBA_8x5:
                  return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR;

                case Format.ASTC_SRGBA_8x6:
                  return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR;

                case Format.ASTC_SRGBA_8x8:
                  return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR;

                case Format.ASTC_SRGBA_10x5:
                  return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR;

                case Format.ASTC_SRGBA_10x6:
                  return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR;

                case Format.ASTC_SRGBA_10x8:
                  return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR;

                case Format.ASTC_SRGBA_10x10:
                  return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR;

                case Format.ASTC_SRGBA_12x10:
                  return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR;

                case Format.ASTC_SRGBA_12x12:
                  return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR;

                default:
                  {
                    console.error('Unsupported Format, convert to WebGL internal format failed.');
                    return gl.RGBA;
                  }
              }
            }
            function GFXFormatToWebGLFormat(format, gl) {
              switch (format) {
                case Format.A8:
                  return gl.ALPHA;

                case Format.L8:
                  return gl.LUMINANCE;

                case Format.LA8:
                  return gl.LUMINANCE_ALPHA;

                case Format.RGB8:
                  return gl.RGB;

                case Format.RGB16F:
                  return gl.RGB;

                case Format.RGB32F:
                  return gl.RGB;

                case Format.BGRA8:
                  return gl.RGBA;

                case Format.RGBA8:
                  return gl.RGBA;

                case Format.RGBA16F:
                  return gl.RGBA;

                case Format.RGBA32F:
                  return gl.RGBA;

                case Format.R5G6B5:
                  return gl.RGB;

                case Format.RGB5A1:
                  return gl.RGBA;

                case Format.RGBA4:
                  return gl.RGBA;

                case Format.D16:
                  return gl.DEPTH_COMPONENT;

                case Format.D16S8:
                  return gl.DEPTH_STENCIL;

                case Format.D24:
                  return gl.DEPTH_COMPONENT;

                case Format.D24S8:
                  return gl.DEPTH_STENCIL;

                case Format.D32F:
                  return gl.DEPTH_COMPONENT;

                case Format.D32F_S8:
                  return gl.DEPTH_STENCIL;

                case Format.BC1:
                  return WebGLEXT.COMPRESSED_RGB_S3TC_DXT1_EXT;

                case Format.BC1_ALPHA:
                  return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT1_EXT;

                case Format.BC1_SRGB:
                  return WebGLEXT.COMPRESSED_SRGB_S3TC_DXT1_EXT;

                case Format.BC1_SRGB_ALPHA:
                  return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;

                case Format.BC2:
                  return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT3_EXT;

                case Format.BC2_SRGB:
                  return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;

                case Format.BC3:
                  return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT5_EXT;

                case Format.BC3_SRGB:
                  return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;

                case Format.ETC_RGB8:
                  return WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL;

                case Format.ETC2_RGB8:
                  return WebGLEXT.COMPRESSED_RGB8_ETC2;

                case Format.ETC2_SRGB8:
                  return WebGLEXT.COMPRESSED_SRGB8_ETC2;

                case Format.ETC2_RGB8_A1:
                  return WebGLEXT.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2;

                case Format.ETC2_SRGB8_A1:
                  return WebGLEXT.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2;

                case Format.ETC2_RGBA8:
                  return WebGLEXT.COMPRESSED_RGBA8_ETC2_EAC;

                case Format.ETC2_SRGB8_A8:
                  return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC;

                case Format.EAC_R11:
                  return WebGLEXT.COMPRESSED_R11_EAC;

                case Format.EAC_R11SN:
                  return WebGLEXT.COMPRESSED_SIGNED_R11_EAC;

                case Format.EAC_RG11:
                  return WebGLEXT.COMPRESSED_RG11_EAC;

                case Format.EAC_RG11SN:
                  return WebGLEXT.COMPRESSED_SIGNED_RG11_EAC;

                case Format.PVRTC_RGB2:
                  return WebGLEXT.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;

                case Format.PVRTC_RGBA2:
                  return WebGLEXT.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;

                case Format.PVRTC_RGB4:
                  return WebGLEXT.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;

                case Format.PVRTC_RGBA4:
                  return WebGLEXT.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;

                case Format.ASTC_RGBA_4x4:
                  return WebGLEXT.COMPRESSED_RGBA_ASTC_4x4_KHR;

                case Format.ASTC_RGBA_5x4:
                  return WebGLEXT.COMPRESSED_RGBA_ASTC_5x4_KHR;

                case Format.ASTC_RGBA_5x5:
                  return WebGLEXT.COMPRESSED_RGBA_ASTC_5x5_KHR;

                case Format.ASTC_RGBA_6x5:
                  return WebGLEXT.COMPRESSED_RGBA_ASTC_6x5_KHR;

                case Format.ASTC_RGBA_6x6:
                  return WebGLEXT.COMPRESSED_RGBA_ASTC_6x6_KHR;

                case Format.ASTC_RGBA_8x5:
                  return WebGLEXT.COMPRESSED_RGBA_ASTC_8x5_KHR;

                case Format.ASTC_RGBA_8x6:
                  return WebGLEXT.COMPRESSED_RGBA_ASTC_8x6_KHR;

                case Format.ASTC_RGBA_8x8:
                  return WebGLEXT.COMPRESSED_RGBA_ASTC_8x8_KHR;

                case Format.ASTC_RGBA_10x5:
                  return WebGLEXT.COMPRESSED_RGBA_ASTC_10x5_KHR;

                case Format.ASTC_RGBA_10x6:
                  return WebGLEXT.COMPRESSED_RGBA_ASTC_10x6_KHR;

                case Format.ASTC_RGBA_10x8:
                  return WebGLEXT.COMPRESSED_RGBA_ASTC_10x8_KHR;

                case Format.ASTC_RGBA_10x10:
                  return WebGLEXT.COMPRESSED_RGBA_ASTC_10x10_KHR;

                case Format.ASTC_RGBA_12x10:
                  return WebGLEXT.COMPRESSED_RGBA_ASTC_12x10_KHR;

                case Format.ASTC_RGBA_12x12:
                  return WebGLEXT.COMPRESSED_RGBA_ASTC_12x12_KHR;

                case Format.ASTC_SRGBA_4x4:
                  return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;

                case Format.ASTC_SRGBA_5x4:
                  return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR;

                case Format.ASTC_SRGBA_5x5:
                  return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR;

                case Format.ASTC_SRGBA_6x5:
                  return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR;

                case Format.ASTC_SRGBA_6x6:
                  return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR;

                case Format.ASTC_SRGBA_8x5:
                  return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR;

                case Format.ASTC_SRGBA_8x6:
                  return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR;

                case Format.ASTC_SRGBA_8x8:
                  return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR;

                case Format.ASTC_SRGBA_10x5:
                  return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR;

                case Format.ASTC_SRGBA_10x6:
                  return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR;

                case Format.ASTC_SRGBA_10x8:
                  return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR;

                case Format.ASTC_SRGBA_10x10:
                  return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR;

                case Format.ASTC_SRGBA_12x10:
                  return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR;

                case Format.ASTC_SRGBA_12x12:
                  return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR;

                default:
                  {
                    console.error('Unsupported Format, convert to WebGL format failed.');
                    return gl.RGBA;
                  }
              }
            }

            function GFXTypeToWebGLType(type, gl) {
              switch (type) {
                case Type.BOOL:
                  return gl.BOOL;

                case Type.BOOL2:
                  return gl.BOOL_VEC2;

                case Type.BOOL3:
                  return gl.BOOL_VEC3;

                case Type.BOOL4:
                  return gl.BOOL_VEC4;

                case Type.INT:
                  return gl.INT;

                case Type.INT2:
                  return gl.INT_VEC2;

                case Type.INT3:
                  return gl.INT_VEC3;

                case Type.INT4:
                  return gl.INT_VEC4;

                case Type.UINT:
                  return gl.UNSIGNED_INT;

                case Type.FLOAT:
                  return gl.FLOAT;

                case Type.FLOAT2:
                  return gl.FLOAT_VEC2;

                case Type.FLOAT3:
                  return gl.FLOAT_VEC3;

                case Type.FLOAT4:
                  return gl.FLOAT_VEC4;

                case Type.MAT2:
                  return gl.FLOAT_MAT2;

                case Type.MAT3:
                  return gl.FLOAT_MAT3;

                case Type.MAT4:
                  return gl.FLOAT_MAT4;

                case Type.SAMPLER2D:
                  return gl.SAMPLER_2D;

                case Type.SAMPLER_CUBE:
                  return gl.SAMPLER_CUBE;

                default:
                  {
                    console.error('Unsupported GLType, convert to GL type failed.');
                    return Type.UNKNOWN;
                  }
              }
            }

            function GFXTypeToTypedArrayCtor(type) {
              switch (type) {
                case Type.BOOL:
                case Type.BOOL2:
                case Type.BOOL3:
                case Type.BOOL4:
                case Type.INT:
                case Type.INT2:
                case Type.INT3:
                case Type.INT4:
                case Type.UINT:
                  return Int32Array;

                case Type.FLOAT:
                case Type.FLOAT2:
                case Type.FLOAT3:
                case Type.FLOAT4:
                case Type.MAT2:
                case Type.MAT3:
                case Type.MAT4:
                  return Float32Array;

                default:
                  {
                    console.error('Unsupported GLType, convert to TypedArrayConstructor failed.');
                    return Float32Array;
                  }
              }
            }

            function WebGLTypeToGFXType(glType, gl) {
              switch (glType) {
                case gl.BOOL:
                  return Type.BOOL;

                case gl.BOOL_VEC2:
                  return Type.BOOL2;

                case gl.BOOL_VEC3:
                  return Type.BOOL3;

                case gl.BOOL_VEC4:
                  return Type.BOOL4;

                case gl.INT:
                  return Type.INT;

                case gl.INT_VEC2:
                  return Type.INT2;

                case gl.INT_VEC3:
                  return Type.INT3;

                case gl.INT_VEC4:
                  return Type.INT4;

                case gl.UNSIGNED_INT:
                  return Type.UINT;

                case gl.FLOAT:
                  return Type.FLOAT;

                case gl.FLOAT_VEC2:
                  return Type.FLOAT2;

                case gl.FLOAT_VEC3:
                  return Type.FLOAT3;

                case gl.FLOAT_VEC4:
                  return Type.FLOAT4;

                case gl.FLOAT_MAT2:
                  return Type.MAT2;

                case gl.FLOAT_MAT3:
                  return Type.MAT3;

                case gl.FLOAT_MAT4:
                  return Type.MAT4;

                case gl.SAMPLER_2D:
                  return Type.SAMPLER2D;

                case gl.SAMPLER_CUBE:
                  return Type.SAMPLER_CUBE;

                default:
                  {
                    console.error('Unsupported GLType, convert to Type failed.');
                    return Type.UNKNOWN;
                  }
              }
            }

            function WebGLGetTypeSize(glType, gl) {
              switch (glType) {
                case gl.BOOL:
                  return 4;

                case gl.BOOL_VEC2:
                  return 8;

                case gl.BOOL_VEC3:
                  return 12;

                case gl.BOOL_VEC4:
                  return 16;

                case gl.INT:
                  return 4;

                case gl.INT_VEC2:
                  return 8;

                case gl.INT_VEC3:
                  return 12;

                case gl.INT_VEC4:
                  return 16;

                case gl.UNSIGNED_INT:
                  return 4;

                case gl.FLOAT:
                  return 4;

                case gl.FLOAT_VEC2:
                  return 8;

                case gl.FLOAT_VEC3:
                  return 12;

                case gl.FLOAT_VEC4:
                  return 16;

                case gl.FLOAT_MAT2:
                  return 16;

                case gl.FLOAT_MAT3:
                  return 36;

                case gl.FLOAT_MAT4:
                  return 64;

                case gl.SAMPLER_2D:
                  return 4;

                case gl.SAMPLER_CUBE:
                  return 4;

                default:
                  {
                    console.error('Unsupported GLType, get type failed.');
                    return 0;
                  }
              }
            }

            function WebGLGetComponentCount(glType, gl) {
              switch (glType) {
                case gl.FLOAT_MAT2:
                  return 2;

                case gl.FLOAT_MAT3:
                  return 3;

                case gl.FLOAT_MAT4:
                  return 4;

                default:
                  {
                    return 1;
                  }
              }
            }

            var WebGLCmpFuncs = [0x0200, 0x0201, 0x0202, 0x0203, 0x0204, 0x0205, 0x0206, 0x0207];
            var WebGLStencilOps = [0x0000, 0x1E00, 0x1E01, 0x1E02, 0x1E03, 0x150A, 0x8507, 0x8508];
            var WebGLBlendOps = [0x8006, 0x800A, 0x800B, 0x8007, 0x8008];
            var WebGLBlendFactors = [0x0000, 0x0001, 0x0302, 0x0304, 0x0303, 0x0305, 0x0300, 0x0306, 0x0301, 0x0307, 0x0308, 0x8001, 0x8002, 0x8003, 0x8004];
            var WebGLCmd;

            (function (WebGLCmd) {
              WebGLCmd[WebGLCmd["BEGIN_RENDER_PASS"] = 0] = "BEGIN_RENDER_PASS";
              WebGLCmd[WebGLCmd["END_RENDER_PASS"] = 1] = "END_RENDER_PASS";
              WebGLCmd[WebGLCmd["BIND_STATES"] = 2] = "BIND_STATES";
              WebGLCmd[WebGLCmd["DRAW"] = 3] = "DRAW";
              WebGLCmd[WebGLCmd["UPDATE_BUFFER"] = 4] = "UPDATE_BUFFER";
              WebGLCmd[WebGLCmd["COPY_BUFFER_TO_TEXTURE"] = 5] = "COPY_BUFFER_TO_TEXTURE";
              WebGLCmd[WebGLCmd["COUNT"] = 6] = "COUNT";
            })(WebGLCmd || (WebGLCmd = {}));

            var WebGLCmdObject = function WebGLCmdObject(type) {
              this.cmdType = void 0;
              this.refCount = 0;
              this.cmdType = type;
            };
            var WebGLCmdBeginRenderPass = function (_WebGLCmdObject) {
              _inheritsLoose(WebGLCmdBeginRenderPass, _WebGLCmdObject);

              function WebGLCmdBeginRenderPass() {
                var _this;

                _this = _WebGLCmdObject.call(this, WebGLCmd.BEGIN_RENDER_PASS) || this;
                _this.gpuRenderPass = null;
                _this.gpuFramebuffer = null;
                _this.renderArea = new Rect$1();
                _this.clearFlag = ClearFlagBit.NONE;
                _this.clearColors = [];
                _this.clearDepth = 1.0;
                _this.clearStencil = 0;
                return _this;
              }

              var _proto = WebGLCmdBeginRenderPass.prototype;

              _proto.clear = function clear() {
                this.gpuFramebuffer = null;
                this.clearColors.length = 0;
              };

              return WebGLCmdBeginRenderPass;
            }(WebGLCmdObject);
            var WebGLCmdBindStates = function (_WebGLCmdObject2) {
              _inheritsLoose(WebGLCmdBindStates, _WebGLCmdObject2);

              function WebGLCmdBindStates() {
                var _this2;

                _this2 = _WebGLCmdObject2.call(this, WebGLCmd.BIND_STATES) || this;
                _this2.gpuPipelineState = null;
                _this2.gpuInputAssembler = null;
                _this2.gpuDescriptorSets = [];
                _this2.dynamicOffsets = [];
                _this2.dynamicStates = new DynamicStates();
                return _this2;
              }

              var _proto2 = WebGLCmdBindStates.prototype;

              _proto2.clear = function clear() {
                this.gpuPipelineState = null;
                this.gpuDescriptorSets.length = 0;
                this.gpuInputAssembler = null;
                this.dynamicOffsets.length = 0;
              };

              return WebGLCmdBindStates;
            }(WebGLCmdObject);
            var WebGLCmdDraw = function (_WebGLCmdObject3) {
              _inheritsLoose(WebGLCmdDraw, _WebGLCmdObject3);

              function WebGLCmdDraw() {
                var _this3;

                _this3 = _WebGLCmdObject3.call(this, WebGLCmd.DRAW) || this;
                _this3.drawInfo = new DrawInfo();
                return _this3;
              }

              var _proto3 = WebGLCmdDraw.prototype;

              _proto3.clear = function clear() {};

              return WebGLCmdDraw;
            }(WebGLCmdObject);
            var WebGLCmdUpdateBuffer = function (_WebGLCmdObject4) {
              _inheritsLoose(WebGLCmdUpdateBuffer, _WebGLCmdObject4);

              function WebGLCmdUpdateBuffer() {
                var _this4;

                _this4 = _WebGLCmdObject4.call(this, WebGLCmd.UPDATE_BUFFER) || this;
                _this4.gpuBuffer = null;
                _this4.buffer = null;
                _this4.offset = 0;
                _this4.size = 0;
                return _this4;
              }

              var _proto4 = WebGLCmdUpdateBuffer.prototype;

              _proto4.clear = function clear() {
                this.gpuBuffer = null;
                this.buffer = null;
              };

              return WebGLCmdUpdateBuffer;
            }(WebGLCmdObject);
            var WebGLCmdCopyBufferToTexture = function (_WebGLCmdObject5) {
              _inheritsLoose(WebGLCmdCopyBufferToTexture, _WebGLCmdObject5);

              function WebGLCmdCopyBufferToTexture() {
                var _this5;

                _this5 = _WebGLCmdObject5.call(this, WebGLCmd.COPY_BUFFER_TO_TEXTURE) || this;
                _this5.gpuTexture = null;
                _this5.buffers = [];
                _this5.regions = [];
                return _this5;
              }

              var _proto5 = WebGLCmdCopyBufferToTexture.prototype;

              _proto5.clear = function clear() {
                this.gpuTexture = null;
                this.buffers.length = 0;
                this.regions.length = 0;
              };

              return WebGLCmdCopyBufferToTexture;
            }(WebGLCmdObject);
            var WebGLCmdPackage = function () {
              function WebGLCmdPackage() {
                this.cmds = new CachedArray(1);
                this.beginRenderPassCmds = new CachedArray(1);
                this.bindStatesCmds = new CachedArray(1);
                this.drawCmds = new CachedArray(1);
                this.updateBufferCmds = new CachedArray(1);
                this.copyBufferToTextureCmds = new CachedArray(1);
              }

              var _proto6 = WebGLCmdPackage.prototype;

              _proto6.clearCmds = function clearCmds(allocator) {
                if (this.beginRenderPassCmds.length) {
                  allocator.beginRenderPassCmdPool.freeCmds(this.beginRenderPassCmds);
                  this.beginRenderPassCmds.clear();
                }

                if (this.bindStatesCmds.length) {
                  allocator.bindStatesCmdPool.freeCmds(this.bindStatesCmds);
                  this.bindStatesCmds.clear();
                }

                if (this.drawCmds.length) {
                  allocator.drawCmdPool.freeCmds(this.drawCmds);
                  this.drawCmds.clear();
                }

                if (this.updateBufferCmds.length) {
                  allocator.updateBufferCmdPool.freeCmds(this.updateBufferCmds);
                  this.updateBufferCmds.clear();
                }

                if (this.copyBufferToTextureCmds.length) {
                  allocator.copyBufferToTextureCmdPool.freeCmds(this.copyBufferToTextureCmds);
                  this.copyBufferToTextureCmds.clear();
                }

                this.cmds.clear();
              };

              return WebGLCmdPackage;
            }();
            function WebGLCmdFuncCreateBuffer(device, gpuBuffer) {
              var gl = device.gl;
              var cache = device.stateCache;
              var glUsage = gpuBuffer.memUsage & MemoryUsageBit.HOST ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;

              if (gpuBuffer.usage & BufferUsageBit.VERTEX) {
                gpuBuffer.glTarget = gl.ARRAY_BUFFER;
                var glBuffer = gl.createBuffer();

                if (glBuffer) {
                  gpuBuffer.glBuffer = glBuffer;

                  if (gpuBuffer.size > 0) {
                    if (device.useVAO) {
                      if (cache.glVAO) {
                        device.OES_vertex_array_object.bindVertexArrayOES(null);
                        cache.glVAO = gfxStateCache.gpuInputAssembler = null;
                      }
                    }

                    if (device.stateCache.glArrayBuffer !== gpuBuffer.glBuffer) {
                      gl.bindBuffer(gl.ARRAY_BUFFER, gpuBuffer.glBuffer);
                      device.stateCache.glArrayBuffer = gpuBuffer.glBuffer;
                    }

                    gl.bufferData(gl.ARRAY_BUFFER, gpuBuffer.size, glUsage);
                    gl.bindBuffer(gl.ARRAY_BUFFER, null);
                    device.stateCache.glArrayBuffer = null;
                  }
                }
              } else if (gpuBuffer.usage & BufferUsageBit.INDEX) {
                gpuBuffer.glTarget = gl.ELEMENT_ARRAY_BUFFER;

                var _glBuffer = gl.createBuffer();

                if (_glBuffer) {
                  gpuBuffer.glBuffer = _glBuffer;

                  if (gpuBuffer.size > 0) {
                    if (device.useVAO) {
                      if (cache.glVAO) {
                        device.OES_vertex_array_object.bindVertexArrayOES(null);
                        cache.glVAO = gfxStateCache.gpuInputAssembler = null;
                      }
                    }

                    if (device.stateCache.glElementArrayBuffer !== gpuBuffer.glBuffer) {
                      gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer);
                      device.stateCache.glElementArrayBuffer = gpuBuffer.glBuffer;
                    }

                    gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.size, glUsage);
                    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
                    device.stateCache.glElementArrayBuffer = null;
                  }
                }
              } else if (gpuBuffer.usage & BufferUsageBit.UNIFORM) {
                gpuBuffer.glTarget = gl.NONE;

                if (gpuBuffer.buffer) {
                  gpuBuffer.vf32 = new Float32Array(gpuBuffer.buffer.buffer);
                }
              } else if (gpuBuffer.usage & BufferUsageBit.INDIRECT) {
                gpuBuffer.glTarget = gl.NONE;
              } else if (gpuBuffer.usage & BufferUsageBit.TRANSFER_DST) {
                gpuBuffer.glTarget = gl.NONE;
              } else if (gpuBuffer.usage & BufferUsageBit.TRANSFER_SRC) {
                gpuBuffer.glTarget = gl.NONE;
              } else {
                console.error('Unsupported BufferType, create buffer failed.');
                gpuBuffer.glTarget = gl.NONE;
              }
            }
            function WebGLCmdFuncDestroyBuffer(device, gpuBuffer) {
              if (gpuBuffer.glBuffer) {
                device.gl.deleteBuffer(gpuBuffer.glBuffer);
                gpuBuffer.glBuffer = null;
              }
            }
            function WebGLCmdFuncResizeBuffer(device, gpuBuffer) {
              var gl = device.gl;
              var cache = device.stateCache;
              var glUsage = gpuBuffer.memUsage & MemoryUsageBit.HOST ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;

              if (gpuBuffer.usage & BufferUsageBit.VERTEX) {
                if (device.useVAO) {
                  if (cache.glVAO) {
                    device.OES_vertex_array_object.bindVertexArrayOES(null);
                    cache.glVAO = gfxStateCache.gpuInputAssembler = null;
                  }
                }

                if (device.stateCache.glArrayBuffer !== gpuBuffer.glBuffer) {
                  gl.bindBuffer(gl.ARRAY_BUFFER, gpuBuffer.glBuffer);
                }

                if (gpuBuffer.buffer) {
                  gl.bufferData(gl.ARRAY_BUFFER, gpuBuffer.buffer, glUsage);
                } else {
                  gl.bufferData(gl.ARRAY_BUFFER, gpuBuffer.size, glUsage);
                }

                gl.bindBuffer(gl.ARRAY_BUFFER, null);
                device.stateCache.glArrayBuffer = null;
              } else if (gpuBuffer.usage & BufferUsageBit.INDEX) {
                if (device.useVAO) {
                  if (cache.glVAO) {
                    device.OES_vertex_array_object.bindVertexArrayOES(null);
                    cache.glVAO = gfxStateCache.gpuInputAssembler = null;
                  }
                }

                if (device.stateCache.glElementArrayBuffer !== gpuBuffer.glBuffer) {
                  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer);
                }

                if (gpuBuffer.buffer) {
                  gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.buffer, glUsage);
                } else {
                  gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.size, glUsage);
                }

                gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
                device.stateCache.glElementArrayBuffer = null;
              } else if (gpuBuffer.usage & BufferUsageBit.UNIFORM) {
                if (gpuBuffer.buffer) {
                  gpuBuffer.vf32 = new Float32Array(gpuBuffer.buffer.buffer);
                }
              } else if (gpuBuffer.usage & BufferUsageBit.INDIRECT || gpuBuffer.usage & BufferUsageBit.TRANSFER_DST || gpuBuffer.usage & BufferUsageBit.TRANSFER_SRC) {
                gpuBuffer.glTarget = gl.NONE;
              } else {
                console.error('Unsupported BufferType, create buffer failed.');
                gpuBuffer.glTarget = gl.NONE;
              }
            }
            function WebGLCmdFuncUpdateBuffer(device, gpuBuffer, buffer, offset, size) {
              if (gpuBuffer.usage & BufferUsageBit.UNIFORM) {
                if (ArrayBuffer.isView(buffer)) {
                  gpuBuffer.vf32.set(buffer, offset / Float32Array.BYTES_PER_ELEMENT);
                } else {
                  gpuBuffer.vf32.set(new Float32Array(buffer), offset / Float32Array.BYTES_PER_ELEMENT);
                }
              } else if (gpuBuffer.usage & BufferUsageBit.INDIRECT) {
                gpuBuffer.indirects.length = offset;
                Array.prototype.push.apply(gpuBuffer.indirects, buffer.drawInfos);
              } else {
                var buff = buffer;
                var gl = device.gl;
                var cache = device.stateCache;

                switch (gpuBuffer.glTarget) {
                  case gl.ARRAY_BUFFER:
                    {
                      if (device.useVAO) {
                        if (cache.glVAO) {
                          device.OES_vertex_array_object.bindVertexArrayOES(null);
                          cache.glVAO = gfxStateCache.gpuInputAssembler = null;
                        }
                      }

                      if (device.stateCache.glArrayBuffer !== gpuBuffer.glBuffer) {
                        gl.bindBuffer(gl.ARRAY_BUFFER, gpuBuffer.glBuffer);
                        device.stateCache.glArrayBuffer = gpuBuffer.glBuffer;
                      }

                      break;
                    }

                  case gl.ELEMENT_ARRAY_BUFFER:
                    {
                      if (device.useVAO) {
                        if (cache.glVAO) {
                          device.OES_vertex_array_object.bindVertexArrayOES(null);
                          cache.glVAO = gfxStateCache.gpuInputAssembler = null;
                        }
                      }

                      if (device.stateCache.glElementArrayBuffer !== gpuBuffer.glBuffer) {
                        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer);
                        device.stateCache.glElementArrayBuffer = gpuBuffer.glBuffer;
                      }

                      break;
                    }

                  default:
                    {
                      console.error('Unsupported BufferType, update buffer failed.');
                      return;
                    }
                }

                if (size === buff.byteLength) {
                  gl.bufferSubData(gpuBuffer.glTarget, offset, buff);
                } else {
                  gl.bufferSubData(gpuBuffer.glTarget, offset, buff.slice(0, size));
                }
              }
            }
            function WebGLCmdFuncCreateTexture(device, gpuTexture) {
              var gl = device.gl;
              gpuTexture.glInternalFmt = GFXFormatToWebGLInternalFormat(gpuTexture.format, gl);
              gpuTexture.glFormat = GFXFormatToWebGLFormat(gpuTexture.format, gl);
              gpuTexture.glType = GFXFormatToWebGLType(gpuTexture.format, gl);
              var w = gpuTexture.width;
              var h = gpuTexture.height;

              switch (gpuTexture.type) {
                case TextureType.TEX2D:
                  {
                    gpuTexture.glTarget = gl.TEXTURE_2D;
                    var maxSize = Math.max(w, h);

                    if (maxSize > device.capabilities.maxTextureSize) {
                      errorID(9100, maxSize, device.capabilities.maxTextureSize);
                    }

                    if (!device.WEBGL_depth_texture && FormatInfos[gpuTexture.format].hasDepth) {
                      var glRenderbuffer = gl.createRenderbuffer();

                      if (glRenderbuffer && gpuTexture.size > 0) {
                        gpuTexture.glRenderbuffer = glRenderbuffer;

                        if (device.stateCache.glRenderbuffer !== gpuTexture.glRenderbuffer) {
                          gl.bindRenderbuffer(gl.RENDERBUFFER, gpuTexture.glRenderbuffer);
                          device.stateCache.glRenderbuffer = gpuTexture.glRenderbuffer;
                        }

                        if (gpuTexture.glInternalFmt === gl.DEPTH_COMPONENT) {
                          gpuTexture.glInternalFmt = gl.DEPTH_COMPONENT16;
                        }

                        gl.renderbufferStorage(gl.RENDERBUFFER, gpuTexture.glInternalFmt, w, h);
                      }
                    } else if (gpuTexture.samples === SampleCount.X1) {
                      var glTexture = gl.createTexture();

                      if (glTexture && gpuTexture.size > 0) {
                        gpuTexture.glTexture = glTexture;
                        var glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit];

                        if (glTexUnit.glTexture !== gpuTexture.glTexture) {
                          gl.bindTexture(gl.TEXTURE_2D, gpuTexture.glTexture);
                          glTexUnit.glTexture = gpuTexture.glTexture;
                        }

                        if (!FormatInfos[gpuTexture.format].isCompressed) {
                          for (var i = 0; i < gpuTexture.mipLevel; ++i) {
                            gl.texImage2D(gl.TEXTURE_2D, i, gpuTexture.glInternalFmt, w, h, 0, gpuTexture.glFormat, gpuTexture.glType, null);
                            w = Math.max(1, w >> 1);
                            h = Math.max(1, h >> 1);
                          }
                        } else if (gpuTexture.glInternalFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL) {
                          for (var _i = 0; _i < gpuTexture.mipLevel; ++_i) {
                            var imgSize = FormatSize(gpuTexture.format, w, h, 1);
                            var view = new Uint8Array(imgSize);
                            gl.compressedTexImage2D(gl.TEXTURE_2D, _i, gpuTexture.glInternalFmt, w, h, 0, view);
                            w = Math.max(1, w >> 1);
                            h = Math.max(1, h >> 1);
                          }
                        } else {
                          var _imgSize = FormatSize(gpuTexture.format, 2, 2, 1);

                          var _view = new Uint8Array(_imgSize);

                          gl.compressedTexImage2D(gl.TEXTURE_2D, 0, gpuTexture.glInternalFmt, 2, 2, 0, _view);
                        }

                        if (gpuTexture.isPowerOf2) {
                          gpuTexture.glWrapS = gl.REPEAT;
                          gpuTexture.glWrapT = gl.REPEAT;
                        } else {
                          gpuTexture.glWrapS = gl.CLAMP_TO_EDGE;
                          gpuTexture.glWrapT = gl.CLAMP_TO_EDGE;
                        }

                        gpuTexture.glMinFilter = gl.LINEAR;
                        gpuTexture.glMagFilter = gl.LINEAR;
                        gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_WRAP_S, gpuTexture.glWrapS);
                        gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_WRAP_T, gpuTexture.glWrapT);
                        gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_MIN_FILTER, gpuTexture.glMinFilter);
                        gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_MAG_FILTER, gpuTexture.glMagFilter);
                      } else {
                        gl.deleteTexture(glTexture);
                      }
                    }

                    break;
                  }

                case TextureType.CUBE:
                  {
                    gpuTexture.glTarget = gl.TEXTURE_CUBE_MAP;

                    var _maxSize = Math.max(w, h);

                    if (_maxSize > device.capabilities.maxCubeMapTextureSize) {
                      errorID(9100, _maxSize, device.capabilities.maxTextureSize);
                    }

                    var _glTexture = gl.createTexture();

                    if (_glTexture && gpuTexture.size > 0) {
                      gpuTexture.glTexture = _glTexture;
                      var _glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit];

                      if (_glTexUnit.glTexture !== gpuTexture.glTexture) {
                        gl.bindTexture(gl.TEXTURE_CUBE_MAP, gpuTexture.glTexture);
                        _glTexUnit.glTexture = gpuTexture.glTexture;
                      }

                      if (!FormatInfos[gpuTexture.format].isCompressed) {
                        for (var f = 0; f < 6; ++f) {
                          w = gpuTexture.width;
                          h = gpuTexture.height;

                          for (var _i2 = 0; _i2 < gpuTexture.mipLevel; ++_i2) {
                            gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, _i2, gpuTexture.glInternalFmt, w, h, 0, gpuTexture.glFormat, gpuTexture.glType, null);
                            w = Math.max(1, w >> 1);
                            h = Math.max(1, h >> 1);
                          }
                        }
                      } else if (gpuTexture.glInternalFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL) {
                        for (var _f = 0; _f < 6; ++_f) {
                          w = gpuTexture.width;
                          h = gpuTexture.height;

                          for (var _i3 = 0; _i3 < gpuTexture.mipLevel; ++_i3) {
                            var _imgSize2 = FormatSize(gpuTexture.format, w, h, 1);

                            var _view2 = new Uint8Array(_imgSize2);

                            gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + _f, _i3, gpuTexture.glInternalFmt, w, h, 0, _view2);
                            w = Math.max(1, w >> 1);
                            h = Math.max(1, h >> 1);
                          }
                        }
                      } else {
                        for (var _f2 = 0; _f2 < 6; ++_f2) {
                          var _imgSize3 = FormatSize(gpuTexture.format, 2, 2, 1);

                          var _view3 = new Uint8Array(_imgSize3);

                          gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + _f2, 0, gpuTexture.glInternalFmt, 2, 2, 0, _view3);
                        }
                      }

                      if (gpuTexture.isPowerOf2) {
                        gpuTexture.glWrapS = gl.REPEAT;
                        gpuTexture.glWrapT = gl.REPEAT;
                      } else {
                        gpuTexture.glWrapS = gl.CLAMP_TO_EDGE;
                        gpuTexture.glWrapT = gl.CLAMP_TO_EDGE;
                      }

                      gpuTexture.glMinFilter = gl.LINEAR;
                      gpuTexture.glMagFilter = gl.LINEAR;
                      gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_WRAP_S, gpuTexture.glWrapS);
                      gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_WRAP_T, gpuTexture.glWrapT);
                      gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_MIN_FILTER, gpuTexture.glMinFilter);
                      gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_MAG_FILTER, gpuTexture.glMagFilter);
                    }

                    break;
                  }

                default:
                  {
                    console.error('Unsupported TextureType, create texture failed.');
                    gpuTexture.type = TextureType.TEX2D;
                    gpuTexture.glTarget = gl.TEXTURE_2D;
                  }
              }
            }
            function WebGLCmdFuncDestroyTexture(device, gpuTexture) {
              if (gpuTexture.glTexture) {
                device.gl.deleteTexture(gpuTexture.glTexture);
                gpuTexture.glTexture = null;
              }

              if (gpuTexture.glRenderbuffer) {
                device.gl.deleteRenderbuffer(gpuTexture.glRenderbuffer);
                gpuTexture.glRenderbuffer = null;
              }
            }
            function WebGLCmdFuncResizeTexture(device, gpuTexture) {
              var gl = device.gl;
              gpuTexture.glInternalFmt = GFXFormatToWebGLInternalFormat(gpuTexture.format, gl);
              gpuTexture.glFormat = GFXFormatToWebGLFormat(gpuTexture.format, gl);
              gpuTexture.glType = GFXFormatToWebGLType(gpuTexture.format, gl);
              var w = gpuTexture.width;
              var h = gpuTexture.height;

              switch (gpuTexture.type) {
                case TextureType.TEX2D:
                  {
                    gpuTexture.glTarget = gl.TEXTURE_2D;
                    var maxSize = Math.max(w, h);

                    if (maxSize > device.capabilities.maxTextureSize) {
                      errorID(9100, maxSize, device.capabilities.maxTextureSize);
                    }

                    if (gpuTexture.glRenderbuffer) {
                      if (device.stateCache.glRenderbuffer !== gpuTexture.glRenderbuffer) {
                        gl.bindRenderbuffer(gl.RENDERBUFFER, gpuTexture.glRenderbuffer);
                        device.stateCache.glRenderbuffer = gpuTexture.glRenderbuffer;
                      }

                      gl.renderbufferStorage(gl.RENDERBUFFER, gpuTexture.glInternalFmt, w, h);
                    } else if (gpuTexture.glTexture) {
                      var glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit];

                      if (glTexUnit.glTexture !== gpuTexture.glTexture) {
                        gl.bindTexture(gl.TEXTURE_2D, gpuTexture.glTexture);
                        glTexUnit.glTexture = gpuTexture.glTexture;
                      }

                      if (!FormatInfos[gpuTexture.format].isCompressed) {
                        for (var i = 0; i < gpuTexture.mipLevel; ++i) {
                          gl.texImage2D(gl.TEXTURE_2D, i, gpuTexture.glInternalFmt, w, h, 0, gpuTexture.glFormat, gpuTexture.glType, null);
                          w = Math.max(1, w >> 1);
                          h = Math.max(1, h >> 1);
                        }
                      } else if (gpuTexture.glInternalFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL) {
                        for (var _i4 = 0; _i4 < gpuTexture.mipLevel; ++_i4) {
                          var imgSize = FormatSize(gpuTexture.format, w, h, 1);
                          var view = new Uint8Array(imgSize);
                          gl.compressedTexImage2D(gl.TEXTURE_2D, _i4, gpuTexture.glInternalFmt, w, h, 0, view);
                          w = Math.max(1, w >> 1);
                          h = Math.max(1, h >> 1);
                        }
                      }
                    }

                    break;
                  }

                case TextureType.CUBE:
                  {
                    gpuTexture.glTarget = gl.TEXTURE_CUBE_MAP;

                    var _maxSize2 = Math.max(w, h);

                    if (_maxSize2 > device.capabilities.maxCubeMapTextureSize) {
                      errorID(9100, _maxSize2, device.capabilities.maxTextureSize);
                    }

                    var _glTexUnit2 = device.stateCache.glTexUnits[device.stateCache.texUnit];

                    if (_glTexUnit2.glTexture !== gpuTexture.glTexture) {
                      gl.bindTexture(gl.TEXTURE_CUBE_MAP, gpuTexture.glTexture);
                      _glTexUnit2.glTexture = gpuTexture.glTexture;
                    }

                    if (!FormatInfos[gpuTexture.format].isCompressed) {
                      for (var f = 0; f < 6; ++f) {
                        w = gpuTexture.width;
                        h = gpuTexture.height;

                        for (var _i5 = 0; _i5 < gpuTexture.mipLevel; ++_i5) {
                          gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, _i5, gpuTexture.glInternalFmt, w, h, 0, gpuTexture.glFormat, gpuTexture.glType, null);
                          w = Math.max(1, w >> 1);
                          h = Math.max(1, h >> 1);
                        }
                      }
                    } else if (gpuTexture.glInternalFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL) {
                      for (var _f3 = 0; _f3 < 6; ++_f3) {
                        w = gpuTexture.width;
                        h = gpuTexture.height;

                        for (var _i6 = 0; _i6 < gpuTexture.mipLevel; ++_i6) {
                          var _imgSize4 = FormatSize(gpuTexture.format, w, h, 1);

                          var _view4 = new Uint8Array(_imgSize4);

                          gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + _f3, _i6, gpuTexture.glInternalFmt, w, h, 0, _view4);
                          w = Math.max(1, w >> 1);
                          h = Math.max(1, h >> 1);
                        }
                      }
                    }

                    break;
                  }

                default:
                  {
                    console.error('Unsupported TextureType, create texture failed.');
                    gpuTexture.type = TextureType.TEX2D;
                    gpuTexture.glTarget = gl.TEXTURE_2D;
                  }
              }
            }
            function WebGLCmdFuncCreateFramebuffer(device, gpuFramebuffer) {
              if (!gpuFramebuffer.gpuColorTextures.length && !gpuFramebuffer.gpuDepthStencilTexture) {
                return;
              }

              var gl = device.gl;
              var attachments = [];
              var glFramebuffer = gl.createFramebuffer();

              if (glFramebuffer) {
                gpuFramebuffer.glFramebuffer = glFramebuffer;

                if (device.stateCache.glFramebuffer !== gpuFramebuffer.glFramebuffer) {
                  gl.bindFramebuffer(gl.FRAMEBUFFER, gpuFramebuffer.glFramebuffer);
                }

                for (var i = 0; i < gpuFramebuffer.gpuColorTextures.length; ++i) {
                  var gpuTexture = gpuFramebuffer.gpuColorTextures[i];

                  if (gpuTexture) {
                    if (gpuTexture.glTexture) {
                      gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gpuTexture.glTarget, gpuTexture.glTexture, 0);
                    } else {
                      gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, gpuTexture.glRenderbuffer);
                    }

                    attachments.push(gl.COLOR_ATTACHMENT0 + i);
                  }
                }

                var dst = gpuFramebuffer.gpuDepthStencilTexture;

                if (dst) {
                  var glAttachment = FormatInfos[dst.format].hasStencil ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;

                  if (dst.glTexture) {
                    gl.framebufferTexture2D(gl.FRAMEBUFFER, glAttachment, dst.glTarget, dst.glTexture, 0);
                  } else {
                    gl.framebufferRenderbuffer(gl.FRAMEBUFFER, glAttachment, gl.RENDERBUFFER, dst.glRenderbuffer);
                  }
                }

                if (device.WEBGL_draw_buffers) {
                  device.WEBGL_draw_buffers.drawBuffersWEBGL(attachments);
                }

                var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);

                if (status !== gl.FRAMEBUFFER_COMPLETE) {
                  switch (status) {
                    case gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
                      {
                        console.error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_ATTACHMENT');
                        break;
                      }

                    case gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
                      {
                        console.error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT');
                        break;
                      }

                    case gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:
                      {
                        console.error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_DIMENSIONS');
                        break;
                      }

                    case gl.FRAMEBUFFER_UNSUPPORTED:
                      {
                        console.error('glCheckFramebufferStatus() - FRAMEBUFFER_UNSUPPORTED');
                        break;
                      }
                  }
                }

                if (device.stateCache.glFramebuffer !== gpuFramebuffer.glFramebuffer) {
                  gl.bindFramebuffer(gl.FRAMEBUFFER, device.stateCache.glFramebuffer);
                }
              }
            }
            function WebGLCmdFuncDestroyFramebuffer(device, gpuFramebuffer) {
              if (gpuFramebuffer.glFramebuffer) {
                device.gl.deleteFramebuffer(gpuFramebuffer.glFramebuffer);
                gpuFramebuffer.glFramebuffer = null;
              }
            }
            function WebGLCmdFuncCreateShader(device, gpuShader) {
              var gl = device.gl;

              var _loop = function _loop(k) {
                var gpuStage = gpuShader.gpuStages[k];
                var glShaderType = 0;
                var shaderTypeStr = '';
                var lineNumber = 1;

                switch (gpuStage.type) {
                  case ShaderStageFlagBit.VERTEX:
                    {
                      shaderTypeStr = 'VertexShader';
                      glShaderType = gl.VERTEX_SHADER;
                      break;
                    }

                  case ShaderStageFlagBit.FRAGMENT:
                    {
                      shaderTypeStr = 'FragmentShader';
                      glShaderType = gl.FRAGMENT_SHADER;
                      break;
                    }

                  default:
                    {
                      console.error('Unsupported ShaderType.');
                      return {
                        v: void 0
                      };
                    }
                }

                var glShader = gl.createShader(glShaderType);

                if (glShader) {
                  gpuStage.glShader = glShader;
                  gl.shaderSource(gpuStage.glShader, gpuStage.source);
                  gl.compileShader(gpuStage.glShader);

                  if (!gl.getShaderParameter(gpuStage.glShader, gl.COMPILE_STATUS)) {
                    console.error(shaderTypeStr + " in '" + gpuShader.name + "' compilation failed.");
                    console.error('Shader source dump:', gpuStage.source.replace(/^|\n/g, function () {
                      return "\n" + lineNumber++ + " ";
                    }));
                    console.error(gl.getShaderInfoLog(gpuStage.glShader));

                    for (var l = 0; l < gpuShader.gpuStages.length; l++) {
                      var stage = gpuShader.gpuStages[k];

                      if (stage.glShader) {
                        gl.deleteShader(stage.glShader);
                        stage.glShader = null;
                      }
                    }

                    return {
                      v: void 0
                    };
                  }
                }
              };

              for (var k = 0; k < gpuShader.gpuStages.length; k++) {
                var _ret = _loop(k);

                if (typeof _ret === "object") return _ret.v;
              }

              var glProgram = gl.createProgram();

              if (!glProgram) {
                return;
              }

              gpuShader.glProgram = glProgram;

              for (var _k = 0; _k < gpuShader.gpuStages.length; _k++) {
                var gpuStage = gpuShader.gpuStages[_k];
                gl.attachShader(gpuShader.glProgram, gpuStage.glShader);
              }

              gl.linkProgram(gpuShader.glProgram);

              if (device.destroyShadersImmediately) {
                for (var _k2 = 0; _k2 < gpuShader.gpuStages.length; _k2++) {
                  var _gpuStage = gpuShader.gpuStages[_k2];

                  if (_gpuStage.glShader) {
                    gl.detachShader(gpuShader.glProgram, _gpuStage.glShader);
                    gl.deleteShader(_gpuStage.glShader);
                    _gpuStage.glShader = null;
                  }
                }
              }

              if (gl.getProgramParameter(gpuShader.glProgram, gl.LINK_STATUS)) {
                console.info("Shader '" + gpuShader.name + "' compilation succeeded.");
              } else {
                console.error("Failed to link shader '" + gpuShader.name + "'.");
                console.error(gl.getProgramInfoLog(gpuShader.glProgram));
                return;
              }

              var activeAttribCount = gl.getProgramParameter(gpuShader.glProgram, gl.ACTIVE_ATTRIBUTES);
              gpuShader.glInputs = new Array(activeAttribCount);

              for (var i = 0; i < activeAttribCount; ++i) {
                var attribInfo = gl.getActiveAttrib(gpuShader.glProgram, i);

                if (attribInfo) {
                  var varName = void 0;
                  var nameOffset = attribInfo.name.indexOf('[');

                  if (nameOffset !== -1) {
                    varName = attribInfo.name.substr(0, nameOffset);
                  } else {
                    varName = attribInfo.name;
                  }

                  var glLoc = gl.getAttribLocation(gpuShader.glProgram, varName);
                  var type = WebGLTypeToGFXType(attribInfo.type, gl);
                  var stride = WebGLGetTypeSize(attribInfo.type, gl);
                  gpuShader.glInputs[i] = {
                    binding: glLoc,
                    name: varName,
                    type: type,
                    stride: stride,
                    count: attribInfo.size,
                    size: stride * attribInfo.size,
                    glType: attribInfo.type,
                    glLoc: glLoc
                  };
                }
              }

              if (gpuShader.blocks.length > 0) {
                gpuShader.glBlocks = new Array(gpuShader.blocks.length);

                for (var _i7 = 0; _i7 < gpuShader.blocks.length; ++_i7) {
                  var block = gpuShader.blocks[_i7];
                  var glBlock = {
                    set: block.set,
                    binding: block.binding,
                    name: block.name,
                    size: 0,
                    glUniforms: new Array(block.members.length),
                    glActiveUniforms: []
                  };
                  gpuShader.glBlocks[_i7] = glBlock;

                  for (var u = 0; u < block.members.length; ++u) {
                    var uniform = block.members[u];
                    var glType = GFXTypeToWebGLType(uniform.type, gl);
                    var Ctor = GFXTypeToTypedArrayCtor(uniform.type);

                    var _stride = WebGLGetTypeSize(glType, gl);

                    var size = _stride * uniform.count;
                    var begin = glBlock.size / 4;
                    var count = size / 4;
                    var array = new Ctor(count);
                    glBlock.glUniforms[u] = {
                      binding: -1,
                      name: uniform.name,
                      type: uniform.type,
                      stride: _stride,
                      count: uniform.count,
                      size: size,
                      offset: glBlock.size,
                      glType: glType,
                      glLoc: -1,
                      array: array,
                      begin: begin
                    };
                    glBlock.size += size;
                  }
                }
              }

              if (gpuShader.samplerTextures.length > 0) {
                gpuShader.glSamplerTextures = new Array(gpuShader.samplerTextures.length);

                for (var _i8 = 0; _i8 < gpuShader.samplerTextures.length; ++_i8) {
                  var sampler = gpuShader.samplerTextures[_i8];
                  gpuShader.glSamplerTextures[_i8] = {
                    set: sampler.set,
                    binding: sampler.binding,
                    name: sampler.name,
                    type: sampler.type,
                    count: sampler.count,
                    units: [],
                    glUnits: null,
                    glType: GFXTypeToWebGLType(sampler.type, gl),
                    glLoc: null
                  };
                }
              }

              var activeUniformCount = gl.getProgramParameter(gpuShader.glProgram, gl.ACTIVE_UNIFORMS);

              for (var _i9 = 0; _i9 < activeUniformCount; ++_i9) {
                var uniformInfo = gl.getActiveUniform(gpuShader.glProgram, _i9);

                if (uniformInfo) {
                  var isSampler = uniformInfo.type === gl.SAMPLER_2D || uniformInfo.type === gl.SAMPLER_CUBE;

                  if (!isSampler) {
                    var _glLoc = gl.getUniformLocation(gpuShader.glProgram, uniformInfo.name);

                    if (_glLoc !== null && (typeof _glLoc === 'number' || _glLoc.id !== -1)) {
                      var _varName = void 0;

                      var _nameOffset = uniformInfo.name.indexOf('[');

                      if (_nameOffset !== -1) {
                        _varName = uniformInfo.name.substr(0, _nameOffset);
                      } else {
                        _varName = uniformInfo.name;
                      }

                      for (var j = 0; j < gpuShader.glBlocks.length; j++) {
                        var _glBlock = gpuShader.glBlocks[j];

                        for (var _k3 = 0; _k3 < _glBlock.glUniforms.length; _k3++) {
                          var glUniform = _glBlock.glUniforms[_k3];

                          if (glUniform.name === _varName) {
                            glUniform.glLoc = _glLoc;

                            _glBlock.glActiveUniforms.push(glUniform);

                            break;
                          }
                        }
                      }
                    }
                  }
                }
              }

              var glActiveSamplers = [];
              var glActiveSamplerLocations = [];
              var bindingMappingInfo = device.bindingMappingInfo;
              var texUnitCacheMap = device.stateCache.texUnitCacheMap;
              var flexibleSetBaseOffset = 0;

              for (var _i10 = 0; _i10 < gpuShader.blocks.length; ++_i10) {
                if (gpuShader.blocks[_i10].set === bindingMappingInfo.flexibleSet) {
                  flexibleSetBaseOffset++;
                }
              }

              var arrayOffset = 0;

              for (var _i11 = 0; _i11 < gpuShader.samplerTextures.length; ++_i11) {
                var _sampler = gpuShader.samplerTextures[_i11];

                var _glLoc2 = gl.getUniformLocation(gpuShader.glProgram, _sampler.name);

                if (_glLoc2 !== null && (typeof _glLoc2 === 'number' || _glLoc2.id !== -1)) {
                  glActiveSamplers.push(gpuShader.glSamplerTextures[_i11]);
                  glActiveSamplerLocations.push(_glLoc2);
                }

                if (texUnitCacheMap[_sampler.name] === undefined) {
                  var binding = _sampler.binding + bindingMappingInfo.samplerOffsets[_sampler.set] + arrayOffset;

                  if (_sampler.set === bindingMappingInfo.flexibleSet) {
                    binding -= flexibleSetBaseOffset;
                  }

                  texUnitCacheMap[_sampler.name] = binding % device.capabilities.maxTextureUnits;
                  arrayOffset += _sampler.count - 1;
                }
              }

              if (glActiveSamplers.length) {
                var usedTexUnits = [];

                for (var _i12 = 0; _i12 < glActiveSamplers.length; ++_i12) {
                  var glSampler = glActiveSamplers[_i12];
                  var cachedUnit = texUnitCacheMap[glSampler.name];

                  if (cachedUnit !== undefined) {
                    glSampler.glLoc = glActiveSamplerLocations[_i12];

                    for (var t = 0; t < glSampler.count; ++t) {
                      while (usedTexUnits[cachedUnit]) {
                        cachedUnit = (cachedUnit + 1) % device.capabilities.maxTextureUnits;
                      }

                      glSampler.units.push(cachedUnit);
                      usedTexUnits[cachedUnit] = true;
                    }
                  }
                }

                var unitIdx = 0;

                for (var _i13 = 0; _i13 < glActiveSamplers.length; ++_i13) {
                  var _glSampler = glActiveSamplers[_i13];

                  if (!_glSampler.glLoc) {
                    _glSampler.glLoc = glActiveSamplerLocations[_i13];

                    for (var _t = 0; _t < _glSampler.count; ++_t) {
                      while (usedTexUnits[unitIdx]) {
                        unitIdx = (unitIdx + 1) % device.capabilities.maxTextureUnits;
                      }

                      if (texUnitCacheMap[_glSampler.name] === undefined) {
                        texUnitCacheMap[_glSampler.name] = unitIdx;
                      }

                      _glSampler.units.push(unitIdx);

                      usedTexUnits[unitIdx] = true;
                    }
                  }
                }

                if (device.stateCache.glProgram !== gpuShader.glProgram) {
                  gl.useProgram(gpuShader.glProgram);
                }

                for (var _i14 = 0; _i14 < glActiveSamplers.length; _i14++) {
                  var _glSampler2 = glActiveSamplers[_i14];
                  _glSampler2.glUnits = new Int32Array(_glSampler2.units);
                  gl.uniform1iv(_glSampler2.glLoc, _glSampler2.glUnits);
                }

                if (device.stateCache.glProgram !== gpuShader.glProgram) {
                  gl.useProgram(device.stateCache.glProgram);
                }
              }

              for (var _i15 = 0; _i15 < gpuShader.glBlocks.length;) {
                if (gpuShader.glBlocks[_i15].glActiveUniforms.length) {
                  _i15++;
                } else {
                  gpuShader.glBlocks[_i15] = gpuShader.glBlocks[gpuShader.glBlocks.length - 1];
                  gpuShader.glBlocks.length--;
                }
              }

              gpuShader.glSamplerTextures = glActiveSamplers;
            }
            function WebGLCmdFuncDestroyShader(device, gpuShader) {
              if (gpuShader.glProgram) {
                var gl = device.gl;

                if (!device.destroyShadersImmediately) {
                  for (var k = 0; k < gpuShader.gpuStages.length; k++) {
                    var gpuStage = gpuShader.gpuStages[k];

                    if (gpuStage.glShader) {
                      gl.detachShader(gpuShader.glProgram, gpuStage.glShader);
                      gl.deleteShader(gpuStage.glShader);
                      gpuStage.glShader = null;
                    }
                  }
                }

                gl.deleteProgram(gpuShader.glProgram);
                gpuShader.glProgram = null;
              }
            }
            function WebGLCmdFuncCreateInputAssember(device, gpuInputAssembler) {
              var gl = device.gl;
              gpuInputAssembler.glAttribs = new Array(gpuInputAssembler.attributes.length);
              var offsets = [0, 0, 0, 0, 0, 0, 0, 0];

              for (var i = 0; i < gpuInputAssembler.attributes.length; ++i) {
                var attrib = gpuInputAssembler.attributes[i];
                var stream = attrib.stream !== undefined ? attrib.stream : 0;
                var gpuBuffer = gpuInputAssembler.gpuVertexBuffers[stream];
                var glType = GFXFormatToWebGLType(attrib.format, gl);
                var size = FormatInfos[attrib.format].size;
                gpuInputAssembler.glAttribs[i] = {
                  name: attrib.name,
                  glBuffer: gpuBuffer.glBuffer,
                  glType: glType,
                  size: size,
                  count: FormatInfos[attrib.format].count,
                  stride: gpuBuffer.stride,
                  componentCount: WebGLGetComponentCount(glType, gl),
                  isNormalized: attrib.isNormalized !== undefined ? attrib.isNormalized : false,
                  isInstanced: attrib.isInstanced !== undefined ? attrib.isInstanced : false,
                  offset: offsets[stream]
                };
                offsets[stream] += size;
              }
            }
            function WebGLCmdFuncDestroyInputAssembler(device, gpuInputAssembler) {
              var it = gpuInputAssembler.glVAOs.values();
              var res = it.next();

              while (!res.done) {
                device.OES_vertex_array_object.deleteVertexArrayOES(res.value);
                res = it.next();
              }

              gpuInputAssembler.glVAOs.clear();
            }
            var gfxStateCache = {
              gpuPipelineState: null,
              gpuInputAssembler: null,
              glPrimitive: 0
            };
            function WebGLCmdFuncBeginRenderPass(device, gpuRenderPass, gpuFramebuffer, renderArea, clearColors, clearDepth, clearStencil) {
              var gl = device.gl;
              var cache = device.stateCache;
              var clears = 0;

              if (gpuFramebuffer && gpuRenderPass) {
                if (cache.glFramebuffer !== gpuFramebuffer.glFramebuffer) {
                  gl.bindFramebuffer(gl.FRAMEBUFFER, gpuFramebuffer.glFramebuffer);
                  cache.glFramebuffer = gpuFramebuffer.glFramebuffer;
                }

                if (cache.viewport.left !== renderArea.x || cache.viewport.top !== renderArea.y || cache.viewport.width !== renderArea.width || cache.viewport.height !== renderArea.height) {
                  gl.viewport(renderArea.x, renderArea.y, renderArea.width, renderArea.height);
                  cache.viewport.left = renderArea.x;
                  cache.viewport.top = renderArea.y;
                  cache.viewport.width = renderArea.width;
                  cache.viewport.height = renderArea.height;
                }

                if (cache.scissorRect.x !== renderArea.x || cache.scissorRect.y !== renderArea.y || cache.scissorRect.width !== renderArea.width || cache.scissorRect.height !== renderArea.height) {
                  gl.scissor(renderArea.x, renderArea.y, renderArea.width, renderArea.height);
                  cache.scissorRect.x = renderArea.x;
                  cache.scissorRect.y = renderArea.y;
                  cache.scissorRect.width = renderArea.width;
                  cache.scissorRect.height = renderArea.height;
                }

                var clearCount = clearColors.length;

                if (!device.WEBGL_draw_buffers) {
                  clearCount = 1;
                }

                for (var j = 0; j < clearCount; ++j) {
                  var colorAttachment = gpuRenderPass.colorAttachments[j];

                  if (colorAttachment.format !== Format.UNKNOWN) {
                    switch (colorAttachment.loadOp) {
                      case LoadOp.LOAD:
                        break;

                      case LoadOp.CLEAR:
                        {
                          if (cache.bs.targets[0].blendColorMask !== ColorMask.ALL) {
                            gl.colorMask(true, true, true, true);
                          }

                          var clearColor = clearColors[0];
                          gl.clearColor(clearColor.x, clearColor.y, clearColor.z, clearColor.w);
                          clears |= gl.COLOR_BUFFER_BIT;
                          break;
                        }

                      case LoadOp.DISCARD:
                        {
                          break;
                        }
                    }
                  }
                }

                if (gpuRenderPass.depthStencilAttachment) {
                  if (gpuRenderPass.depthStencilAttachment.format !== Format.UNKNOWN) {
                    switch (gpuRenderPass.depthStencilAttachment.depthLoadOp) {
                      case LoadOp.LOAD:
                        break;

                      case LoadOp.CLEAR:
                        {
                          if (!cache.dss.depthWrite) {
                            gl.depthMask(true);
                          }

                          gl.clearDepth(clearDepth);
                          clears |= gl.DEPTH_BUFFER_BIT;
                          break;
                        }

                      case LoadOp.DISCARD:
                        {
                          break;
                        }
                    }

                    if (FormatInfos[gpuRenderPass.depthStencilAttachment.format].hasStencil) {
                      switch (gpuRenderPass.depthStencilAttachment.stencilLoadOp) {
                        case LoadOp.LOAD:
                          break;

                        case LoadOp.CLEAR:
                          {
                            if (!cache.dss.stencilWriteMaskFront) {
                              gl.stencilMaskSeparate(gl.FRONT, 0xffff);
                            }

                            if (!cache.dss.stencilWriteMaskBack) {
                              gl.stencilMaskSeparate(gl.BACK, 0xffff);
                            }

                            gl.clearStencil(clearStencil);
                            clears |= gl.STENCIL_BUFFER_BIT;
                            break;
                          }

                        case LoadOp.DISCARD:
                          {
                            break;
                          }
                      }
                    }
                  }
                }

                if (clears) {
                  gl.clear(clears);
                }

                if (clears & gl.COLOR_BUFFER_BIT) {
                  var colorMask = cache.bs.targets[0].blendColorMask;

                  if (colorMask !== ColorMask.ALL) {
                    var r = (colorMask & ColorMask.R) !== ColorMask.NONE;
                    var g = (colorMask & ColorMask.G) !== ColorMask.NONE;
                    var b = (colorMask & ColorMask.B) !== ColorMask.NONE;
                    var a = (colorMask & ColorMask.A) !== ColorMask.NONE;
                    gl.colorMask(r, g, b, a);
                  }
                }

                if (clears & gl.DEPTH_BUFFER_BIT && !cache.dss.depthWrite) {
                  gl.depthMask(false);
                }

                if (clears & gl.STENCIL_BUFFER_BIT) {
                  if (!cache.dss.stencilWriteMaskFront) {
                    gl.stencilMaskSeparate(gl.FRONT, 0);
                  }

                  if (!cache.dss.stencilWriteMaskBack) {
                    gl.stencilMaskSeparate(gl.BACK, 0);
                  }
                }
              }
            }
            function WebGLCmdFuncBindStates(device, gpuPipelineState, gpuInputAssembler, gpuDescriptorSets, dynamicOffsets, dynamicStates) {
              var gl = device.gl;
              var cache = device.stateCache;
              var gpuShader = gpuPipelineState && gpuPipelineState.gpuShader;
              var isShaderChanged = false;
              var glWrapS;
              var glWrapT;
              var glMinFilter;

              if (gpuPipelineState && gfxStateCache.gpuPipelineState !== gpuPipelineState) {
                gfxStateCache.gpuPipelineState = gpuPipelineState;
                gfxStateCache.glPrimitive = gpuPipelineState.glPrimitive;

                if (gpuPipelineState.gpuShader) {
                  var glProgram = gpuPipelineState.gpuShader.glProgram;

                  if (cache.glProgram !== glProgram) {
                    gl.useProgram(glProgram);
                    cache.glProgram = glProgram;
                    isShaderChanged = true;
                  }
                }

                var rs = gpuPipelineState.rs;

                if (rs) {
                  if (cache.rs.cullMode !== rs.cullMode) {
                    switch (rs.cullMode) {
                      case CullMode.NONE:
                        {
                          gl.disable(gl.CULL_FACE);
                          break;
                        }

                      case CullMode.FRONT:
                        {
                          gl.enable(gl.CULL_FACE);
                          gl.cullFace(gl.FRONT);
                          break;
                        }

                      case CullMode.BACK:
                        {
                          gl.enable(gl.CULL_FACE);
                          gl.cullFace(gl.BACK);
                          break;
                        }
                    }

                    cache.rs.cullMode = rs.cullMode;
                  }

                  var isFrontFaceCCW = rs.isFrontFaceCCW;

                  if (cache.rs.isFrontFaceCCW !== isFrontFaceCCW) {
                    gl.frontFace(isFrontFaceCCW ? gl.CCW : gl.CW);
                    cache.rs.isFrontFaceCCW = isFrontFaceCCW;
                  }

                  if (cache.rs.depthBias !== rs.depthBias || cache.rs.depthBiasSlop !== rs.depthBiasSlop) {
                    gl.polygonOffset(rs.depthBias, rs.depthBiasSlop);
                    cache.rs.depthBias = rs.depthBias;
                    cache.rs.depthBiasSlop = rs.depthBiasSlop;
                  }

                  if (cache.rs.lineWidth !== rs.lineWidth) {
                    gl.lineWidth(rs.lineWidth);
                    cache.rs.lineWidth = rs.lineWidth;
                  }
                }

                var dss = gpuPipelineState.dss;

                if (dss) {
                  if (cache.dss.depthTest !== dss.depthTest) {
                    if (dss.depthTest) {
                      gl.enable(gl.DEPTH_TEST);
                    } else {
                      gl.disable(gl.DEPTH_TEST);
                    }

                    cache.dss.depthTest = dss.depthTest;
                  }

                  if (cache.dss.depthWrite !== dss.depthWrite) {
                    gl.depthMask(dss.depthWrite);
                    cache.dss.depthWrite = dss.depthWrite;
                  }

                  if (cache.dss.depthFunc !== dss.depthFunc) {
                    gl.depthFunc(WebGLCmpFuncs[dss.depthFunc]);
                    cache.dss.depthFunc = dss.depthFunc;
                  }

                  if (cache.dss.stencilTestFront !== dss.stencilTestFront || cache.dss.stencilTestBack !== dss.stencilTestBack) {
                    if (dss.stencilTestFront || dss.stencilTestBack) {
                      gl.enable(gl.STENCIL_TEST);
                    } else {
                      gl.disable(gl.STENCIL_TEST);
                    }

                    cache.dss.stencilTestFront = dss.stencilTestFront;
                    cache.dss.stencilTestBack = dss.stencilTestBack;
                  }

                  if (cache.dss.stencilFuncFront !== dss.stencilFuncFront || cache.dss.stencilRefFront !== dss.stencilRefFront || cache.dss.stencilReadMaskFront !== dss.stencilReadMaskFront) {
                    gl.stencilFuncSeparate(gl.FRONT, WebGLCmpFuncs[dss.stencilFuncFront], dss.stencilRefFront, dss.stencilReadMaskFront);
                    cache.dss.stencilFuncFront = dss.stencilFuncFront;
                    cache.dss.stencilRefFront = dss.stencilRefFront;
                    cache.dss.stencilReadMaskFront = dss.stencilReadMaskFront;
                  }

                  if (cache.dss.stencilFailOpFront !== dss.stencilFailOpFront || cache.dss.stencilZFailOpFront !== dss.stencilZFailOpFront || cache.dss.stencilPassOpFront !== dss.stencilPassOpFront) {
                    gl.stencilOpSeparate(gl.FRONT, WebGLStencilOps[dss.stencilFailOpFront], WebGLStencilOps[dss.stencilZFailOpFront], WebGLStencilOps[dss.stencilPassOpFront]);
                    cache.dss.stencilFailOpFront = dss.stencilFailOpFront;
                    cache.dss.stencilZFailOpFront = dss.stencilZFailOpFront;
                    cache.dss.stencilPassOpFront = dss.stencilPassOpFront;
                  }

                  if (cache.dss.stencilWriteMaskFront !== dss.stencilWriteMaskFront) {
                    gl.stencilMaskSeparate(gl.FRONT, dss.stencilWriteMaskFront);
                    cache.dss.stencilWriteMaskFront = dss.stencilWriteMaskFront;
                  }

                  if (cache.dss.stencilFuncBack !== dss.stencilFuncBack || cache.dss.stencilRefBack !== dss.stencilRefBack || cache.dss.stencilReadMaskBack !== dss.stencilReadMaskBack) {
                    gl.stencilFuncSeparate(gl.BACK, WebGLCmpFuncs[dss.stencilFuncBack], dss.stencilRefBack, dss.stencilReadMaskBack);
                    cache.dss.stencilFuncBack = dss.stencilFuncBack;
                    cache.dss.stencilRefBack = dss.stencilRefBack;
                    cache.dss.stencilReadMaskBack = dss.stencilReadMaskBack;
                  }

                  if (cache.dss.stencilFailOpBack !== dss.stencilFailOpBack || cache.dss.stencilZFailOpBack !== dss.stencilZFailOpBack || cache.dss.stencilPassOpBack !== dss.stencilPassOpBack) {
                    gl.stencilOpSeparate(gl.BACK, WebGLStencilOps[dss.stencilFailOpBack], WebGLStencilOps[dss.stencilZFailOpBack], WebGLStencilOps[dss.stencilPassOpBack]);
                    cache.dss.stencilFailOpBack = dss.stencilFailOpBack;
                    cache.dss.stencilZFailOpBack = dss.stencilZFailOpBack;
                    cache.dss.stencilPassOpBack = dss.stencilPassOpBack;
                  }

                  if (cache.dss.stencilWriteMaskBack !== dss.stencilWriteMaskBack) {
                    gl.stencilMaskSeparate(gl.BACK, dss.stencilWriteMaskBack);
                    cache.dss.stencilWriteMaskBack = dss.stencilWriteMaskBack;
                  }
                }

                var bs = gpuPipelineState.bs;

                if (bs) {
                  if (cache.bs.isA2C !== bs.isA2C) {
                    if (bs.isA2C) {
                      gl.enable(gl.SAMPLE_ALPHA_TO_COVERAGE);
                    } else {
                      gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
                    }

                    cache.bs.isA2C = bs.isA2C;
                  }

                  if (cache.bs.blendColor.x !== bs.blendColor.x || cache.bs.blendColor.y !== bs.blendColor.y || cache.bs.blendColor.z !== bs.blendColor.z || cache.bs.blendColor.w !== bs.blendColor.w) {
                    gl.blendColor(bs.blendColor.x, bs.blendColor.y, bs.blendColor.z, bs.blendColor.w);
                    cache.bs.blendColor.x = bs.blendColor.x;
                    cache.bs.blendColor.y = bs.blendColor.y;
                    cache.bs.blendColor.z = bs.blendColor.z;
                    cache.bs.blendColor.w = bs.blendColor.w;
                  }

                  var target0 = bs.targets[0];
                  var target0Cache = cache.bs.targets[0];

                  if (target0Cache.blend !== target0.blend) {
                    if (target0.blend) {
                      gl.enable(gl.BLEND);
                    } else {
                      gl.disable(gl.BLEND);
                    }

                    target0Cache.blend = target0.blend;
                  }

                  if (target0Cache.blendEq !== target0.blendEq || target0Cache.blendAlphaEq !== target0.blendAlphaEq) {
                    gl.blendEquationSeparate(WebGLBlendOps[target0.blendEq], WebGLBlendOps[target0.blendAlphaEq]);
                    target0Cache.blendEq = target0.blendEq;
                    target0Cache.blendAlphaEq = target0.blendAlphaEq;
                  }

                  if (target0Cache.blendSrc !== target0.blendSrc || target0Cache.blendDst !== target0.blendDst || target0Cache.blendSrcAlpha !== target0.blendSrcAlpha || target0Cache.blendDstAlpha !== target0.blendDstAlpha) {
                    gl.blendFuncSeparate(WebGLBlendFactors[target0.blendSrc], WebGLBlendFactors[target0.blendDst], WebGLBlendFactors[target0.blendSrcAlpha], WebGLBlendFactors[target0.blendDstAlpha]);
                    target0Cache.blendSrc = target0.blendSrc;
                    target0Cache.blendDst = target0.blendDst;
                    target0Cache.blendSrcAlpha = target0.blendSrcAlpha;
                    target0Cache.blendDstAlpha = target0.blendDstAlpha;
                  }

                  if (target0Cache.blendColorMask !== target0.blendColorMask) {
                    gl.colorMask((target0.blendColorMask & ColorMask.R) !== ColorMask.NONE, (target0.blendColorMask & ColorMask.G) !== ColorMask.NONE, (target0.blendColorMask & ColorMask.B) !== ColorMask.NONE, (target0.blendColorMask & ColorMask.A) !== ColorMask.NONE);
                    target0Cache.blendColorMask = target0.blendColorMask;
                  }
                }
              }

              if (gpuPipelineState && gpuPipelineState.gpuPipelineLayout && gpuShader) {
                var blockLen = gpuShader.glBlocks.length;
                var dynamicOffsetIndices = gpuPipelineState.gpuPipelineLayout.dynamicOffsetIndices;

                for (var j = 0; j < blockLen; j++) {
                  var glBlock = gpuShader.glBlocks[j];
                  var gpuDescriptorSet = gpuDescriptorSets[glBlock.set];
                  var descriptorIdx = gpuDescriptorSet && gpuDescriptorSet.descriptorIndices[glBlock.binding];
                  var gpuDescriptor = descriptorIdx >= 0 && gpuDescriptorSet.gpuDescriptors[descriptorIdx];
                  var vf32 = null;
                  var offset = 0;

                  if (gpuDescriptor && gpuDescriptor.gpuBuffer) {
                    var gpuBuffer = gpuDescriptor.gpuBuffer;
                    var dynamicOffsetIndexSet = dynamicOffsetIndices[glBlock.set];
                    var dynamicOffsetIndex = dynamicOffsetIndexSet && dynamicOffsetIndexSet[glBlock.binding];

                    if (dynamicOffsetIndex >= 0) {
                      offset = dynamicOffsets[dynamicOffsetIndex];
                    }

                    if ('vf32' in gpuBuffer) {
                      vf32 = gpuBuffer.vf32;
                    } else {
                      offset += gpuBuffer.offset;
                      vf32 = gpuBuffer.gpuBuffer.vf32;
                    }

                    offset >>= 2;
                  }

                  if (!vf32) {
                    error("Buffer binding '" + glBlock.name + "' at set " + glBlock.set + " binding " + glBlock.binding + " is not bounded");
                    continue;
                  }

                  var uniformLen = glBlock.glActiveUniforms.length;

                  for (var l = 0; l < uniformLen; l++) {
                    var glUniform = glBlock.glActiveUniforms[l];

                    switch (glUniform.glType) {
                      case gl.BOOL:
                      case gl.INT:
                        {
                          for (var u = 0; u < glUniform.array.length; ++u) {
                            var idx = glUniform.begin + offset + u;

                            if (vf32[idx] !== glUniform.array[u]) {
                              for (var n = u, m = idx; n < glUniform.array.length; ++n, ++m) {
                                glUniform.array[n] = vf32[m];
                              }

                              gl.uniform1iv(glUniform.glLoc, glUniform.array);
                              break;
                            }
                          }

                          break;
                        }

                      case gl.BOOL_VEC2:
                      case gl.INT_VEC2:
                        {
                          for (var _u = 0; _u < glUniform.array.length; ++_u) {
                            var _idx = glUniform.begin + offset + _u;

                            if (vf32[_idx] !== glUniform.array[_u]) {
                              for (var _n = _u, _m = _idx; _n < glUniform.array.length; ++_n, ++_m) {
                                glUniform.array[_n] = vf32[_m];
                              }

                              gl.uniform2iv(glUniform.glLoc, glUniform.array);
                              break;
                            }
                          }

                          break;
                        }

                      case gl.BOOL_VEC3:
                      case gl.INT_VEC3:
                        {
                          for (var _u2 = 0; _u2 < glUniform.array.length; ++_u2) {
                            var _idx2 = glUniform.begin + offset + _u2;

                            if (vf32[_idx2] !== glUniform.array[_u2]) {
                              for (var _n2 = _u2, _m2 = _idx2; _n2 < glUniform.array.length; ++_n2, ++_m2) {
                                glUniform.array[_n2] = vf32[_m2];
                              }

                              gl.uniform3iv(glUniform.glLoc, glUniform.array);
                              break;
                            }
                          }

                          break;
                        }

                      case gl.BOOL_VEC4:
                      case gl.INT_VEC4:
                        {
                          for (var _u3 = 0; _u3 < glUniform.array.length; ++_u3) {
                            var _idx3 = glUniform.begin + offset + _u3;

                            if (vf32[_idx3] !== glUniform.array[_u3]) {
                              for (var _n3 = _u3, _m3 = _idx3; _n3 < glUniform.array.length; ++_n3, ++_m3) {
                                glUniform.array[_n3] = vf32[_m3];
                              }

                              gl.uniform4iv(glUniform.glLoc, glUniform.array);
                              break;
                            }
                          }

                          break;
                        }

                      case gl.FLOAT:
                        {
                          for (var _u4 = 0; _u4 < glUniform.array.length; ++_u4) {
                            var _idx4 = glUniform.begin + offset + _u4;

                            if (vf32[_idx4] !== glUniform.array[_u4]) {
                              for (var _n4 = _u4, _m4 = _idx4; _n4 < glUniform.array.length; ++_n4, ++_m4) {
                                glUniform.array[_n4] = vf32[_m4];
                              }

                              gl.uniform1fv(glUniform.glLoc, glUniform.array);
                              break;
                            }
                          }

                          break;
                        }

                      case gl.FLOAT_VEC2:
                        {
                          for (var _u5 = 0; _u5 < glUniform.array.length; ++_u5) {
                            var _idx5 = glUniform.begin + offset + _u5;

                            if (vf32[_idx5] !== glUniform.array[_u5]) {
                              for (var _n5 = _u5, _m5 = _idx5; _n5 < glUniform.array.length; ++_n5, ++_m5) {
                                glUniform.array[_n5] = vf32[_m5];
                              }

                              gl.uniform2fv(glUniform.glLoc, glUniform.array);
                              break;
                            }
                          }

                          break;
                        }

                      case gl.FLOAT_VEC3:
                        {
                          for (var _u6 = 0; _u6 < glUniform.array.length; ++_u6) {
                            var _idx6 = glUniform.begin + offset + _u6;

                            if (vf32[_idx6] !== glUniform.array[_u6]) {
                              for (var _n6 = _u6, _m6 = _idx6; _n6 < glUniform.array.length; ++_n6, ++_m6) {
                                glUniform.array[_n6] = vf32[_m6];
                              }

                              gl.uniform3fv(glUniform.glLoc, glUniform.array);
                              break;
                            }
                          }

                          break;
                        }

                      case gl.FLOAT_VEC4:
                        {
                          for (var _u7 = 0; _u7 < glUniform.array.length; ++_u7) {
                            var _idx7 = glUniform.begin + offset + _u7;

                            if (vf32[_idx7] !== glUniform.array[_u7]) {
                              for (var _n7 = _u7, _m7 = _idx7; _n7 < glUniform.array.length; ++_n7, ++_m7) {
                                glUniform.array[_n7] = vf32[_m7];
                              }

                              gl.uniform4fv(glUniform.glLoc, glUniform.array);
                              break;
                            }
                          }

                          break;
                        }

                      case gl.FLOAT_MAT2:
                        {
                          for (var _u8 = 0; _u8 < glUniform.array.length; ++_u8) {
                            var _idx8 = glUniform.begin + offset + _u8;

                            if (vf32[_idx8] !== glUniform.array[_u8]) {
                              for (var _n8 = _u8, _m8 = _idx8; _n8 < glUniform.array.length; ++_n8, ++_m8) {
                                glUniform.array[_n8] = vf32[_m8];
                              }

                              gl.uniformMatrix2fv(glUniform.glLoc, false, glUniform.array);
                              break;
                            }
                          }

                          break;
                        }

                      case gl.FLOAT_MAT3:
                        {
                          for (var _u9 = 0; _u9 < glUniform.array.length; ++_u9) {
                            var _idx9 = glUniform.begin + offset + _u9;

                            if (vf32[_idx9] !== glUniform.array[_u9]) {
                              for (var _n9 = _u9, _m9 = _idx9; _n9 < glUniform.array.length; ++_n9, ++_m9) {
                                glUniform.array[_n9] = vf32[_m9];
                              }

                              gl.uniformMatrix3fv(glUniform.glLoc, false, glUniform.array);
                              break;
                            }
                          }

                          break;
                        }

                      case gl.FLOAT_MAT4:
                        {
                          for (var _u10 = 0; _u10 < glUniform.array.length; ++_u10) {
                            var _idx10 = glUniform.begin + offset + _u10;

                            if (vf32[_idx10] !== glUniform.array[_u10]) {
                              for (var _n10 = _u10, _m10 = _idx10; _n10 < glUniform.array.length; ++_n10, ++_m10) {
                                glUniform.array[_n10] = vf32[_m10];
                              }

                              gl.uniformMatrix4fv(glUniform.glLoc, false, glUniform.array);
                              break;
                            }
                          }

                          break;
                        }
                    }
                  }

                  continue;
                }

                var samplerLen = gpuShader.glSamplerTextures.length;

                for (var i = 0; i < samplerLen; i++) {
                  var glSampler = gpuShader.glSamplerTextures[i];
                  var _gpuDescriptorSet = gpuDescriptorSets[glSampler.set];
                  var descriptorIndex = _gpuDescriptorSet && _gpuDescriptorSet.descriptorIndices[glSampler.binding];

                  var _gpuDescriptor = descriptorIndex >= 0 && _gpuDescriptorSet.gpuDescriptors[descriptorIndex];

                  var texUnitLen = glSampler.units.length;

                  for (var _l = 0; _l < texUnitLen; _l++) {
                    var texUnit = glSampler.units[_l];

                    if (!_gpuDescriptor || !_gpuDescriptor.gpuSampler) {
                      error("Sampler binding '" + glSampler.name + "' at set " + glSampler.set + " binding " + glSampler.binding + " index " + _l + " is not bounded");
                      continue;
                    }

                    if (_gpuDescriptor.gpuTexture && _gpuDescriptor.gpuTexture.size > 0) {
                      var _gpuDescriptor2 = _gpuDescriptor,
                          gpuTexture = _gpuDescriptor2.gpuTexture;
                      var glTexUnit = cache.glTexUnits[texUnit];

                      if (glTexUnit.glTexture !== gpuTexture.glTexture) {
                        if (cache.texUnit !== texUnit) {
                          gl.activeTexture(gl.TEXTURE0 + texUnit);
                          cache.texUnit = texUnit;
                        }

                        if (gpuTexture.glTexture) {
                          gl.bindTexture(gpuTexture.glTarget, gpuTexture.glTexture);
                        } else {
                          gl.bindTexture(gpuTexture.glTarget, device.nullTex2D.gpuTexture.glTexture);
                        }

                        glTexUnit.glTexture = gpuTexture.glTexture;
                      }

                      var _gpuDescriptor3 = _gpuDescriptor,
                          gpuSampler = _gpuDescriptor3.gpuSampler;

                      if (gpuTexture.isPowerOf2) {
                        glWrapS = gpuSampler.glWrapS;
                        glWrapT = gpuSampler.glWrapT;
                      } else {
                        glWrapS = gl.CLAMP_TO_EDGE;
                        glWrapT = gl.CLAMP_TO_EDGE;
                      }

                      if (gpuTexture.isPowerOf2) {
                        if (gpuTexture.mipLevel <= 1 && (gpuSampler.glMinFilter === gl.LINEAR_MIPMAP_NEAREST || gpuSampler.glMinFilter === gl.LINEAR_MIPMAP_LINEAR)) {
                          glMinFilter = gl.LINEAR;
                        } else {
                          glMinFilter = gpuSampler.glMinFilter;
                        }
                      } else if (gpuSampler.glMinFilter === gl.LINEAR || gpuSampler.glMinFilter === gl.LINEAR_MIPMAP_NEAREST || gpuSampler.glMinFilter === gl.LINEAR_MIPMAP_LINEAR) {
                        glMinFilter = gl.LINEAR;
                      } else {
                        glMinFilter = gl.NEAREST;
                      }

                      if (gpuTexture.glWrapS !== glWrapS) {
                        if (cache.texUnit !== texUnit) {
                          gl.activeTexture(gl.TEXTURE0 + texUnit);
                          cache.texUnit = texUnit;
                        }

                        gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_WRAP_S, glWrapS);
                        gpuTexture.glWrapS = glWrapS;
                      }

                      if (gpuTexture.glWrapT !== glWrapT) {
                        if (cache.texUnit !== texUnit) {
                          gl.activeTexture(gl.TEXTURE0 + texUnit);
                          cache.texUnit = texUnit;
                        }

                        gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_WRAP_T, glWrapT);
                        gpuTexture.glWrapT = glWrapT;
                      }

                      if (gpuTexture.glMinFilter !== glMinFilter) {
                        if (cache.texUnit !== texUnit) {
                          gl.activeTexture(gl.TEXTURE0 + texUnit);
                          cache.texUnit = texUnit;
                        }

                        gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_MIN_FILTER, glMinFilter);
                        gpuTexture.glMinFilter = glMinFilter;
                      }

                      if (gpuTexture.glMagFilter !== gpuSampler.glMagFilter) {
                        if (cache.texUnit !== texUnit) {
                          gl.activeTexture(gl.TEXTURE0 + texUnit);
                          cache.texUnit = texUnit;
                        }

                        gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_MAG_FILTER, gpuSampler.glMagFilter);
                        gpuTexture.glMagFilter = gpuSampler.glMagFilter;
                      }
                    }

                    _gpuDescriptor = _gpuDescriptorSet.gpuDescriptors[++descriptorIndex];
                  }
                }
              }

              if (gpuInputAssembler && gpuShader && (isShaderChanged || gfxStateCache.gpuInputAssembler !== gpuInputAssembler)) {
                gfxStateCache.gpuInputAssembler = gpuInputAssembler;
                var ia = device.ANGLE_instanced_arrays;

                if (device.useVAO) {
                  var vao = device.OES_vertex_array_object;
                  var glVAO = gpuInputAssembler.glVAOs.get(gpuShader.glProgram);

                  if (!glVAO) {
                    glVAO = vao.createVertexArrayOES();
                    gpuInputAssembler.glVAOs.set(gpuShader.glProgram, glVAO);
                    vao.bindVertexArrayOES(glVAO);
                    gl.bindBuffer(gl.ARRAY_BUFFER, null);
                    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
                    cache.glArrayBuffer = null;
                    cache.glElementArrayBuffer = null;
                    var glAttrib;
                    var inputLen = gpuShader.glInputs.length;

                    for (var _j = 0; _j < inputLen; _j++) {
                      var glInput = gpuShader.glInputs[_j];
                      glAttrib = null;
                      var attribLen = gpuInputAssembler.glAttribs.length;

                      for (var k = 0; k < attribLen; k++) {
                        var attrib = gpuInputAssembler.glAttribs[k];

                        if (attrib.name === glInput.name) {
                          glAttrib = attrib;
                          break;
                        }
                      }

                      if (glAttrib) {
                        if (cache.glArrayBuffer !== glAttrib.glBuffer) {
                          gl.bindBuffer(gl.ARRAY_BUFFER, glAttrib.glBuffer);
                          cache.glArrayBuffer = glAttrib.glBuffer;
                        }

                        for (var c = 0; c < glAttrib.componentCount; ++c) {
                          var glLoc = glInput.glLoc + c;
                          var attribOffset = glAttrib.offset + glAttrib.size * c;
                          gl.enableVertexAttribArray(glLoc);
                          cache.glCurrentAttribLocs[glLoc] = true;
                          gl.vertexAttribPointer(glLoc, glAttrib.count, glAttrib.glType, glAttrib.isNormalized, glAttrib.stride, attribOffset);

                          if (ia) {
                            ia.vertexAttribDivisorANGLE(glLoc, glAttrib.isInstanced ? 1 : 0);
                          }
                        }
                      }
                    }

                    var _gpuBuffer = gpuInputAssembler.gpuIndexBuffer;

                    if (_gpuBuffer) {
                      gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _gpuBuffer.glBuffer);
                    }

                    vao.bindVertexArrayOES(null);
                    gl.bindBuffer(gl.ARRAY_BUFFER, null);
                    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
                    cache.glArrayBuffer = null;
                    cache.glElementArrayBuffer = null;
                  }

                  if (cache.glVAO !== glVAO) {
                    vao.bindVertexArrayOES(glVAO);
                    cache.glVAO = glVAO;
                  }
                } else {
                  for (var a = 0; a < device.capabilities.maxVertexAttributes; ++a) {
                    cache.glCurrentAttribLocs[a] = false;
                  }

                  var _inputLen = gpuShader.glInputs.length;

                  for (var _j2 = 0; _j2 < _inputLen; _j2++) {
                    var _glInput = gpuShader.glInputs[_j2];
                    var _glAttrib = null;
                    var _attribLen = gpuInputAssembler.glAttribs.length;

                    for (var _k4 = 0; _k4 < _attribLen; _k4++) {
                      var _attrib = gpuInputAssembler.glAttribs[_k4];

                      if (_attrib.name === _glInput.name) {
                        _glAttrib = _attrib;
                        break;
                      }
                    }

                    if (_glAttrib) {
                      if (cache.glArrayBuffer !== _glAttrib.glBuffer) {
                        gl.bindBuffer(gl.ARRAY_BUFFER, _glAttrib.glBuffer);
                        cache.glArrayBuffer = _glAttrib.glBuffer;
                      }

                      for (var _c = 0; _c < _glAttrib.componentCount; ++_c) {
                        var _glLoc3 = _glInput.glLoc + _c;

                        var _attribOffset = _glAttrib.offset + _glAttrib.size * _c;

                        if (!cache.glEnabledAttribLocs[_glLoc3] && _glLoc3 >= 0) {
                          gl.enableVertexAttribArray(_glLoc3);
                          cache.glEnabledAttribLocs[_glLoc3] = true;
                        }

                        cache.glCurrentAttribLocs[_glLoc3] = true;
                        gl.vertexAttribPointer(_glLoc3, _glAttrib.count, _glAttrib.glType, _glAttrib.isNormalized, _glAttrib.stride, _attribOffset);

                        if (ia) {
                          ia.vertexAttribDivisorANGLE(_glLoc3, _glAttrib.isInstanced ? 1 : 0);
                        }
                      }
                    }
                  }

                  var _gpuBuffer2 = gpuInputAssembler.gpuIndexBuffer;

                  if (_gpuBuffer2) {
                    if (cache.glElementArrayBuffer !== _gpuBuffer2.glBuffer) {
                      gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _gpuBuffer2.glBuffer);
                      cache.glElementArrayBuffer = _gpuBuffer2.glBuffer;
                    }
                  }

                  for (var _a = 0; _a < device.capabilities.maxVertexAttributes; ++_a) {
                    if (cache.glEnabledAttribLocs[_a] !== cache.glCurrentAttribLocs[_a]) {
                      gl.disableVertexAttribArray(_a);
                      cache.glEnabledAttribLocs[_a] = false;
                    }
                  }
                }
              }

              if (gpuPipelineState && gpuPipelineState.dynamicStates.length) {
                var dsLen = gpuPipelineState.dynamicStates.length;

                for (var _j3 = 0; _j3 < dsLen; _j3++) {
                  var dynamicState = gpuPipelineState.dynamicStates[_j3];

                  switch (dynamicState) {
                    case DynamicStateFlagBit.VIEWPORT:
                      {
                        var viewport = dynamicStates.viewport;

                        if (cache.viewport.left !== viewport.left || cache.viewport.top !== viewport.top || cache.viewport.width !== viewport.width || cache.viewport.height !== viewport.height) {
                          gl.viewport(viewport.left, viewport.top, viewport.width, viewport.height);
                          cache.viewport.left = viewport.left;
                          cache.viewport.top = viewport.top;
                          cache.viewport.width = viewport.width;
                          cache.viewport.height = viewport.height;
                        }

                        break;
                      }

                    case DynamicStateFlagBit.SCISSOR:
                      {
                        var scissor = dynamicStates.scissor;

                        if (cache.scissorRect.x !== scissor.x || cache.scissorRect.y !== scissor.y || cache.scissorRect.width !== scissor.width || cache.scissorRect.height !== scissor.height) {
                          gl.scissor(scissor.x, scissor.y, scissor.width, scissor.height);
                          cache.scissorRect.x = scissor.x;
                          cache.scissorRect.y = scissor.y;
                          cache.scissorRect.width = scissor.width;
                          cache.scissorRect.height = scissor.height;
                        }

                        break;
                      }

                    case DynamicStateFlagBit.LINE_WIDTH:
                      {
                        if (cache.rs.lineWidth !== dynamicStates.lineWidth) {
                          gl.lineWidth(dynamicStates.lineWidth);
                          cache.rs.lineWidth = dynamicStates.lineWidth;
                        }

                        break;
                      }

                    case DynamicStateFlagBit.DEPTH_BIAS:
                      {
                        if (cache.rs.depthBias !== dynamicStates.depthBiasConstant || cache.rs.depthBiasSlop !== dynamicStates.depthBiasSlope) {
                          gl.polygonOffset(dynamicStates.depthBiasConstant, dynamicStates.depthBiasSlope);
                          cache.rs.depthBias = dynamicStates.depthBiasConstant;
                          cache.rs.depthBiasSlop = dynamicStates.depthBiasSlope;
                        }

                        break;
                      }

                    case DynamicStateFlagBit.BLEND_CONSTANTS:
                      {
                        var blendConstant = dynamicStates.blendConstant;

                        if (cache.bs.blendColor.x !== blendConstant.x || cache.bs.blendColor.y !== blendConstant.y || cache.bs.blendColor.z !== blendConstant.z || cache.bs.blendColor.w !== blendConstant.w) {
                          gl.blendColor(blendConstant.x, blendConstant.y, blendConstant.z, blendConstant.w);
                          cache.bs.blendColor.copy(blendConstant);
                        }

                        break;
                      }

                    case DynamicStateFlagBit.STENCIL_WRITE_MASK:
                      {
                        var front = dynamicStates.stencilStatesFront;
                        var back = dynamicStates.stencilStatesBack;

                        if (cache.dss.stencilWriteMaskFront !== front.writeMask) {
                          gl.stencilMaskSeparate(gl.FRONT, front.writeMask);
                          cache.dss.stencilWriteMaskFront = front.writeMask;
                        }

                        if (cache.dss.stencilWriteMaskBack !== back.writeMask) {
                          gl.stencilMaskSeparate(gl.BACK, back.writeMask);
                          cache.dss.stencilWriteMaskBack = back.writeMask;
                        }

                        break;
                      }

                    case DynamicStateFlagBit.STENCIL_COMPARE_MASK:
                      {
                        var _front = dynamicStates.stencilStatesFront;
                        var _back = dynamicStates.stencilStatesBack;

                        if (cache.dss.stencilRefFront !== _front.reference || cache.dss.stencilReadMaskFront !== _front.compareMask) {
                          gl.stencilFuncSeparate(gl.FRONT, WebGLCmpFuncs[cache.dss.stencilFuncFront], _front.reference, _front.compareMask);
                          cache.dss.stencilRefFront = _front.reference;
                          cache.dss.stencilReadMaskFront = _front.compareMask;
                        }

                        if (cache.dss.stencilRefBack !== _back.reference || cache.dss.stencilReadMaskBack !== _back.compareMask) {
                          gl.stencilFuncSeparate(gl.BACK, WebGLCmpFuncs[cache.dss.stencilFuncBack], _back.reference, _back.compareMask);
                          cache.dss.stencilRefBack = _back.reference;
                          cache.dss.stencilReadMaskBack = _back.compareMask;
                        }

                        break;
                      }
                  }
                }
              }
            }
            function WebGLCmdFuncDraw(device, drawInfo) {
              var gl = device.gl;
              var ia = device.ANGLE_instanced_arrays;
              var gpuInputAssembler = gfxStateCache.gpuInputAssembler,
                  glPrimitive = gfxStateCache.glPrimitive;

              if (gpuInputAssembler) {
                if (gpuInputAssembler.gpuIndirectBuffer) {
                  var diLen = gpuInputAssembler.gpuIndirectBuffer.indirects.length;

                  for (var j = 0; j < diLen; j++) {
                    var subDrawInfo = gpuInputAssembler.gpuIndirectBuffer.indirects[j];
                    var gpuBuffer = gpuInputAssembler.gpuIndexBuffer;

                    if (subDrawInfo.instanceCount && ia) {
                      if (gpuBuffer) {
                        if (subDrawInfo.indexCount > 0) {
                          var offset = subDrawInfo.firstIndex * gpuBuffer.stride;
                          ia.drawElementsInstancedANGLE(glPrimitive, subDrawInfo.indexCount, gpuInputAssembler.glIndexType, offset, subDrawInfo.instanceCount);
                        }
                      } else if (subDrawInfo.vertexCount > 0) {
                        ia.drawArraysInstancedANGLE(glPrimitive, subDrawInfo.firstVertex, subDrawInfo.vertexCount, subDrawInfo.instanceCount);
                      }
                    } else if (gpuBuffer) {
                      if (subDrawInfo.indexCount > 0) {
                        var _offset = subDrawInfo.firstIndex * gpuBuffer.stride;

                        gl.drawElements(glPrimitive, subDrawInfo.indexCount, gpuInputAssembler.glIndexType, _offset);
                      }
                    } else if (subDrawInfo.vertexCount > 0) {
                      gl.drawArrays(glPrimitive, subDrawInfo.firstVertex, subDrawInfo.vertexCount);
                    }
                  }
                } else {
                  var _gpuBuffer3 = gpuInputAssembler.gpuIndexBuffer;

                  if (drawInfo.instanceCount && ia) {
                    if (_gpuBuffer3) {
                      if (drawInfo.indexCount > 0) {
                        var _offset2 = drawInfo.firstIndex * _gpuBuffer3.stride;

                        ia.drawElementsInstancedANGLE(glPrimitive, drawInfo.indexCount, gpuInputAssembler.glIndexType, _offset2, drawInfo.instanceCount);
                      }
                    } else if (drawInfo.vertexCount > 0) {
                      ia.drawArraysInstancedANGLE(glPrimitive, drawInfo.firstVertex, drawInfo.vertexCount, drawInfo.instanceCount);
                    }
                  } else if (_gpuBuffer3) {
                    if (drawInfo.indexCount > 0) {
                      var _offset3 = drawInfo.firstIndex * _gpuBuffer3.stride;

                      gl.drawElements(glPrimitive, drawInfo.indexCount, gpuInputAssembler.glIndexType, _offset3);
                    }
                  } else if (drawInfo.vertexCount > 0) {
                    gl.drawArrays(glPrimitive, drawInfo.firstVertex, drawInfo.vertexCount);
                  }
                }
              }
            }
            var cmdIds = new Array(WebGLCmd.COUNT);
            function WebGLCmdFuncExecuteCmds(device, cmdPackage) {
              cmdIds.fill(0);

              for (var i = 0; i < cmdPackage.cmds.length; ++i) {
                var cmd = cmdPackage.cmds.array[i];
                var cmdId = cmdIds[cmd]++;

                switch (cmd) {
                  case WebGLCmd.BEGIN_RENDER_PASS:
                    {
                      var cmd0 = cmdPackage.beginRenderPassCmds.array[cmdId];
                      WebGLCmdFuncBeginRenderPass(device, cmd0.gpuRenderPass, cmd0.gpuFramebuffer, cmd0.renderArea, cmd0.clearColors, cmd0.clearDepth, cmd0.clearStencil);
                      break;
                    }

                  case WebGLCmd.BIND_STATES:
                    {
                      var cmd2 = cmdPackage.bindStatesCmds.array[cmdId];
                      WebGLCmdFuncBindStates(device, cmd2.gpuPipelineState, cmd2.gpuInputAssembler, cmd2.gpuDescriptorSets, cmd2.dynamicOffsets, cmd2.dynamicStates);
                      break;
                    }

                  case WebGLCmd.DRAW:
                    {
                      var cmd3 = cmdPackage.drawCmds.array[cmdId];
                      WebGLCmdFuncDraw(device, cmd3.drawInfo);
                      break;
                    }

                  case WebGLCmd.UPDATE_BUFFER:
                    {
                      var cmd4 = cmdPackage.updateBufferCmds.array[cmdId];
                      WebGLCmdFuncUpdateBuffer(device, cmd4.gpuBuffer, cmd4.buffer, cmd4.offset, cmd4.size);
                      break;
                    }

                  case WebGLCmd.COPY_BUFFER_TO_TEXTURE:
                    {
                      var cmd5 = cmdPackage.copyBufferToTextureCmds.array[cmdId];
                      WebGLCmdFuncCopyBuffersToTexture(device, cmd5.buffers, cmd5.gpuTexture, cmd5.regions);
                      break;
                    }
                }
              }
            }
            function WebGLCmdFuncCopyTexImagesToTexture(device, texImages, gpuTexture, regions) {
              var gl = device.gl;
              var glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit];

              if (glTexUnit.glTexture !== gpuTexture.glTexture) {
                gl.bindTexture(gpuTexture.glTarget, gpuTexture.glTexture);
                glTexUnit.glTexture = gpuTexture.glTexture;
              }

              var n = 0;
              var f = 0;

              switch (gpuTexture.glTarget) {
                case gl.TEXTURE_2D:
                  {
                    for (var i = 0; i < regions.length; i++) {
                      var region = regions[i];
                      gl.texSubImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, region.texOffset.x, region.texOffset.y, gpuTexture.glFormat, gpuTexture.glType, texImages[n++]);
                    }

                    break;
                  }

                case gl.TEXTURE_CUBE_MAP:
                  {
                    for (var _i16 = 0; _i16 < regions.length; _i16++) {
                      var _region = regions[_i16];
                      var fcount = _region.texSubres.baseArrayLayer + _region.texSubres.layerCount;

                      for (f = _region.texSubres.baseArrayLayer; f < fcount; ++f) {
                        gl.texSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, _region.texSubres.mipLevel, _region.texOffset.x, _region.texOffset.y, gpuTexture.glFormat, gpuTexture.glType, texImages[n++]);
                      }
                    }

                    break;
                  }

                default:
                  {
                    console.error('Unsupported GL texture type, copy buffer to texture failed.');
                  }
              }

              if (gpuTexture.flags & TextureFlagBit.GEN_MIPMAP && gpuTexture.isPowerOf2) {
                gl.generateMipmap(gpuTexture.glTarget);
              }
            }
            function WebGLCmdFuncCopyBuffersToTexture(device, buffers, gpuTexture, regions) {
              var gl = device.gl;
              var glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit];

              if (glTexUnit.glTexture !== gpuTexture.glTexture) {
                gl.bindTexture(gpuTexture.glTarget, gpuTexture.glTexture);
                glTexUnit.glTexture = gpuTexture.glTexture;
              }

              var n = 0;
              var w = 1;
              var h = 1;
              var f = 0;
              var fmtInfo = FormatInfos[gpuTexture.format];
              var isCompressed = fmtInfo.isCompressed;

              switch (gpuTexture.glTarget) {
                case gl.TEXTURE_2D:
                  {
                    for (var i = 0; i < regions.length; i++) {
                      var region = regions[i];
                      w = region.texExtent.width;
                      h = region.texExtent.height;
                      var pixels = buffers[n++];

                      if (!isCompressed) {
                        gl.texSubImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, region.texOffset.x, region.texOffset.y, w, h, gpuTexture.glFormat, gpuTexture.glType, pixels);
                      } else if (gpuTexture.glInternalFmt === WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL || device.noCompressedTexSubImage2D) {
                        gl.compressedTexImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, gpuTexture.glInternalFmt, w, h, 0, pixels);
                      } else {
                        gl.compressedTexSubImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, region.texOffset.x, region.texOffset.y, w, h, gpuTexture.glFormat, pixels);
                      }
                    }

                    break;
                  }

                case gl.TEXTURE_CUBE_MAP:
                  {
                    for (var _i17 = 0; _i17 < regions.length; _i17++) {
                      var _region2 = regions[_i17];
                      var fcount = _region2.texSubres.baseArrayLayer + _region2.texSubres.layerCount;

                      for (f = _region2.texSubres.baseArrayLayer; f < fcount; ++f) {
                        w = _region2.texExtent.width;
                        h = _region2.texExtent.height;
                        var _pixels = buffers[n++];

                        if (!isCompressed) {
                          gl.texSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, _region2.texSubres.mipLevel, _region2.texOffset.x, _region2.texOffset.y, w, h, gpuTexture.glFormat, gpuTexture.glType, _pixels);
                        } else if (gpuTexture.glInternalFmt === WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL || device.noCompressedTexSubImage2D) {
                          gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, _region2.texSubres.mipLevel, gpuTexture.glInternalFmt, w, h, 0, _pixels);
                        } else {
                          gl.compressedTexSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, _region2.texSubres.mipLevel, _region2.texOffset.x, _region2.texOffset.y, w, h, gpuTexture.glFormat, _pixels);
                        }
                      }
                    }

                    break;
                  }

                default:
                  {
                    console.error('Unsupported GL texture type, copy buffer to texture failed.');
                  }
              }

              if (gpuTexture.flags & TextureFlagBit.GEN_MIPMAP) {
                gl.generateMipmap(gpuTexture.glTarget);
              }
            }

            var WebGLBuffer = function (_Buffer) {
              _inheritsLoose(WebGLBuffer, _Buffer);

              function WebGLBuffer() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Buffer.call.apply(_Buffer, [this].concat(args)) || this;
                _this._gpuBuffer = null;
                _this._gpuBufferView = null;
                _this._uniformBuffer = null;
                return _this;
              }

              var _proto = WebGLBuffer.prototype;

              _proto.initialize = function initialize(info) {
                if ('buffer' in info) {
                  this._isBufferView = true;
                  var buffer = info.buffer;
                  this._usage = buffer.usage;
                  this._memUsage = buffer.memUsage;
                  this._size = this._stride = info.range;
                  this._count = 1;
                  this._flags = buffer.flags;
                  this._gpuBufferView = {
                    gpuBuffer: buffer.gpuBuffer,
                    offset: info.offset,
                    range: info.range
                  };
                } else {
                  this._usage = info.usage;
                  this._memUsage = info.memUsage;
                  this._size = info.size;
                  this._stride = Math.max(info.stride || this._size, 1);
                  this._count = this._size / this._stride;
                  this._flags = info.flags;

                  if (this._usage & BufferUsageBit.INDIRECT) {
                    this._indirectBuffer = new IndirectBuffer();
                  }

                  if (this._usage & BufferUsageBit.UNIFORM && this._size > 0) {
                    this._uniformBuffer = new Uint8Array(this._size);
                  }

                  this._gpuBuffer = {
                    usage: this._usage,
                    memUsage: this._memUsage,
                    size: this._size,
                    stride: this._stride,
                    buffer: null,
                    vf32: null,
                    indirects: [],
                    glTarget: 0,
                    glBuffer: null
                  };

                  if (info.usage & BufferUsageBit.INDIRECT) {
                    this._gpuBuffer.indirects = this._indirectBuffer.drawInfos;
                  }

                  if (this._usage & BufferUsageBit.UNIFORM) {
                    this._gpuBuffer.buffer = this._uniformBuffer;
                  }

                  WebGLCmdFuncCreateBuffer(this._device, this._gpuBuffer);
                  this._device.memoryStatus.bufferSize += this._size;
                }

                return true;
              };

              _proto.destroy = function destroy() {
                if (this._gpuBuffer) {
                  WebGLCmdFuncDestroyBuffer(this._device, this._gpuBuffer);
                  this._device.memoryStatus.bufferSize -= this._size;
                  this._gpuBuffer = null;
                }

                if (this._gpuBufferView) {
                  this._gpuBufferView = null;
                }
              };

              _proto.resize = function resize(size) {
                if (this._isBufferView) {
                  console.warn('cannot resize buffer views!');
                  return;
                }

                var oldSize = this._size;

                if (oldSize === size) {
                  return;
                }

                this._size = size;
                this._count = this._size / this._stride;

                if (this._uniformBuffer) {
                  this._uniformBuffer = new Uint8Array(size);
                }

                if (this._gpuBuffer) {
                  if (this._uniformBuffer) {
                    this._gpuBuffer.buffer = this._uniformBuffer;
                  }

                  this._gpuBuffer.size = size;

                  if (size > 0) {
                    WebGLCmdFuncResizeBuffer(this._device, this._gpuBuffer);
                    this._device.memoryStatus.bufferSize -= oldSize;
                    this._device.memoryStatus.bufferSize += size;
                  }
                }
              };

              _proto.update = function update(buffer, size) {
                if (this._isBufferView) {
                  console.warn('cannot update through buffer views!');
                  return;
                }

                var buffSize;

                if (size !== undefined) {
                  buffSize = size;
                } else if (this._usage & BufferUsageBit.INDIRECT) {
                  buffSize = 0;
                } else {
                  buffSize = buffer.byteLength;
                }

                WebGLCmdFuncUpdateBuffer(this._device, this._gpuBuffer, buffer, 0, buffSize);
              };

              _createClass(WebGLBuffer, [{
                key: "gpuBuffer",
                get: function get() {
                  return this._gpuBuffer;
                }
              }, {
                key: "gpuBufferView",
                get: function get() {
                  return this._gpuBufferView;
                }
              }]);

              return WebGLBuffer;
            }(Buffer);

            var WebGLCommandPool = function () {
              function WebGLCommandPool(Clazz, count) {
                this._frees = void 0;
                this._freeIdx = 0;
                this._freeCmds = void 0;
                this._frees = new Array(count);
                this._freeCmds = new CachedArray(count);

                for (var i = 0; i < count; ++i) {
                  this._frees[i] = new Clazz();
                }

                this._freeIdx = count - 1;
              }

              var _proto = WebGLCommandPool.prototype;

              _proto.alloc = function alloc(Clazz) {
                if (this._freeIdx < 0) {
                  var size = this._frees.length * 2;
                  var temp = this._frees;
                  this._frees = new Array(size);
                  var increase = size - temp.length;

                  for (var i = 0; i < increase; ++i) {
                    this._frees[i] = new Clazz();
                  }

                  for (var _i = increase, j = 0; _i < size; ++_i, ++j) {
                    this._frees[_i] = temp[j];
                  }

                  this._freeIdx += increase;
                }

                var cmd = this._frees[this._freeIdx];
                this._frees[this._freeIdx--] = null;
                ++cmd.refCount;
                return cmd;
              };

              _proto.free = function free(cmd) {
                if (--cmd.refCount === 0) {
                  this._freeCmds.push(cmd);
                }
              };

              _proto.freeCmds = function freeCmds(cmds) {
                for (var i = 0; i < cmds.length; ++i) {
                  if (--cmds.array[i].refCount === 0) {
                    this._freeCmds.push(cmds.array[i]);
                  }
                }
              };

              _proto.release = function release() {
                for (var i = 0; i < this._freeCmds.length; ++i) {
                  var cmd = this._freeCmds.array[i];
                  cmd.clear();
                  this._frees[++this._freeIdx] = cmd;
                }

                this._freeCmds.clear();
              };

              return WebGLCommandPool;
            }();
            var WebGLCommandAllocator = function () {
              function WebGLCommandAllocator() {
                this.beginRenderPassCmdPool = void 0;
                this.bindStatesCmdPool = void 0;
                this.drawCmdPool = void 0;
                this.updateBufferCmdPool = void 0;
                this.copyBufferToTextureCmdPool = void 0;
                this.beginRenderPassCmdPool = new WebGLCommandPool(WebGLCmdBeginRenderPass, 1);
                this.bindStatesCmdPool = new WebGLCommandPool(WebGLCmdBindStates, 1);
                this.drawCmdPool = new WebGLCommandPool(WebGLCmdDraw, 1);
                this.updateBufferCmdPool = new WebGLCommandPool(WebGLCmdUpdateBuffer, 1);
                this.copyBufferToTextureCmdPool = new WebGLCommandPool(WebGLCmdCopyBufferToTexture, 1);
              }

              var _proto2 = WebGLCommandAllocator.prototype;

              _proto2.clearCmds = function clearCmds(cmdPackage) {
                if (cmdPackage.beginRenderPassCmds.length) {
                  this.beginRenderPassCmdPool.freeCmds(cmdPackage.beginRenderPassCmds);
                  cmdPackage.beginRenderPassCmds.clear();
                }

                if (cmdPackage.bindStatesCmds.length) {
                  this.bindStatesCmdPool.freeCmds(cmdPackage.bindStatesCmds);
                  cmdPackage.bindStatesCmds.clear();
                }

                if (cmdPackage.drawCmds.length) {
                  this.drawCmdPool.freeCmds(cmdPackage.drawCmds);
                  cmdPackage.drawCmds.clear();
                }

                if (cmdPackage.updateBufferCmds.length) {
                  this.updateBufferCmdPool.freeCmds(cmdPackage.updateBufferCmds);
                  cmdPackage.updateBufferCmds.clear();
                }

                if (cmdPackage.copyBufferToTextureCmds.length) {
                  this.copyBufferToTextureCmdPool.freeCmds(cmdPackage.copyBufferToTextureCmds);
                  cmdPackage.copyBufferToTextureCmds.clear();
                }

                cmdPackage.cmds.clear();
              };

              _proto2.releaseCmds = function releaseCmds() {
                this.beginRenderPassCmdPool.release();
                this.bindStatesCmdPool.release();
                this.drawCmdPool.release();
                this.updateBufferCmdPool.release();
                this.copyBufferToTextureCmdPool.release();
              };

              return WebGLCommandAllocator;
            }();

            var WebGLCommandBuffer = function (_CommandBuffer) {
              _inheritsLoose(WebGLCommandBuffer, _CommandBuffer);

              function WebGLCommandBuffer() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _CommandBuffer.call.apply(_CommandBuffer, [this].concat(args)) || this;
                _this.cmdPackage = new WebGLCmdPackage();
                _this._webGLAllocator = null;
                _this._isInRenderPass = false;
                _this._curGPUPipelineState = null;
                _this._curGPUInputAssembler = null;
                _this._curGPUDescriptorSets = [];
                _this._curDynamicOffsets = Array(8).fill(0);
                _this._curDynamicStates = new DynamicStates();
                _this._isStateInvalied = false;
                return _this;
              }

              var _proto = WebGLCommandBuffer.prototype;

              _proto.initialize = function initialize(info) {
                this._type = info.type;
                this._queue = info.queue;
                this._webGLAllocator = this._device.cmdAllocator;
                var setCount = this._device.bindingMappingInfo.bufferOffsets.length;

                for (var i = 0; i < setCount; i++) {
                  this._curGPUDescriptorSets.push(null);
                }

                return true;
              };

              _proto.destroy = function destroy() {
                if (this._webGLAllocator) {
                  this._webGLAllocator.clearCmds(this.cmdPackage);

                  this._webGLAllocator = null;
                }
              };

              _proto.begin = function begin(renderPass, subpass, frameBuffer) {

                this._webGLAllocator.clearCmds(this.cmdPackage);

                this._curGPUPipelineState = null;
                this._curGPUInputAssembler = null;
                this._curGPUDescriptorSets.length = 0;
                this._numDrawCalls = 0;
                this._numInstances = 0;
                this._numTris = 0;
              };

              _proto.end = function end() {
                if (this._isStateInvalied) {
                  this.bindStates();
                }

                this._isInRenderPass = false;
              };

              _proto.beginRenderPass = function beginRenderPass(renderPass, framebuffer, renderArea, clearColors, clearDepth, clearStencil) {
                var cmd = this._webGLAllocator.beginRenderPassCmdPool.alloc(WebGLCmdBeginRenderPass);

                cmd.gpuRenderPass = renderPass.gpuRenderPass;
                cmd.gpuFramebuffer = framebuffer.gpuFramebuffer;
                cmd.renderArea = renderArea;
                cmd.clearColors.length = clearColors.length;

                for (var i = 0; i < clearColors.length; ++i) {
                  cmd.clearColors[i] = clearColors[i];
                }

                cmd.clearDepth = clearDepth;
                cmd.clearStencil = clearStencil;
                this.cmdPackage.beginRenderPassCmds.push(cmd);
                this.cmdPackage.cmds.push(WebGLCmd.BEGIN_RENDER_PASS);
                this._isInRenderPass = true;
              };

              _proto.endRenderPass = function endRenderPass() {
                this._isInRenderPass = false;
              };

              _proto.bindPipelineState = function bindPipelineState(pipelineState) {
                var gpuPipelineState = pipelineState.gpuPipelineState;

                if (gpuPipelineState !== this._curGPUPipelineState) {
                  this._curGPUPipelineState = gpuPipelineState;
                  this._isStateInvalied = true;
                }
              };

              _proto.bindDescriptorSet = function bindDescriptorSet(set, descriptorSet, dynamicOffsets) {
                var gpuDescriptorSet = descriptorSet.gpuDescriptorSet;

                if (gpuDescriptorSet !== this._curGPUDescriptorSets[set]) {
                  this._curGPUDescriptorSets[set] = gpuDescriptorSet;
                  this._isStateInvalied = true;
                }

                if (dynamicOffsets) {
                  var _this$_curGPUPipeline;

                  var gpuPipelineLayout = (_this$_curGPUPipeline = this._curGPUPipelineState) === null || _this$_curGPUPipeline === void 0 ? void 0 : _this$_curGPUPipeline.gpuPipelineLayout;

                  if (gpuPipelineLayout) {
                    var offsets = this._curDynamicOffsets;
                    var idx = gpuPipelineLayout.dynamicOffsetOffsets[set];

                    for (var i = 0; i < dynamicOffsets.length; i++) {
                      offsets[idx + i] = dynamicOffsets[i];
                    }

                    this._isStateInvalied = true;
                  }
                }
              };

              _proto.bindInputAssembler = function bindInputAssembler(inputAssembler) {
                var gpuInputAssembler = inputAssembler.gpuInputAssembler;
                this._curGPUInputAssembler = gpuInputAssembler;
                this._isStateInvalied = true;
              };

              _proto.setViewport = function setViewport(viewport) {
                var cache = this._curDynamicStates.viewport;

                if (cache.left !== viewport.left || cache.top !== viewport.top || cache.width !== viewport.width || cache.height !== viewport.height || cache.minDepth !== viewport.minDepth || cache.maxDepth !== viewport.maxDepth) {
                  cache.left = viewport.left;
                  cache.top = viewport.top;
                  cache.width = viewport.width;
                  cache.height = viewport.height;
                  cache.minDepth = viewport.minDepth;
                  cache.maxDepth = viewport.maxDepth;
                  this._isStateInvalied = true;
                }
              };

              _proto.setScissor = function setScissor(scissor) {
                var cache = this._curDynamicStates.scissor;

                if (cache.x !== scissor.x || cache.y !== scissor.y || cache.width !== scissor.width || cache.height !== scissor.height) {
                  cache.x = scissor.x;
                  cache.y = scissor.y;
                  cache.width = scissor.width;
                  cache.height = scissor.height;
                  this._isStateInvalied = true;
                }
              };

              _proto.setLineWidth = function setLineWidth(lineWidth) {
                if (this._curDynamicStates.lineWidth !== lineWidth) {
                  this._curDynamicStates.lineWidth = lineWidth;
                  this._isStateInvalied = true;
                }
              };

              _proto.setDepthBias = function setDepthBias(depthBiasConstantFactor, depthBiasClamp, depthBiasSlopeFactor) {
                var cache = this._curDynamicStates;

                if (cache.depthBiasConstant !== depthBiasConstantFactor || cache.depthBiasClamp !== depthBiasClamp || cache.depthBiasSlope !== depthBiasSlopeFactor) {
                  cache.depthBiasConstant = depthBiasConstantFactor;
                  cache.depthBiasClamp = depthBiasClamp;
                  cache.depthBiasSlope = depthBiasSlopeFactor;
                  this._isStateInvalied = true;
                }
              };

              _proto.setBlendConstants = function setBlendConstants(blendConstants) {
                var cache = this._curDynamicStates.blendConstant;

                if (cache.x !== blendConstants.x || cache.y !== blendConstants.y || cache.z !== blendConstants.z || cache.w !== blendConstants.w) {
                  cache.copy(blendConstants);
                  this._isStateInvalied = true;
                }
              };

              _proto.setDepthBound = function setDepthBound(minDepthBounds, maxDepthBounds) {
                var cache = this._curDynamicStates;

                if (cache.depthMinBounds !== minDepthBounds || cache.depthMaxBounds !== maxDepthBounds) {
                  cache.depthMinBounds = minDepthBounds;
                  cache.depthMaxBounds = maxDepthBounds;
                  this._isStateInvalied = true;
                }
              };

              _proto.setStencilWriteMask = function setStencilWriteMask(face, writeMask) {
                var front = this._curDynamicStates.stencilStatesFront;
                var back = this._curDynamicStates.stencilStatesBack;

                if (face & StencilFace.FRONT) {
                  if (front.writeMask !== writeMask) {
                    front.writeMask = writeMask;
                    this._isStateInvalied = true;
                  }
                }

                if (face & StencilFace.BACK) {
                  if (back.writeMask !== writeMask) {
                    back.writeMask = writeMask;
                    this._isStateInvalied = true;
                  }
                }
              };

              _proto.setStencilCompareMask = function setStencilCompareMask(face, reference, compareMask) {
                var front = this._curDynamicStates.stencilStatesFront;
                var back = this._curDynamicStates.stencilStatesBack;

                if (face & StencilFace.FRONT) {
                  if (front.compareMask !== compareMask || front.reference !== reference) {
                    front.reference = reference;
                    front.compareMask = compareMask;
                    this._isStateInvalied = true;
                  }
                }

                if (face & StencilFace.BACK) {
                  if (back.compareMask !== compareMask || back.reference !== reference) {
                    back.reference = reference;
                    back.compareMask = compareMask;
                    this._isStateInvalied = true;
                  }
                }
              };

              _proto.draw = function draw(info) {
                if (this._type === CommandBufferType.PRIMARY && this._isInRenderPass || this._type === CommandBufferType.SECONDARY) {
                  if (this._isStateInvalied) {
                    this.bindStates();
                  }

                  var cmd = this._webGLAllocator.drawCmdPool.alloc(WebGLCmdDraw);

                  cmd.drawInfo.vertexCount = info.vertexCount;
                  cmd.drawInfo.firstVertex = info.firstVertex;
                  cmd.drawInfo.indexCount = info.indexCount;
                  cmd.drawInfo.firstIndex = info.firstIndex;
                  cmd.drawInfo.vertexOffset = info.vertexOffset;
                  cmd.drawInfo.instanceCount = info.instanceCount;
                  cmd.drawInfo.firstInstance = info.firstInstance;
                  this.cmdPackage.drawCmds.push(cmd);
                  this.cmdPackage.cmds.push(WebGLCmd.DRAW);
                  ++this._numDrawCalls;
                  this._numInstances += info.instanceCount;
                  var indexCount = info.indexCount || info.vertexCount;

                  if (this._curGPUPipelineState) {
                    var glPrimitive = this._curGPUPipelineState.glPrimitive;

                    switch (glPrimitive) {
                      case 0x0004:
                        {
                          this._numTris += indexCount / 3 * Math.max(info.instanceCount, 1);
                          break;
                        }

                      case 0x0005:
                      case 0x0006:
                        {
                          this._numTris += (indexCount - 2) * Math.max(info.instanceCount, 1);
                          break;
                        }
                    }
                  }
                } else {
                  console.error('Command \'draw\' must be recorded inside a render pass.');
                }
              };

              _proto.updateBuffer = function updateBuffer(buffer, data, size) {
                if (this._type === CommandBufferType.PRIMARY && !this._isInRenderPass || this._type === CommandBufferType.SECONDARY) {
                  var gpuBuffer = buffer.gpuBuffer;

                  if (gpuBuffer) {
                    var cmd = this._webGLAllocator.updateBufferCmdPool.alloc(WebGLCmdUpdateBuffer);

                    var buffSize = 0;
                    var buff = null;

                    if (buffer.usage & BufferUsageBit.INDIRECT) {
                      buff = data;
                    } else {
                      if (size !== undefined) {
                        buffSize = size;
                      } else {
                        buffSize = data.byteLength;
                      }

                      buff = data;
                    }

                    cmd.gpuBuffer = gpuBuffer;
                    cmd.buffer = buff;
                    cmd.offset = 0;
                    cmd.size = buffSize;
                    this.cmdPackage.updateBufferCmds.push(cmd);
                    this.cmdPackage.cmds.push(WebGLCmd.UPDATE_BUFFER);
                  }
                } else {
                  console.error('Command \'updateBuffer\' must be recorded outside a render pass.');
                }
              };

              _proto.copyBuffersToTexture = function copyBuffersToTexture(buffers, texture, regions) {
                if (this._type === CommandBufferType.PRIMARY && !this._isInRenderPass || this._type === CommandBufferType.SECONDARY) {
                  var gpuTexture = texture.gpuTexture;

                  if (gpuTexture) {
                    var cmd = this._webGLAllocator.copyBufferToTextureCmdPool.alloc(WebGLCmdCopyBufferToTexture);

                    if (cmd) {
                      cmd.gpuTexture = gpuTexture;
                      cmd.regions = regions;
                      cmd.buffers = buffers;
                      this.cmdPackage.copyBufferToTextureCmds.push(cmd);
                      this.cmdPackage.cmds.push(WebGLCmd.COPY_BUFFER_TO_TEXTURE);
                    }
                  }
                } else {
                  console.error('Command \'copyBufferToTexture\' must be recorded outside a render pass.');
                }
              };

              _proto.execute = function execute(cmdBuffs, count) {
                for (var i = 0; i < count; ++i) {
                  var webGLCmdBuff = cmdBuffs[i];

                  for (var c = 0; c < webGLCmdBuff.cmdPackage.beginRenderPassCmds.length; ++c) {
                    var cmd = webGLCmdBuff.cmdPackage.beginRenderPassCmds.array[c];
                    ++cmd.refCount;
                    this.cmdPackage.beginRenderPassCmds.push(cmd);
                  }

                  for (var _c = 0; _c < webGLCmdBuff.cmdPackage.bindStatesCmds.length; ++_c) {
                    var _cmd = webGLCmdBuff.cmdPackage.bindStatesCmds.array[_c];
                    ++_cmd.refCount;
                    this.cmdPackage.bindStatesCmds.push(_cmd);
                  }

                  for (var _c2 = 0; _c2 < webGLCmdBuff.cmdPackage.drawCmds.length; ++_c2) {
                    var _cmd2 = webGLCmdBuff.cmdPackage.drawCmds.array[_c2];
                    ++_cmd2.refCount;
                    this.cmdPackage.drawCmds.push(_cmd2);
                  }

                  for (var _c3 = 0; _c3 < webGLCmdBuff.cmdPackage.updateBufferCmds.length; ++_c3) {
                    var _cmd3 = webGLCmdBuff.cmdPackage.updateBufferCmds.array[_c3];
                    ++_cmd3.refCount;
                    this.cmdPackage.updateBufferCmds.push(_cmd3);
                  }

                  for (var _c4 = 0; _c4 < webGLCmdBuff.cmdPackage.copyBufferToTextureCmds.length; ++_c4) {
                    var _cmd4 = webGLCmdBuff.cmdPackage.copyBufferToTextureCmds.array[_c4];
                    ++_cmd4.refCount;
                    this.cmdPackage.copyBufferToTextureCmds.push(_cmd4);
                  }

                  this.cmdPackage.cmds.concat(webGLCmdBuff.cmdPackage.cmds.array);
                  this._numDrawCalls += webGLCmdBuff._numDrawCalls;
                  this._numInstances += webGLCmdBuff._numInstances;
                  this._numTris += webGLCmdBuff._numTris;
                }
              };

              _proto.pipelineBarrier = function pipelineBarrier(globalBarrier, textureBarriers) {};

              _proto.bindStates = function bindStates() {
                var bindStatesCmd = this._webGLAllocator.bindStatesCmdPool.alloc(WebGLCmdBindStates);

                if (bindStatesCmd) {
                  bindStatesCmd.gpuPipelineState = this._curGPUPipelineState;
                  Array.prototype.push.apply(bindStatesCmd.gpuDescriptorSets, this._curGPUDescriptorSets);
                  Array.prototype.push.apply(bindStatesCmd.dynamicOffsets, this._curDynamicOffsets);
                  bindStatesCmd.gpuInputAssembler = this._curGPUInputAssembler;
                  bindStatesCmd.dynamicStates.copy(this._curDynamicStates);
                  this.cmdPackage.bindStatesCmds.push(bindStatesCmd);
                  this.cmdPackage.cmds.push(WebGLCmd.BIND_STATES);
                  this._isStateInvalied = false;
                }
              };

              _createClass(WebGLCommandBuffer, [{
                key: "webGLDevice",
                get: function get() {
                  return this._device;
                }
              }]);

              return WebGLCommandBuffer;
            }(CommandBuffer);

            var WebGLFramebuffer = function (_Framebuffer) {
              _inheritsLoose(WebGLFramebuffer, _Framebuffer);

              function WebGLFramebuffer() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Framebuffer.call.apply(_Framebuffer, [this].concat(args)) || this;
                _this._gpuFramebuffer = null;
                return _this;
              }

              var _proto = WebGLFramebuffer.prototype;

              _proto.initialize = function initialize(info) {
                this._renderPass = info.renderPass;
                this._colorTextures = info.colorTextures || [];
                this._depthStencilTexture = info.depthStencilTexture || null;

                if (info.depthStencilMipmapLevel !== 0) {
                  console.warn('The mipmap level of th texture image to be attached of depth stencil attachment should be 0. Convert to 0.');
                }

                for (var i = 0; i < info.colorMipmapLevels.length; ++i) {
                  if (info.colorMipmapLevels[i] !== 0) {
                    console.warn("The mipmap level of th texture image to be attached of color attachment " + i + " should be 0. Convert to 0.");
                  }
                }

                var gpuColorTextures = [];

                for (var _i = 0; _i < info.colorTextures.length; ++_i) {
                  var colorTexture = info.colorTextures[_i];

                  if (colorTexture) {
                    gpuColorTextures.push(colorTexture.gpuTexture);
                  }
                }

                var gpuDepthStencilTexture = null;

                if (info.depthStencilTexture) {
                  gpuDepthStencilTexture = info.depthStencilTexture.gpuTexture;
                }

                this._gpuFramebuffer = {
                  gpuRenderPass: info.renderPass.gpuRenderPass,
                  gpuColorTextures: gpuColorTextures,
                  gpuDepthStencilTexture: gpuDepthStencilTexture,
                  glFramebuffer: null
                };
                WebGLCmdFuncCreateFramebuffer(this._device, this._gpuFramebuffer);
                return true;
              };

              _proto.destroy = function destroy() {
                if (this._gpuFramebuffer) {
                  WebGLCmdFuncDestroyFramebuffer(this._device, this._gpuFramebuffer);
                  this._gpuFramebuffer = null;
                }
              };

              _createClass(WebGLFramebuffer, [{
                key: "gpuFramebuffer",
                get: function get() {
                  return this._gpuFramebuffer;
                }
              }]);

              return WebGLFramebuffer;
            }(Framebuffer);

            var WebGLInputAssembler = function (_InputAssembler) {
              _inheritsLoose(WebGLInputAssembler, _InputAssembler);

              function WebGLInputAssembler() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _InputAssembler.call.apply(_InputAssembler, [this].concat(args)) || this;
                _this._gpuInputAssembler = null;
                return _this;
              }

              var _proto = WebGLInputAssembler.prototype;

              _proto.initialize = function initialize(info) {
                if (info.vertexBuffers.length === 0) {
                  console.error('InputAssemblerInfo.vertexBuffers is null.');
                  return false;
                }

                this._attributes = info.attributes;
                this._attributesHash = this.computeAttributesHash();
                this._vertexBuffers = info.vertexBuffers;

                if (info.indexBuffer) {
                  this._indexBuffer = info.indexBuffer;
                  this._indexCount = this._indexBuffer.size / this._indexBuffer.stride;
                  this._firstIndex = 0;
                } else {
                  var vertBuff = this._vertexBuffers[0];
                  this._vertexCount = vertBuff.size / vertBuff.stride;
                  this._firstVertex = 0;
                  this._vertexOffset = 0;
                }

                this._instanceCount = 0;
                this._firstInstance = 0;
                this._indirectBuffer = info.indirectBuffer || null;
                var gpuVertexBuffers = new Array(info.vertexBuffers.length);

                for (var i = 0; i < info.vertexBuffers.length; ++i) {
                  var vb = info.vertexBuffers[i];

                  if (vb.gpuBuffer) {
                    gpuVertexBuffers[i] = vb.gpuBuffer;
                  }
                }

                var gpuIndexBuffer = null;
                var glIndexType = 0;

                if (info.indexBuffer) {
                  gpuIndexBuffer = info.indexBuffer.gpuBuffer;

                  if (gpuIndexBuffer) {
                    switch (gpuIndexBuffer.stride) {
                      case 1:
                        glIndexType = 0x1401;
                        break;

                      case 2:
                        glIndexType = 0x1403;
                        break;

                      case 4:
                        glIndexType = 0x1405;
                        break;

                      default:
                        {
                          console.error('Error index buffer stride.');
                        }
                    }
                  }
                }

                var gpuIndirectBuffer = null;

                if (info.indirectBuffer) {
                  gpuIndirectBuffer = info.indirectBuffer.gpuBuffer;
                }

                this._gpuInputAssembler = {
                  attributes: info.attributes,
                  gpuVertexBuffers: gpuVertexBuffers,
                  gpuIndexBuffer: gpuIndexBuffer,
                  gpuIndirectBuffer: gpuIndirectBuffer,
                  glAttribs: [],
                  glIndexType: glIndexType,
                  glVAOs: new Map()
                };
                WebGLCmdFuncCreateInputAssember(this._device, this._gpuInputAssembler);
                return true;
              };

              _proto.destroy = function destroy() {
                var webglDev = this._device;

                if (this._gpuInputAssembler && webglDev.useVAO) {
                  WebGLCmdFuncDestroyInputAssembler(webglDev, this._gpuInputAssembler);
                }

                this._gpuInputAssembler = null;
              };

              _createClass(WebGLInputAssembler, [{
                key: "gpuInputAssembler",
                get: function get() {
                  return this._gpuInputAssembler;
                }
              }]);

              return WebGLInputAssembler;
            }(InputAssembler);

            var WebGLDescriptorSetLayout = function (_DescriptorSetLayout) {
              _inheritsLoose(WebGLDescriptorSetLayout, _DescriptorSetLayout);

              function WebGLDescriptorSetLayout() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _DescriptorSetLayout.call.apply(_DescriptorSetLayout, [this].concat(args)) || this;
                _this._gpuDescriptorSetLayout = null;
                return _this;
              }

              var _proto = WebGLDescriptorSetLayout.prototype;

              _proto.initialize = function initialize(info) {
                Array.prototype.push.apply(this._bindings, info.bindings);
                var descriptorCount = 0;
                var maxBinding = -1;
                var flattenedIndices = [];

                for (var i = 0; i < this._bindings.length; i++) {
                  var binding = this._bindings[i];
                  flattenedIndices.push(descriptorCount);
                  descriptorCount += binding.count;
                  if (binding.binding > maxBinding) maxBinding = binding.binding;
                }

                this._bindingIndices = Array(maxBinding + 1).fill(-1);
                var descriptorIndices = this._descriptorIndices = Array(maxBinding + 1).fill(-1);

                for (var _i = 0; _i < this._bindings.length; _i++) {
                  var _binding = this._bindings[_i];
                  this._bindingIndices[_binding.binding] = _i;
                  descriptorIndices[_binding.binding] = flattenedIndices[_i];
                }

                var dynamicBindings = [];

                for (var _i2 = 0; _i2 < this._bindings.length; _i2++) {
                  var _binding2 = this._bindings[_i2];

                  if (_binding2.descriptorType & DESCRIPTOR_DYNAMIC_TYPE) {
                    for (var j = 0; j < _binding2.count; j++) {
                      dynamicBindings.push(_binding2.binding);
                    }
                  }
                }

                this._gpuDescriptorSetLayout = {
                  bindings: this._bindings,
                  dynamicBindings: dynamicBindings,
                  descriptorIndices: descriptorIndices,
                  descriptorCount: descriptorCount
                };
                return true;
              };

              _proto.destroy = function destroy() {
                this._bindings.length = 0;
              };

              _createClass(WebGLDescriptorSetLayout, [{
                key: "gpuDescriptorSetLayout",
                get: function get() {
                  return this._gpuDescriptorSetLayout;
                }
              }]);

              return WebGLDescriptorSetLayout;
            }(DescriptorSetLayout);

            var WebGLPipelineLayout = function (_PipelineLayout) {
              _inheritsLoose(WebGLPipelineLayout, _PipelineLayout);

              function WebGLPipelineLayout() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _PipelineLayout.call.apply(_PipelineLayout, [this].concat(args)) || this;
                _this._gpuPipelineLayout = null;
                return _this;
              }

              var _proto = WebGLPipelineLayout.prototype;

              _proto.initialize = function initialize(info) {
                Array.prototype.push.apply(this._setLayouts, info.setLayouts);
                var dynamicOffsetIndices = [];
                var gpuSetLayouts = [];
                var dynamicOffsetCount = 0;
                var dynamicOffsetOffsets = [];

                for (var i = 0; i < this._setLayouts.length; i++) {
                  var setLayout = this._setLayouts[i];
                  var dynamicBindings = setLayout.gpuDescriptorSetLayout.dynamicBindings;
                  var indices = Array(setLayout.bindingIndices.length).fill(-1);

                  for (var j = 0; j < dynamicBindings.length; j++) {
                    var binding = dynamicBindings[j];
                    if (indices[binding] < 0) indices[binding] = dynamicOffsetCount + j;
                  }

                  gpuSetLayouts.push(setLayout.gpuDescriptorSetLayout);
                  dynamicOffsetIndices.push(indices);
                  dynamicOffsetOffsets.push(dynamicOffsetCount);
                  dynamicOffsetCount += dynamicBindings.length;
                }

                this._gpuPipelineLayout = {
                  gpuSetLayouts: gpuSetLayouts,
                  dynamicOffsetIndices: dynamicOffsetIndices,
                  dynamicOffsetCount: dynamicOffsetCount,
                  dynamicOffsetOffsets: dynamicOffsetOffsets
                };
                return true;
              };

              _proto.destroy = function destroy() {
                this._setLayouts.length = 0;
              };

              _createClass(WebGLPipelineLayout, [{
                key: "gpuPipelineLayout",
                get: function get() {
                  return this._gpuPipelineLayout;
                }
              }]);

              return WebGLPipelineLayout;
            }(PipelineLayout);

            var WebGLPrimitives = [0x0000, 0x0001, 0x0003, 0x0002, 0x0000, 0x0000, 0x0000, 0x0004, 0x0005, 0x0006, 0x0000, 0x0000, 0x0000, 0x0000];
            var WebGLPipelineState = function (_PipelineState) {
              _inheritsLoose(WebGLPipelineState, _PipelineState);

              function WebGLPipelineState() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _PipelineState.call.apply(_PipelineState, [this].concat(args)) || this;
                _this._gpuPipelineState = null;
                return _this;
              }

              var _proto = WebGLPipelineState.prototype;

              _proto.initialize = function initialize(info) {
                this._primitive = info.primitive;
                this._shader = info.shader;
                this._pipelineLayout = info.pipelineLayout;
                var bs = this._bs;

                if (info.blendState) {
                  var bsInfo = info.blendState;
                  var targets = bsInfo.targets;

                  if (targets) {
                    targets.forEach(function (t, i) {
                      bs.setTarget(i, t);
                    });
                  }

                  if (bsInfo.isA2C !== undefined) {
                    bs.isA2C = bsInfo.isA2C;
                  }

                  if (bsInfo.isIndepend !== undefined) {
                    bs.isIndepend = bsInfo.isIndepend;
                  }

                  if (bsInfo.blendColor !== undefined) {
                    bs.blendColor = bsInfo.blendColor;
                  }
                }

                Object.assign(this._rs, info.rasterizerState);
                Object.assign(this._dss, info.depthStencilState);
                this._is = info.inputState;
                this._renderPass = info.renderPass;
                this._dynamicStates = info.dynamicStates;
                var dynamicStates = [];

                for (var i = 0; i < 31; i++) {
                  if (this._dynamicStates & 1 << i) {
                    dynamicStates.push(1 << i);
                  }
                }

                this._gpuPipelineState = {
                  glPrimitive: WebGLPrimitives[info.primitive],
                  gpuShader: info.shader.gpuShader,
                  gpuPipelineLayout: info.pipelineLayout.gpuPipelineLayout,
                  rs: info.rasterizerState,
                  dss: info.depthStencilState,
                  bs: info.blendState,
                  gpuRenderPass: info.renderPass.gpuRenderPass,
                  dynamicStates: dynamicStates
                };
                return true;
              };

              _proto.destroy = function destroy() {
                this._gpuPipelineState = null;
              };

              _createClass(WebGLPipelineState, [{
                key: "gpuPipelineState",
                get: function get() {
                  return this._gpuPipelineState;
                }
              }]);

              return WebGLPipelineState;
            }(PipelineState);

            var WebGLPrimaryCommandBuffer = function (_WebGLCommandBuffer) {
              _inheritsLoose(WebGLPrimaryCommandBuffer, _WebGLCommandBuffer);

              function WebGLPrimaryCommandBuffer() {
                return _WebGLCommandBuffer.apply(this, arguments) || this;
              }

              var _proto = WebGLPrimaryCommandBuffer.prototype;

              _proto.beginRenderPass = function beginRenderPass(renderPass, framebuffer, renderArea, clearColors, clearDepth, clearStencil) {
                WebGLCmdFuncBeginRenderPass(this._device, renderPass.gpuRenderPass, framebuffer.gpuFramebuffer, renderArea, clearColors, clearDepth, clearStencil);
                this._isInRenderPass = true;
              };

              _proto.draw = function draw(info) {
                if (this._isInRenderPass) {
                  if (this._isStateInvalied) {
                    this.bindStates();
                  }

                  WebGLCmdFuncDraw(this._device, info);
                  ++this._numDrawCalls;
                  this._numInstances += info.instanceCount;
                  var indexCount = info.indexCount || info.vertexCount;

                  if (this._curGPUPipelineState) {
                    var glPrimitive = this._curGPUPipelineState.glPrimitive;

                    switch (glPrimitive) {
                      case 0x0004:
                        {
                          this._numTris += indexCount / 3 * Math.max(info.instanceCount, 1);
                          break;
                        }

                      case 0x0005:
                      case 0x0006:
                        {
                          this._numTris += (indexCount - 2) * Math.max(info.instanceCount, 1);
                          break;
                        }
                    }
                  }
                } else {
                  console.error('Command \'draw\' must be recorded inside a render pass.');
                }
              };

              _proto.updateBuffer = function updateBuffer(buffer, data, size) {
                if (!this._isInRenderPass) {
                  var gpuBuffer = buffer.gpuBuffer;

                  if (gpuBuffer) {
                    var buffSize;

                    if (size !== undefined) {
                      buffSize = size;
                    } else if (buffer.usage & BufferUsageBit.INDIRECT) {
                      buffSize = 0;
                    } else {
                      buffSize = data.byteLength;
                    }

                    WebGLCmdFuncUpdateBuffer(this._device, gpuBuffer, data, 0, buffSize);
                  }
                } else {
                  console.error('Command \'updateBuffer\' must be recorded outside a render pass.');
                }
              };

              _proto.copyBuffersToTexture = function copyBuffersToTexture(buffers, texture, regions) {
                if (!this._isInRenderPass) {
                  var gpuTexture = texture.gpuTexture;

                  if (gpuTexture) {
                    WebGLCmdFuncCopyBuffersToTexture(this._device, buffers, gpuTexture, regions);
                  }
                } else {
                  console.error('Command \'copyBufferToTexture\' must be recorded outside a render pass.');
                }
              };

              _proto.execute = function execute(cmdBuffs, count) {
                for (var i = 0; i < count; ++i) {
                  var webGLCmdBuff = cmdBuffs[i];
                  WebGLCmdFuncExecuteCmds(this._device, webGLCmdBuff.cmdPackage);
                  this._numDrawCalls += webGLCmdBuff._numDrawCalls;
                  this._numInstances += webGLCmdBuff._numInstances;
                  this._numTris += webGLCmdBuff._numTris;
                }
              };

              _proto.bindStates = function bindStates() {
                WebGLCmdFuncBindStates(this._device, this._curGPUPipelineState, this._curGPUInputAssembler, this._curGPUDescriptorSets, this._curDynamicOffsets, this._curDynamicStates);
                this._isStateInvalied = false;
              };

              return WebGLPrimaryCommandBuffer;
            }(WebGLCommandBuffer);

            var WebGLQueue = function (_Queue) {
              _inheritsLoose(WebGLQueue, _Queue);

              function WebGLQueue() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Queue.call.apply(_Queue, [this].concat(args)) || this;
                _this.numDrawCalls = 0;
                _this.numInstances = 0;
                _this.numTris = 0;
                return _this;
              }

              var _proto = WebGLQueue.prototype;

              _proto.initialize = function initialize(info) {
                this._type = info.type;
                return true;
              };

              _proto.destroy = function destroy() {};

              _proto.submit = function submit(cmdBuffs) {
                if (!this._isAsync) {
                  var len = cmdBuffs.length;

                  for (var i = 0; i < len; i++) {
                    var cmdBuff = cmdBuffs[i];
                    this.numDrawCalls += cmdBuff.numDrawCalls;
                    this.numInstances += cmdBuff.numInstances;
                    this.numTris += cmdBuff.numTris;
                  }
                }
              };

              _proto.clear = function clear() {
                this.numDrawCalls = 0;
                this.numInstances = 0;
                this.numTris = 0;
              };

              return WebGLQueue;
            }(Queue);

            var WebGLRenderPass = function (_RenderPass) {
              _inheritsLoose(WebGLRenderPass, _RenderPass);

              function WebGLRenderPass() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _RenderPass.call.apply(_RenderPass, [this].concat(args)) || this;
                _this._gpuRenderPass = null;
                return _this;
              }

              var _proto = WebGLRenderPass.prototype;

              _proto.initialize = function initialize(info) {
                this._colorInfos = info.colorAttachments;
                this._depthStencilInfo = info.depthStencilAttachment;

                if (info.subpasses) {
                  this._subpasses = info.subpasses;
                }

                this._gpuRenderPass = {
                  colorAttachments: this._colorInfos,
                  depthStencilAttachment: this._depthStencilInfo
                };
                this._hash = this.computeHash();
                return true;
              };

              _proto.destroy = function destroy() {
                this._gpuRenderPass = null;
              };

              _createClass(WebGLRenderPass, [{
                key: "gpuRenderPass",
                get: function get() {
                  return this._gpuRenderPass;
                }
              }]);

              return WebGLRenderPass;
            }(RenderPass);

            var WebGLWraps = [0x2901, 0x8370, 0x812F, 0x812F];
            var WebGLSampler = function (_Sampler) {
              _inheritsLoose(WebGLSampler, _Sampler);

              function WebGLSampler() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Sampler.call.apply(_Sampler, [this].concat(args)) || this;
                _this._gpuSampler = null;
                return _this;
              }

              var _proto = WebGLSampler.prototype;

              _proto.initialize = function initialize(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;
                this._borderColor = info.borderColor;
                this._mipLODBias = info.mipLODBias;
                var glMinFilter = 0;
                var glMagFilter = 0;
                var minFilter = this._minFilter;
                var magFilter = this._magFilter;
                var mipFilter = this._mipFilter;

                if (minFilter === Filter.LINEAR || minFilter === Filter.ANISOTROPIC) {
                  if (mipFilter === Filter.LINEAR || mipFilter === Filter.ANISOTROPIC) {
                    glMinFilter = 0x2703;
                  } else if (mipFilter === Filter.POINT) {
                    glMinFilter = 0x2701;
                  } else {
                    glMinFilter = 0x2601;
                  }
                } else if (mipFilter === Filter.LINEAR || mipFilter === Filter.ANISOTROPIC) {
                  glMinFilter = 0x2702;
                } else if (mipFilter === Filter.POINT) {
                  glMinFilter = 0x2700;
                } else {
                  glMinFilter = 0x2600;
                }

                if (magFilter === Filter.LINEAR || magFilter === Filter.ANISOTROPIC) {
                  glMagFilter = 0x2601;
                } else {
                  glMagFilter = 0x2600;
                }

                var glWrapS = WebGLWraps[this._addressU];
                var glWrapT = WebGLWraps[this._addressV];
                var glWrapR = WebGLWraps[this._addressW];
                this._gpuSampler = {
                  glMinFilter: glMinFilter,
                  glMagFilter: glMagFilter,
                  glWrapS: glWrapS,
                  glWrapT: glWrapT,
                  glWrapR: glWrapR
                };
                return true;
              };

              _proto.destroy = function destroy() {
                this._gpuSampler = null;
              };

              _createClass(WebGLSampler, [{
                key: "gpuSampler",
                get: function get() {
                  return this._gpuSampler;
                }
              }]);

              return WebGLSampler;
            }(Sampler);

            var WebGLShader = function (_Shader) {
              _inheritsLoose(WebGLShader, _Shader);

              function WebGLShader() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Shader.call.apply(_Shader, [this].concat(args)) || this;
                _this._gpuShader = null;
                return _this;
              }

              var _proto = WebGLShader.prototype;

              _proto.initialize = function initialize(info) {
                this._name = info.name;
                this._stages = info.stages;
                this._attributes = info.attributes;
                this._blocks = info.blocks;
                this._samplers = info.samplers;
                this._gpuShader = {
                  name: info.name,
                  blocks: info.blocks,
                  samplerTextures: info.samplerTextures,
                  gpuStages: new Array(info.stages.length),
                  glProgram: null,
                  glInputs: [],
                  glUniforms: [],
                  glBlocks: [],
                  glSamplerTextures: []
                };

                for (var i = 0; i < info.stages.length; ++i) {
                  var stage = info.stages[i];
                  this._gpuShader.gpuStages[i] = {
                    type: stage.stage,
                    source: stage.source,
                    glShader: null
                  };
                }

                WebGLCmdFuncCreateShader(this._device, this._gpuShader);
                return true;
              };

              _proto.destroy = function destroy() {
                if (this._gpuShader) {
                  WebGLCmdFuncDestroyShader(this._device, this._gpuShader);
                  this._gpuShader = null;
                }
              };

              _createClass(WebGLShader, [{
                key: "gpuShader",
                get: function get() {
                  return this._gpuShader;
                }
              }]);

              return WebGLShader;
            }(Shader);

            var WebGLStateCache = function () {
              function WebGLStateCache() {
                this.glArrayBuffer = null;
                this.glElementArrayBuffer = null;
                this.glVAO = null;
                this.texUnit = 0;
                this.glTexUnits = [];
                this.glRenderbuffer = null;
                this.glFramebuffer = null;
                this.viewport = new Viewport();
                this.scissorRect = new Rect$1(0, 0, 0, 0);
                this.rs = new RasterizerState();
                this.dss = new DepthStencilState();
                this.bs = new BlendState();
                this.glProgram = null;
                this.glEnabledAttribLocs = [];
                this.glCurrentAttribLocs = [];
                this.texUnitCacheMap = {};
              }

              var _proto = WebGLStateCache.prototype;

              _proto.initialize = function initialize(texUnit, vertexAttributes) {
                for (var i = 0; i < texUnit; ++i) {
                  this.glTexUnits.push({
                    glTexture: null
                  });
                }

                this.glEnabledAttribLocs.length = vertexAttributes;
                this.glEnabledAttribLocs.fill(false);
                this.glCurrentAttribLocs.length = vertexAttributes;
                this.glCurrentAttribLocs.fill(false);
              };

              return WebGLStateCache;
            }();

            var WebGLTexture = function (_Texture) {
              _inheritsLoose(WebGLTexture, _Texture);

              function WebGLTexture() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Texture.call.apply(_Texture, [this].concat(args)) || this;
                _this._gpuTexture = null;
                return _this;
              }

              var _proto = WebGLTexture.prototype;

              _proto.initialize = function initialize(info) {
                if ('texture' in info) {
                  console.log('WebGL does not support texture view.');
                  return false;
                }

                this._type = info.type;
                this._usage = info.usage;
                this._format = info.format;
                this._width = info.width;
                this._height = info.height;
                this._depth = info.depth;
                this._layerCount = info.layerCount;
                this._levelCount = info.levelCount;
                this._samples = info.samples;
                this._flags = info.flags;
                this._isPowerOf2 = IsPowerOf2(this._width) && IsPowerOf2(this._height);
                this._size = FormatSurfaceSize(this._format, this.width, this.height, this.depth, this._levelCount) * this._layerCount;
                this._gpuTexture = {
                  type: this._type,
                  format: this._format,
                  usage: this._usage,
                  width: this._width,
                  height: this._height,
                  depth: this._depth,
                  size: this._size,
                  arrayLayer: this._layerCount,
                  mipLevel: this._levelCount,
                  samples: this._samples,
                  flags: this._flags,
                  isPowerOf2: this._isPowerOf2,
                  glTarget: 0,
                  glInternalFmt: 0,
                  glFormat: 0,
                  glType: 0,
                  glUsage: 0,
                  glTexture: null,
                  glRenderbuffer: null,
                  glWrapS: 0,
                  glWrapT: 0,
                  glMinFilter: 0,
                  glMagFilter: 0
                };
                WebGLCmdFuncCreateTexture(this._device, this._gpuTexture);
                this._device.memoryStatus.textureSize += this._size;
                return true;
              };

              _proto.destroy = function destroy() {
                if (this._gpuTexture) {
                  WebGLCmdFuncDestroyTexture(this._device, this._gpuTexture);
                  this._device.memoryStatus.textureSize -= this._size;
                  this._gpuTexture = null;
                }
              };

              _proto.resize = function resize(width, height) {
                var oldSize = this._size;
                this._width = width;
                this._height = height;
                this._size = FormatSurfaceSize(this._format, this.width, this.height, this.depth, this._levelCount) * this._layerCount;

                if (this._gpuTexture) {
                  this._gpuTexture.width = width;
                  this._gpuTexture.height = height;
                  this._gpuTexture.size = this._size;
                  WebGLCmdFuncResizeTexture(this._device, this._gpuTexture);
                  this._device.memoryStatus.textureSize -= oldSize;
                  this._device.memoryStatus.textureSize += this._size;
                }
              };

              _createClass(WebGLTexture, [{
                key: "gpuTexture",
                get: function get() {
                  return this._gpuTexture;
                }
              }]);

              return WebGLTexture;
            }(Texture);

            var eventWebGLContextLost = 'webglcontextlost';
            var WebGLDevice = exports('WebGLDevice', function (_Device) {
              _inheritsLoose(WebGLDevice, _Device);

              function WebGLDevice() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Device.call.apply(_Device, [this].concat(args)) || this;
                _this.stateCache = new WebGLStateCache();
                _this.cmdAllocator = new WebGLCommandAllocator();
                _this.nullTex2D = null;
                _this.nullTexCube = null;
                _this._webGLRC = null;
                _this._isAntialias = true;
                _this._isPremultipliedAlpha = true;
                _this._useVAO = false;
                _this._destroyShadersImmediately = true;
                _this._noCompressedTexSubImage2D = false;
                _this._bindingMappingInfo = new BindingMappingInfo();
                _this._webGLContextLostHandler = null;
                _this._extensions = null;
                _this._EXT_texture_filter_anisotropic = null;
                _this._EXT_blend_minmax = null;
                _this._EXT_frag_depth = null;
                _this._EXT_shader_texture_lod = null;
                _this._EXT_sRGB = null;
                _this._OES_vertex_array_object = null;
                _this._EXT_color_buffer_half_float = null;
                _this._WEBGL_color_buffer_float = null;
                _this._WEBGL_compressed_texture_etc1 = null;
                _this._WEBGL_compressed_texture_etc = null;
                _this._WEBGL_compressed_texture_pvrtc = null;
                _this._WEBGL_compressed_texture_astc = null;
                _this._WEBGL_compressed_texture_s3tc = null;
                _this._WEBGL_compressed_texture_s3tc_srgb = null;
                _this._WEBGL_debug_shaders = null;
                _this._WEBGL_draw_buffers = null;
                _this._WEBGL_lose_context = null;
                _this._WEBGL_depth_texture = null;
                _this._WEBGL_debug_renderer_info = null;
                _this._OES_texture_half_float = null;
                _this._OES_texture_half_float_linear = null;
                _this._OES_texture_float = null;
                _this._OES_texture_float_linear = null;
                _this._OES_standard_derivatives = null;
                _this._OES_element_index_uint = null;
                _this._ANGLE_instanced_arrays = null;
                return _this;
              }

              var _proto = WebGLDevice.prototype;

              _proto.initialize = function initialize(info) {
                this._canvas = info.canvasElm;
                this._isAntialias = info.isAntialias;
                this._isPremultipliedAlpha = info.isPremultipliedAlpha;
                this._bindingMappingInfo = info.bindingMappingInfo;
                if (!this._bindingMappingInfo.bufferOffsets.length) this._bindingMappingInfo.bufferOffsets.push(0);
                if (!this._bindingMappingInfo.samplerOffsets.length) this._bindingMappingInfo.samplerOffsets.push(0);

                try {
                  var webGLCtxAttribs = {
                    alpha: macro.ENABLE_TRANSPARENT_CANVAS,
                    antialias: this._isAntialias,
                    depth: true,
                    stencil: true,
                    premultipliedAlpha: this._isPremultipliedAlpha,
                    preserveDrawingBuffer: false,
                    powerPreference: 'default',
                    failIfMajorPerformanceCaveat: false
                  };
                  this._webGLRC = this._canvas.getContext('webgl', webGLCtxAttribs);
                } catch (err) {
                  console.error(err);
                  return false;
                }

                if (!this._webGLRC) {
                  console.error('This device does not support WebGL.');
                  return false;
                }

                this._webGLContextLostHandler = this._onWebGLContextLost.bind(this);

                this._canvas.addEventListener(eventWebGLContextLost, this._onWebGLContextLost);

                this._canvas2D = document.createElement('canvas');
                console.info('WebGL device initialized.');
                this._gfxAPI = API.WEBGL;
                this._deviceName = 'WebGL';
                var gl = this._webGLRC;
                this._WEBGL_debug_renderer_info = this.getExtension('WEBGL_debug_renderer_info');

                if (this._WEBGL_debug_renderer_info) {
                  this._renderer = gl.getParameter(this._WEBGL_debug_renderer_info.UNMASKED_RENDERER_WEBGL);
                  this._vendor = gl.getParameter(this._WEBGL_debug_renderer_info.UNMASKED_VENDOR_WEBGL);
                } else {
                  this._renderer = gl.getParameter(gl.RENDERER);
                  this._vendor = gl.getParameter(gl.VENDOR);
                }

                this._version = gl.getParameter(gl.VERSION);
                this._caps.maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
                this._caps.maxVertexUniformVectors = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS);
                this._caps.maxFragmentUniformVectors = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS);
                this._caps.maxTextureUnits = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
                this._caps.maxVertexTextureUnits = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
                this._caps.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
                this._caps.maxCubeMapTextureSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
                this._caps.depthBits = gl.getParameter(gl.DEPTH_BITS);
                this._caps.stencilBits = gl.getParameter(gl.STENCIL_BITS);
                this.stateCache.initialize(this._caps.maxTextureUnits, this._caps.maxVertexAttributes);

                this._devicePixelRatio = info.devicePixelRatio || 1.0;
                this._width = this._canvas.width;
                this._height = this._canvas.height;
                this._nativeWidth = Math.max(info.nativeWidth || this._width, 0);
                this._nativeHeight = Math.max(info.nativeHeight || this._height, 0);
                this._colorFmt = Format.RGBA8;

                if (this._caps.depthBits === 24) {
                  if (this._caps.stencilBits === 8) {
                    this._depthStencilFmt = Format.D24S8;
                  } else {
                    this._depthStencilFmt = Format.D24;
                  }
                } else if (this._caps.stencilBits === 8) {
                  this._depthStencilFmt = Format.D16S8;
                } else {
                  this._depthStencilFmt = Format.D16;
                }

                this._extensions = gl.getSupportedExtensions();
                var extensions = '';

                if (this._extensions) {
                  for (var _iterator = _createForOfIteratorHelperLoose(this._extensions), _step; !(_step = _iterator()).done;) {
                    var ext = _step.value;
                    extensions += ext + " ";
                  }

                  console.debug("EXTENSIONS: " + extensions);
                }

                this._EXT_texture_filter_anisotropic = this.getExtension('EXT_texture_filter_anisotropic');
                this._EXT_blend_minmax = this.getExtension('EXT_blend_minmax');
                this._EXT_frag_depth = this.getExtension('EXT_frag_depth');
                this._EXT_shader_texture_lod = this.getExtension('EXT_shader_texture_lod');
                this._EXT_sRGB = this.getExtension('EXT_sRGB');
                this._OES_vertex_array_object = this.getExtension('OES_vertex_array_object');
                this._EXT_color_buffer_half_float = this.getExtension('EXT_color_buffer_half_float');
                this._WEBGL_color_buffer_float = this.getExtension('WEBGL_color_buffer_float');
                this._WEBGL_compressed_texture_etc1 = this.getExtension('WEBGL_compressed_texture_etc1');
                this._WEBGL_compressed_texture_etc = this.getExtension('WEBGL_compressed_texture_etc');
                this._WEBGL_compressed_texture_pvrtc = this.getExtension('WEBGL_compressed_texture_pvrtc');
                this._WEBGL_compressed_texture_s3tc = this.getExtension('WEBGL_compressed_texture_s3tc');
                this._WEBGL_compressed_texture_s3tc_srgb = this.getExtension('WEBGL_compressed_texture_s3tc_srgb');
                this._WEBGL_debug_shaders = this.getExtension('WEBGL_debug_shaders');
                this._WEBGL_draw_buffers = this.getExtension('WEBGL_draw_buffers');
                this._WEBGL_lose_context = this.getExtension('WEBGL_lose_context');
                this._WEBGL_depth_texture = this.getExtension('WEBGL_depth_texture');
                this._OES_texture_half_float = this.getExtension('OES_texture_half_float');
                this._OES_texture_half_float_linear = this.getExtension('OES_texture_half_float_linear');
                this._OES_texture_float = this.getExtension('OES_texture_float');
                this._OES_texture_float_linear = this.getExtension('OES_texture_float_linear');
                this._OES_standard_derivatives = this.getExtension('OES_standard_derivatives');
                this._OES_element_index_uint = this.getExtension('OES_element_index_uint');
                this._ANGLE_instanced_arrays = this.getExtension('ANGLE_instanced_arrays');
                {
                  if (system.os !== OS.IOS || sys.osMainVersion !== 14 || !sys.isBrowser) {
                    this._WEBGL_compressed_texture_astc = this.getExtension('WEBGL_compressed_texture_astc');
                  }

                  if (system.browserType === BrowserType.UC) {
                    this._ANGLE_instanced_arrays = null;
                  }

                  if (system.os === OS.IOS && sys.osMainVersion <= 10 || WECHAT ) {
                    this._destroyShadersImmediately = false;
                  }
                }

                this._features.fill(false);

                if (this._EXT_blend_minmax) {
                  this._features[Feature.BLEND_MINMAX] = true;
                }

                if (this._WEBGL_color_buffer_float) {
                  this._features[Feature.COLOR_FLOAT] = true;
                }

                if (this._EXT_color_buffer_half_float) {
                  this._features[Feature.COLOR_HALF_FLOAT] = true;
                }

                if (this._OES_texture_float) {
                  this._features[Feature.TEXTURE_FLOAT] = true;
                }

                if (this._OES_texture_half_float) {
                  this._features[Feature.TEXTURE_HALF_FLOAT] = true;
                }

                if (this._OES_texture_float_linear) {
                  this._features[Feature.TEXTURE_FLOAT_LINEAR] = true;
                }

                if (this._OES_texture_half_float_linear) {
                  this._features[Feature.TEXTURE_HALF_FLOAT_LINEAR] = true;
                }

                this._features[Feature.FORMAT_RGB8] = true;

                if (this._WEBGL_depth_texture) {
                  this._features[Feature.FORMAT_D16] = true;
                  this._features[Feature.FORMAT_D24] = true;
                  this._features[Feature.FORMAT_D24S8] = true;
                }

                if (this._OES_element_index_uint) {
                  this._features[Feature.ELEMENT_INDEX_UINT] = true;
                }

                if (this._ANGLE_instanced_arrays) {
                  this._features[Feature.INSTANCED_ARRAYS] = true;
                }

                if (this._WEBGL_draw_buffers) {
                  this._features[Feature.MULTIPLE_RENDER_TARGETS] = true;
                }

                var compressedFormat = '';

                if (this._WEBGL_compressed_texture_etc1) {
                  this._features[Feature.FORMAT_ETC1] = true;
                  compressedFormat += 'etc1 ';
                }

                if (this._WEBGL_compressed_texture_etc) {
                  this._features[Feature.FORMAT_ETC2] = true;
                  compressedFormat += 'etc2 ';
                }

                if (this._WEBGL_compressed_texture_s3tc) {
                  this._features[Feature.FORMAT_DXT] = true;
                  compressedFormat += 'dxt ';
                }

                if (this._WEBGL_compressed_texture_pvrtc) {
                  this._features[Feature.FORMAT_PVRTC] = true;
                  compressedFormat += 'pvrtc ';
                }

                if (this._WEBGL_compressed_texture_astc) {
                  this._features[Feature.FORMAT_ASTC] = true;
                  compressedFormat += 'astc ';
                }

                if (this._OES_vertex_array_object) {
                  this._useVAO = true;
                }

                console.info("RENDERER: " + this._renderer);
                console.info("VENDOR: " + this._vendor);
                console.info("VERSION: " + this._version);
                console.info("DPR: " + this._devicePixelRatio);
                console.info("SCREEN_SIZE: " + this._width + " x " + this._height);
                console.info("NATIVE_SIZE: " + this._nativeWidth + " x " + this._nativeHeight);
                console.info("MAX_VERTEX_UNIFORM_VECTORS: " + this._caps.maxVertexUniformVectors);
                console.info("DEPTH_BITS: " + this._caps.depthBits);
                console.info("STENCIL_BITS: " + this._caps.stencilBits);

                if (this._EXT_texture_filter_anisotropic) {
                  console.info("MAX_TEXTURE_MAX_ANISOTROPY_EXT: " + this._EXT_texture_filter_anisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
                }

                console.info("USE_VAO: " + this._useVAO);
                console.info("COMPRESSED_FORMAT: " + compressedFormat);
                this.initStates(gl);
                this._queue = this.createQueue(new QueueInfo(QueueType.GRAPHICS));
                this._cmdBuff = this.createCommandBuffer(new CommandBufferInfo(this._queue));
                this.nullTex2D = this.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.SAMPLED, Format.RGBA8, 2, 2, TextureFlagBit.GEN_MIPMAP));
                this.nullTexCube = this.createTexture(new TextureInfo(TextureType.CUBE, TextureUsageBit.SAMPLED, Format.RGBA8, 2, 2, TextureFlagBit.GEN_MIPMAP, 6));
                var nullTexRegion = new BufferTextureCopy();
                nullTexRegion.texExtent.width = 2;
                nullTexRegion.texExtent.height = 2;
                var nullTexBuff = new Uint8Array(this.nullTex2D.size);
                nullTexBuff.fill(0);
                this.copyBuffersToTexture([nullTexBuff], this.nullTex2D, [nullTexRegion]);
                nullTexRegion.texSubres.layerCount = 6;
                this.copyBuffersToTexture([nullTexBuff, nullTexBuff, nullTexBuff, nullTexBuff, nullTexBuff, nullTexBuff], this.nullTexCube, [nullTexRegion]);
                return true;
              };

              _proto.destroy = function destroy() {
                if (this._canvas && this._webGLContextLostHandler) {
                  this._canvas.removeEventListener(eventWebGLContextLost, this._webGLContextLostHandler);

                  this._webGLContextLostHandler = null;
                }

                if (this.nullTex2D) {
                  this.nullTex2D.destroy();
                  this.nullTex2D = null;
                }

                if (this.nullTexCube) {
                  this.nullTexCube.destroy();
                  this.nullTexCube = null;
                }

                if (this._queue) {
                  this._queue.destroy();

                  this._queue = null;
                }

                if (this._cmdBuff) {
                  this._cmdBuff.destroy();

                  this._cmdBuff = null;
                }

                this._extensions = null;
                this._webGLRC = null;
              };

              _proto.resize = function resize(width, height) {
                if (this._width !== width || this._height !== height) {
                  console.info("Resizing device: " + width + "x" + height);
                  this._canvas.width = width;
                  this._canvas.height = height;
                  this._width = width;
                  this._height = height;
                }
              };

              _proto.flushCommands = function flushCommands(cmdBuffs) {};

              _proto.acquire = function acquire() {
                this.cmdAllocator.releaseCmds();
              };

              _proto.present = function present() {
                var queue = this._queue;
                this._numDrawCalls = queue.numDrawCalls;
                this._numInstances = queue.numInstances;
                this._numTris = queue.numTris;
                queue.clear();
              };

              _proto.createCommandBuffer = function createCommandBuffer(info) {
                var Ctor = info.type === CommandBufferType.PRIMARY ? WebGLPrimaryCommandBuffer : WebGLCommandBuffer;
                var cmdBuff = new Ctor(this);
                cmdBuff.initialize(info);
                return cmdBuff;
              };

              _proto.createBuffer = function createBuffer(info) {
                var buffer = new WebGLBuffer(this);

                if (buffer.initialize(info)) {
                  return buffer;
                }

                return null;
              };

              _proto.createTexture = function createTexture(info) {
                var texture = new WebGLTexture(this);

                if (texture.initialize(info)) {
                  return texture;
                }

                return null;
              };

              _proto.createSampler = function createSampler(info) {
                var sampler = new WebGLSampler(this);

                if (sampler.initialize(info)) {
                  return sampler;
                }

                return null;
              };

              _proto.createDescriptorSet = function createDescriptorSet(info) {
                var descriptorSet = new WebGLDescriptorSet(this);

                if (descriptorSet.initialize(info)) {
                  return descriptorSet;
                }

                return null;
              };

              _proto.createShader = function createShader(info) {
                var shader = new WebGLShader(this);

                if (shader.initialize(info)) {
                  return shader;
                }

                return null;
              };

              _proto.createInputAssembler = function createInputAssembler(info) {
                var inputAssembler = new WebGLInputAssembler(this);

                if (inputAssembler.initialize(info)) {
                  return inputAssembler;
                }

                return null;
              };

              _proto.createRenderPass = function createRenderPass(info) {
                var renderPass = new WebGLRenderPass(this);

                if (renderPass.initialize(info)) {
                  return renderPass;
                }

                return null;
              };

              _proto.createFramebuffer = function createFramebuffer(info) {
                var framebuffer = new WebGLFramebuffer(this);

                if (framebuffer.initialize(info)) {
                  return framebuffer;
                }

                return null;
              };

              _proto.createDescriptorSetLayout = function createDescriptorSetLayout(info) {
                var descriptorSetLayout = new WebGLDescriptorSetLayout(this);

                if (descriptorSetLayout.initialize(info)) {
                  return descriptorSetLayout;
                }

                return null;
              };

              _proto.createPipelineLayout = function createPipelineLayout(info) {
                var pipelineLayout = new WebGLPipelineLayout(this);

                if (pipelineLayout.initialize(info)) {
                  return pipelineLayout;
                }

                return null;
              };

              _proto.createPipelineState = function createPipelineState(info) {
                var pipelineState = new WebGLPipelineState(this);

                if (pipelineState.initialize(info)) {
                  return pipelineState;
                }

                return null;
              };

              _proto.createQueue = function createQueue(info) {
                var queue = new WebGLQueue(this);

                if (queue.initialize(info)) {
                  return queue;
                }

                return null;
              };

              _proto.createGlobalBarrier = function createGlobalBarrier(info) {
                var barrier = new GlobalBarrier(this);

                if (barrier.initialize(info)) {
                  return barrier;
                }

                return null;
              };

              _proto.createTextureBarrier = function createTextureBarrier(info) {
                var barrier = new TextureBarrier(this);

                if (barrier.initialize(info)) {
                  return barrier;
                }

                return null;
              };

              _proto.copyBuffersToTexture = function copyBuffersToTexture(buffers, texture, regions) {
                WebGLCmdFuncCopyBuffersToTexture(this, buffers, texture.gpuTexture, regions);
              };

              _proto.copyTexImagesToTexture = function copyTexImagesToTexture(texImages, texture, regions) {
                WebGLCmdFuncCopyTexImagesToTexture(this, texImages, texture.gpuTexture, regions);
              };

              _proto.copyFramebufferToBuffer = function copyFramebufferToBuffer(srcFramebuffer, dstBuffer, regions) {
                var gl = this._webGLRC;
                var gpuFramebuffer = srcFramebuffer.gpuFramebuffer;
                var format = gpuFramebuffer.gpuColorTextures[0].format;
                var glFormat = GFXFormatToWebGLFormat(format, gl);
                var glType = GFXFormatToWebGLType(format, gl);
                var Ctor = getTypedArrayConstructor(FormatInfos[format]);
                var curFBO = this.stateCache.glFramebuffer;

                if (this.stateCache.glFramebuffer !== gpuFramebuffer.glFramebuffer) {
                  gl.bindFramebuffer(gl.FRAMEBUFFER, gpuFramebuffer.glFramebuffer);
                  this.stateCache.glFramebuffer = gpuFramebuffer.glFramebuffer;
                }

                var view = new Ctor(dstBuffer);

                for (var _iterator2 = _createForOfIteratorHelperLoose(regions), _step2; !(_step2 = _iterator2()).done;) {
                  var region = _step2.value;
                  var w = region.texExtent.width;
                  var h = region.texExtent.height;
                  gl.readPixels(region.texOffset.x, region.texOffset.y, w, h, glFormat, glType, view);
                }

                if (this.stateCache.glFramebuffer !== curFBO) {
                  gl.bindFramebuffer(gl.FRAMEBUFFER, curFBO);
                  this.stateCache.glFramebuffer = curFBO;
                }
              };

              _proto.blitFramebuffer = function blitFramebuffer(src, dst, srcRect, dstRect, filter) {};

              _proto.getExtension = function getExtension(ext) {
                var prefixes = ['', 'WEBKIT_', 'MOZ_'];

                for (var i = 0; i < prefixes.length; ++i) {
                  var _ext = this.gl.getExtension(prefixes[i] + ext);

                  if (_ext) {
                    return _ext;
                  }
                }

                return null;
              };

              _proto.initStates = function initStates(gl) {
                gl.activeTexture(gl.TEXTURE0);
                gl.pixelStorei(gl.PACK_ALIGNMENT, 1);
                gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
                gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
                gl.bindFramebuffer(gl.FRAMEBUFFER, null);
                gl.enable(gl.SCISSOR_TEST);
                gl.enable(gl.CULL_FACE);
                gl.cullFace(gl.BACK);
                gl.frontFace(gl.CCW);
                gl.disable(gl.POLYGON_OFFSET_FILL);
                gl.polygonOffset(0.0, 0.0);
                gl.enable(gl.DEPTH_TEST);
                gl.depthMask(true);
                gl.depthFunc(gl.LESS);
                gl.depthRange(0.0, 1.0);
                gl.stencilFuncSeparate(gl.FRONT, gl.ALWAYS, 1, 0xffff);
                gl.stencilOpSeparate(gl.FRONT, gl.KEEP, gl.KEEP, gl.KEEP);
                gl.stencilMaskSeparate(gl.FRONT, 0xffff);
                gl.stencilFuncSeparate(gl.BACK, gl.ALWAYS, 1, 0xffff);
                gl.stencilOpSeparate(gl.BACK, gl.KEEP, gl.KEEP, gl.KEEP);
                gl.stencilMaskSeparate(gl.BACK, 0xffff);
                gl.disable(gl.STENCIL_TEST);
                gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
                gl.disable(gl.BLEND);
                gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD);
                gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO);
                gl.colorMask(true, true, true, true);
                gl.blendColor(0.0, 0.0, 0.0, 0.0);
              };

              _proto._onWebGLContextLost = function _onWebGLContextLost(event) {
                warnID(11000);
                warn(event);
              };

              _createClass(WebGLDevice, [{
                key: "gl",
                get: function get() {
                  return this._webGLRC;
                }
              }, {
                key: "webGLQueue",
                get: function get() {
                  return this._queue;
                }
              }, {
                key: "isAntialias",
                get: function get() {
                  return this._isAntialias;
                }
              }, {
                key: "isPremultipliedAlpha",
                get: function get() {
                  return this._isPremultipliedAlpha;
                }
              }, {
                key: "useVAO",
                get: function get() {
                  return this._useVAO;
                }
              }, {
                key: "destroyShadersImmediately",
                get: function get() {
                  return this._destroyShadersImmediately;
                }
              }, {
                key: "noCompressedTexSubImage2D",
                get: function get() {
                  return this._noCompressedTexSubImage2D;
                }
              }, {
                key: "bindingMappingInfo",
                get: function get() {
                  return this._bindingMappingInfo;
                }
              }, {
                key: "EXT_texture_filter_anisotropic",
                get: function get() {
                  return this._EXT_texture_filter_anisotropic;
                }
              }, {
                key: "EXT_blend_minmax",
                get: function get() {
                  return this._EXT_blend_minmax;
                }
              }, {
                key: "EXT_frag_depth",
                get: function get() {
                  return this._EXT_frag_depth;
                }
              }, {
                key: "EXT_shader_texture_lod",
                get: function get() {
                  return this._EXT_shader_texture_lod;
                }
              }, {
                key: "EXT_sRGB",
                get: function get() {
                  return this._EXT_sRGB;
                }
              }, {
                key: "OES_vertex_array_object",
                get: function get() {
                  return this._OES_vertex_array_object;
                }
              }, {
                key: "WEBGL_color_buffer_float",
                get: function get() {
                  return this._WEBGL_color_buffer_float;
                }
              }, {
                key: "WEBGL_compressed_texture_etc1",
                get: function get() {
                  return this._WEBGL_compressed_texture_etc1;
                }
              }, {
                key: "WEBGL_compressed_texture_pvrtc",
                get: function get() {
                  return this._WEBGL_compressed_texture_pvrtc;
                }
              }, {
                key: "WEBGL_compressed_texture_astc",
                get: function get() {
                  return this._WEBGL_compressed_texture_astc;
                }
              }, {
                key: "WEBGL_compressed_texture_s3tc",
                get: function get() {
                  return this._WEBGL_compressed_texture_s3tc;
                }
              }, {
                key: "WEBGL_compressed_texture_s3tc_srgb",
                get: function get() {
                  return this._WEBGL_compressed_texture_s3tc_srgb;
                }
              }, {
                key: "WEBGL_debug_shaders",
                get: function get() {
                  return this._WEBGL_debug_shaders;
                }
              }, {
                key: "WEBGL_draw_buffers",
                get: function get() {
                  return this._WEBGL_draw_buffers;
                }
              }, {
                key: "WEBGL_lose_context",
                get: function get() {
                  return this._WEBGL_lose_context;
                }
              }, {
                key: "WEBGL_depth_texture",
                get: function get() {
                  return this._WEBGL_depth_texture;
                }
              }, {
                key: "WEBGL_debug_renderer_info",
                get: function get() {
                  return this._WEBGL_debug_renderer_info;
                }
              }, {
                key: "OES_texture_half_float",
                get: function get() {
                  return this._OES_texture_half_float;
                }
              }, {
                key: "OES_texture_half_float_linear",
                get: function get() {
                  return this._OES_texture_half_float_linear;
                }
              }, {
                key: "OES_texture_float",
                get: function get() {
                  return this._OES_texture_float;
                }
              }, {
                key: "OES_standard_derivatives",
                get: function get() {
                  return this._OES_standard_derivatives;
                }
              }, {
                key: "OES_element_index_uint",
                get: function get() {
                  return this._OES_element_index_uint;
                }
              }, {
                key: "ANGLE_instanced_arrays",
                get: function get() {
                  return this._ANGLE_instanced_arrays;
                }
              }]);

              return WebGLDevice;
            }(Device));

            legacyCC.WebGLDevice = WebGLDevice;

            var vec3_temp = new Vec3();

            var _worldMatrix = new Mat4();

            function fillVertices3D(node, renderer, renderData, color) {
              var dataList = renderData.data;
              var buffer = renderer.acquireBufferBatch();
              var vertexOffset = buffer.byteOffset >> 2;
              var vertexCount = renderData.vertexCount;
              var indicesOffset = buffer.indicesOffset;
              var vertexId = buffer.vertexOffset;
              var isRecreate = buffer.request(vertexCount, renderData.indicesCount);

              if (!isRecreate) {
                buffer = renderer.currBufferBatch;
                vertexCount = 0;
                indicesOffset = 0;
                vertexId = 0;
              }

              var vBuf = buffer.vData;
              node.getWorldMatrix(_worldMatrix);

              for (var i = 0; i < vertexCount; i++) {
                var vert = dataList[i];
                Vec3.set(vec3_temp, vert.x, vert.y, 0);
                Vec3.transformMat4(vec3_temp, vec3_temp, _worldMatrix);
                vBuf[vertexOffset++] = vec3_temp.x;
                vBuf[vertexOffset++] = vec3_temp.y;
                vBuf[vertexOffset++] = vec3_temp.z;
                vBuf[vertexOffset++] = vert.u;
                vBuf[vertexOffset++] = vert.v;
                Color.toArray(vBuf, color, vertexOffset);
                vertexOffset += 4;
              }

              var iBuf = buffer.iData;

              for (var _i = 0; _i < renderData.dataLength; _i++) {
                iBuf[indicesOffset + _i] = vertexId + _i;
              }
            }
            function fillMeshVertices3D(node, renderer, renderData, color) {
              var dataList = renderData.data;
              var buffer = renderer.acquireBufferBatch();
              var vertexOffset = buffer.byteOffset >> 2;
              var vertexCount = renderData.vertexCount;
              var indicesOffset = buffer.indicesOffset;
              var vertexId = buffer.vertexOffset;
              var isRecreate = buffer.request(vertexCount, renderData.indicesCount);

              if (!isRecreate) {
                buffer = renderer.currBufferBatch;
                vertexCount = 0;
                indicesOffset = 0;
                vertexId = 0;
              }

              var vBuf = buffer.vData;
              var iBuf = buffer.iData;
              node.getWorldMatrix(_worldMatrix);

              for (var i = 0; i < vertexCount; i++) {
                var vert = dataList[i];
                Vec3.set(vec3_temp, vert.x, vert.y, 0);
                Vec3.transformMat4(vec3_temp, vec3_temp, _worldMatrix);
                vBuf[vertexOffset++] = vec3_temp.x;
                vBuf[vertexOffset++] = vec3_temp.y;
                vBuf[vertexOffset++] = vec3_temp.z;
                vBuf[vertexOffset++] = vert.u;
                vBuf[vertexOffset++] = vert.v;
                Color.toArray(vBuf, color, vertexOffset);
                vertexOffset += 4;
              }

              for (var _i2 = 0, count = vertexCount / 4; _i2 < count; _i2++) {
                var start = vertexId + _i2 * 4;
                iBuf[indicesOffset++] = start;
                iBuf[indicesOffset++] = start + 1;
                iBuf[indicesOffset++] = start + 2;
                iBuf[indicesOffset++] = start + 1;
                iBuf[indicesOffset++] = start + 3;
                iBuf[indicesOffset++] = start + 2;
              }
            }
            function fillVerticesWithoutCalc3D(node, renderer, renderData, color) {
              var dataList = renderData.data;
              var buffer = renderer.acquireBufferBatch();
              var vertexOffset = buffer.byteOffset >> 2;
              var vertexCount = renderData.vertexCount;
              var indicesOffset = buffer.indicesOffset;
              var vertexId = buffer.vertexOffset;
              var isRecreate = buffer.request(vertexCount, renderData.indicesCount);

              if (!isRecreate) {
                buffer = renderer.currBufferBatch;
                vertexCount = 0;
                indicesOffset = 0;
                vertexId = 0;
              }

              var vBuf = buffer.vData;

              for (var i = 0; i < vertexCount; i++) {
                var vert = dataList[i];
                vBuf[vertexOffset++] = vert.x;
                vBuf[vertexOffset++] = vert.y;
                vBuf[vertexOffset++] = vert.z;
                vBuf[vertexOffset++] = vert.u;
                vBuf[vertexOffset++] = vert.v;
                Color.toArray(vBuf, color, vertexOffset);
                vertexOffset += 4;
              }

              var iBuf = buffer.iData;
              iBuf[indicesOffset++] = vertexId;
              iBuf[indicesOffset++] = vertexId + 1;
              iBuf[indicesOffset++] = vertexId + 2;
              iBuf[indicesOffset++] = vertexId + 1;
              iBuf[indicesOffset++] = vertexId + 3;
              iBuf[indicesOffset++] = vertexId + 2;
            }

            var space = 2;
            var Atlas = function () {
              function Atlas(width, height) {
                this._texture = void 0;
                this._width = void 0;
                this._height = void 0;
                this._x = void 0;
                this._y = void 0;
                this._nexty = void 0;
                this._innerTextureInfos = {};
                this._innerSpriteFrames = void 0;
                this._count = void 0;
                var texture = new DynamicAtlasTexture();
                texture.initWithSize(width, height);
                this._texture = texture;
                this._width = width;
                this._height = height;
                this._x = space;
                this._y = space;
                this._nexty = space;
                this._innerTextureInfos = {};
                this._innerSpriteFrames = [];
                this._count = 0;
              }

              var _proto = Atlas.prototype;

              _proto.insertSpriteFrame = function insertSpriteFrame(spriteFrame) {
                var rect = spriteFrame.rect;
                var texture = spriteFrame.texture;

                var info = this._innerTextureInfos[texture.getId()];

                var sx = rect.x;
                var sy = rect.y;

                if (info) {
                  sx += info.x;
                  sy += info.y;
                } else {
                  var width = texture.width;
                  var height = texture.height;

                  if (this._x + width + space > this._width) {
                    this._x = space;
                    this._y = this._nexty;
                  }

                  if (this._y + height + space > this._nexty) {
                    this._nexty = this._y + height + space;
                  }

                  if (this._nexty > this._height) {
                    return null;
                  }

                  if (legacyCC.internal.dynamicAtlasManager.textureBleeding) {
                    if (width <= 8 || height <= 8) {
                      this._texture.drawTextureAt(texture.image, this._x - 1, this._y - 1);

                      this._texture.drawTextureAt(texture.image, this._x - 1, this._y + 1);

                      this._texture.drawTextureAt(texture.image, this._x + 1, this._y - 1);

                      this._texture.drawTextureAt(texture.image, this._x + 1, this._y + 1);
                    }

                    this._texture.drawTextureAt(texture.image, this._x - 1, this._y);

                    this._texture.drawTextureAt(texture.image, this._x + 1, this._y);

                    this._texture.drawTextureAt(texture.image, this._x, this._y - 1);

                    this._texture.drawTextureAt(texture.image, this._x, this._y + 1);
                  }

                  this._texture.drawTextureAt(texture.image, this._x, this._y);

                  this._innerTextureInfos[texture.getId()] = {
                    x: this._x,
                    y: this._y,
                    texture: texture
                  };
                  this._count++;
                  sx += this._x;
                  sy += this._y;
                  this._x += width + space;
                }

                var frame = {
                  x: sx,
                  y: sy,
                  texture: this._texture
                };

                this._innerSpriteFrames.push(spriteFrame);

                return frame;
              };

              _proto.deleteInnerTexture = function deleteInnerTexture(texture) {
                if (texture && this._innerTextureInfos[texture.getId()]) {
                  delete this._innerTextureInfos[texture.getId()];
                  this._count--;
                }
              };

              _proto.isEmpty = function isEmpty() {
                return this._count <= 0;
              };

              _proto.reset = function reset() {
                this._x = space;
                this._y = space;
                this._nexty = space;
                var frames = this._innerSpriteFrames;

                for (var i = 0, l = frames.length; i < l; i++) {
                  var frame = frames[i];

                  if (!frame.isValid) {
                    continue;
                  }

                  frame._resetDynamicAtlasFrame();
                }

                this._innerSpriteFrames.length = 0;
                this._innerTextureInfos = {};
              };

              _proto.destroy = function destroy() {
                this.reset();

                this._texture.destroy();
              };

              return Atlas;
            }();
            var DynamicAtlasTexture = function (_Texture2D) {
              _inheritsLoose(DynamicAtlasTexture, _Texture2D);

              function DynamicAtlasTexture() {
                return _Texture2D.apply(this, arguments) || this;
              }

              var _proto2 = DynamicAtlasTexture.prototype;

              _proto2.initWithSize = function initWithSize(width, height, format) {
                if (format === void 0) {
                  format = PixelFormat.RGBA8888;
                }

                this.reset({
                  width: width,
                  height: height,
                  format: format
                });
                this.loaded = true;
                this.emit('load');
              };

              _proto2.drawTextureAt = function drawTextureAt(image, x, y) {
                var gfxTexture = this.getGFXTexture();

                if (!image || !gfxTexture) {
                  return;
                }

                var gfxDevice = this._getGFXDevice();

                if (!gfxDevice) {
                  console.warn('Unable to get device');
                  return;
                }

                var region = new BufferTextureCopy();
                region.texOffset.x = x;
                region.texOffset.y = y;
                region.texExtent.width = image.width;
                region.texExtent.height = image.height;
                gfxDevice.copyTexImagesToTexture([image.data], gfxTexture, [region]);
              };

              return DynamicAtlasTexture;
            }(Texture2D);

            var DynamicAtlasManager = function () {
              function DynamicAtlasManager() {
                this._atlases = [];
                this._atlasIndex = -1;
                this._maxAtlasCount = 5;
                this._textureSize = 2048;
                this._maxFrameSize = 512;
                this._textureBleeding = true;
                this._enabled = false;
              }

              var _proto = DynamicAtlasManager.prototype;

              _proto.newAtlas = function newAtlas() {
                var atlas = this._atlases[++this._atlasIndex];

                if (!atlas) {
                  atlas = new Atlas(this._textureSize, this._textureSize);

                  this._atlases.push(atlas);
                }

                return atlas;
              };

              _proto.beforeSceneLoad = function beforeSceneLoad() {
                this.reset();
              };

              _proto.insertSpriteFrame = function insertSpriteFrame(spriteFrame) {
                if (!this._enabled || this._atlasIndex === this._maxAtlasCount || !spriteFrame || spriteFrame._original) return null;
                if (!spriteFrame.packable) return null;
                var atlas = this._atlases[this._atlasIndex];

                if (!atlas) {
                  atlas = this.newAtlas();
                }

                var frame = atlas.insertSpriteFrame(spriteFrame);

                if (!frame && this._atlasIndex !== this._maxAtlasCount) {
                  atlas = this.newAtlas();
                  return atlas.insertSpriteFrame(spriteFrame);
                }

                return frame;
              };

              _proto.reset = function reset() {
                for (var i = 0, l = this._atlases.length; i < l; i++) {
                  this._atlases[i].destroy();
                }

                this._atlases.length = 0;
                this._atlasIndex = -1;
              };

              _proto.deleteAtlasSpriteFrame = function deleteAtlasSpriteFrame(spriteFrame) {
                if (!spriteFrame._original) return;
                var texture = spriteFrame._original._texture;
                this.deleteAtlasTexture(texture);
              };

              _proto.deleteAtlasTexture = function deleteAtlasTexture(texture) {
                if (texture) {
                  for (var i = this._atlases.length - 1; i >= 0; i--) {
                    this._atlases[i].deleteInnerTexture(texture);

                    if (this._atlases[i].isEmpty()) {
                      this._atlases[i].destroy();

                      this._atlases.splice(i, 1);

                      this._atlasIndex--;
                    }
                  }
                }
              };

              _proto.packToDynamicAtlas = function packToDynamicAtlas(comp, frame) {

                if (!frame._original && frame.packable) {
                  var packedFrame = this.insertSpriteFrame(frame);

                  if (packedFrame) {
                    frame._setDynamicAtlasFrame(packedFrame);
                  }
                }
              };

              _createClass(DynamicAtlasManager, [{
                key: "enabled",
                get: function get() {
                  return this._enabled;
                },
                set: function set(value) {
                  if (this._enabled === value) return;

                  if (value) {
                    this.reset();
                    legacyCC.director.on(legacyCC.Director.EVENT_BEFORE_SCENE_LAUNCH, this.beforeSceneLoad, this);
                  } else {
                    this.reset();
                    legacyCC.director.off(legacyCC.Director.EVENT_BEFORE_SCENE_LAUNCH, this.beforeSceneLoad, this);
                  }

                  this._enabled = value;
                }
              }, {
                key: "maxAtlasCount",
                get: function get() {
                  return this._maxAtlasCount;
                },
                set: function set(value) {
                  this._maxAtlasCount = value;
                }
              }, {
                key: "atlasCount",
                get: function get() {
                  return this._atlases.length;
                }
              }, {
                key: "textureBleeding",
                get: function get() {
                  return this._textureBleeding;
                },
                set: function set(enable) {
                  this._textureBleeding = enable;
                }
              }, {
                key: "textureSize",
                get: function get() {
                  return this._textureSize;
                },
                set: function set(value) {
                  this._textureSize = value;
                }
              }, {
                key: "maxFrameSize",
                get: function get() {
                  return this._maxFrameSize;
                },
                set: function set(value) {
                  this._maxFrameSize = value;
                }
              }]);

              return DynamicAtlasManager;
            }();
            DynamicAtlasManager.instance = void 0;
            var dynamicAtlasManager = exports('dynamicAtlasManager', DynamicAtlasManager.instance = new DynamicAtlasManager());
            legacyCC.internal.dynamicAtlasManager = dynamicAtlasManager;

            var _dec$N, _class$O, _temp$M;
            var INSET_LEFT = 0;
            var INSET_TOP = 1;
            var INSET_RIGHT = 2;
            var INSET_BOTTOM = 3;
            var temp_uvs = [{
              u: 0,
              v: 0
            }, {
              u: 0,
              v: 0
            }, {
              u: 0,
              v: 0
            }, {
              u: 0,
              v: 0
            }];
            var SpriteFrame = exports('SpriteFrame', (_dec$N = ccclass('cc.SpriteFrame'), _dec$N(_class$O = (_temp$M = function (_Asset) {
              _inheritsLoose(SpriteFrame, _Asset);

              SpriteFrame.createWithImage = function createWithImage(imageSourceOrImageAsset) {
                var img = imageSourceOrImageAsset instanceof ImageAsset ? imageSourceOrImageAsset : new ImageAsset(imageSourceOrImageAsset);
                var tex = new Texture2D();
                tex.image = img;
                var spf = new SpriteFrame();
                spf.texture = tex;
                return spf;
              };

              function SpriteFrame() {
                var _this;

                _this = _Asset.call(this) || this;
                _this.vertices = null;
                _this.uv = [];
                _this.uvHash = 0;
                _this.unbiasUV = [];
                _this.uvSliced = [];
                _this._rect = new Rect();
                _this._offset = new Vec2();
                _this._originalSize = new 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;

                return _this;
              }

              var _proto = SpriteFrame.prototype;

              _proto.textureLoaded = function textureLoaded() {
                return this.texture && this.texture.loaded;
              };

              _proto.isRotated = function isRotated() {
                return this._rotated;
              };

              _proto.setRotated = function setRotated(rotated) {
                this.rotated = rotated;
              };

              _proto.getRect = function getRect(out) {
                if (out) {
                  out.set(this._rect);
                  return out;
                }

                return this._rect.clone();
              };

              _proto.setRect = function setRect(rect) {
                this.rect = rect;
              };

              _proto.getOriginalSize = function getOriginalSize(out) {
                if (out) {
                  out.set(this._originalSize);
                  return out;
                }

                return this._originalSize.clone();
              };

              _proto.setOriginalSize = function setOriginalSize(size) {
                this.originalSize = size;
              };

              _proto.getOffset = function getOffset(out) {
                if (out) {
                  out.set(this._offset);
                  return out;
                }

                return this._offset.clone();
              };

              _proto.setOffset = function setOffset(offset) {
                this.offset = offset;
              };

              _proto.getGFXTexture = function getGFXTexture() {
                return this._texture.getGFXTexture();
              };

              _proto.getGFXSampler = function getGFXSampler() {
                return this._texture.getGFXSampler();
              };

              _proto.getHash = function getHash() {
                return this._texture.getHash();
              };

              _proto.getSamplerHash = function getSamplerHash() {
                return this._texture.getSamplerHash();
              };

              _proto.reset = function reset(info, clearData) {
                if (clearData === void 0) {
                  clearData = false;
                }

                var calUV = false;

                if (clearData) {
                  this._originalSize.set(0, 0);

                  this._rect.set(0, 0, 0, 0);

                  this._offset.set(0, 0);

                  this._capInsets = [0, 0, 0, 0];
                  this._rotated = false;
                  calUV = true;
                }

                if (info) {
                  if (info.texture) {
                    this.loaded = false;
                    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();
                }
              };

              _proto.checkRect = function checkRect(texture) {
                var rect = this._rect;
                var maxX = rect.x;
                var maxY = rect.y;

                if (this._rotated) {
                  maxX += rect.height;
                  maxY += rect.width;
                } else {
                  maxX += rect.width;
                  maxY += rect.height;
                }

                if (maxX > texture.width) {
                  errorID(3300, this.name + "/" + texture.name, maxX, texture.width);
                  return false;
                }

                if (maxY > texture.height) {
                  errorID(3301, this.name + "/" + texture.name, maxY, texture.height);
                  return false;
                }

                return true;
              };

              _proto.onLoaded = function onLoaded() {
                this.loaded = true;
                this.emit('load');
              };

              _proto.destroy = function destroy() {
                if (this._packable && dynamicAtlasManager) {
                  dynamicAtlasManager.deleteAtlasSpriteFrame(this);
                }

                return _Asset.prototype.destroy.call(this);
              };

              _proto._calculateSlicedUV = function _calculateSlicedUV() {
                var rect = this._rect;
                var tex = this.texture;
                var atlasWidth = tex.width;
                var atlasHeight = tex.height;
                var leftWidth = this._capInsets[INSET_LEFT];
                var rightWidth = this._capInsets[INSET_RIGHT];
                var centerWidth = rect.width - leftWidth - rightWidth;
                var topHeight = this._capInsets[INSET_TOP];
                var bottomHeight = this._capInsets[INSET_BOTTOM];
                var centerHeight = rect.height - topHeight - bottomHeight;
                var uvSliced = this.uvSliced;
                uvSliced.length = 0;

                if (this._rotated) {
                  temp_uvs[0].u = rect.x / atlasWidth;
                  temp_uvs[1].u = (rect.x + bottomHeight) / atlasWidth;
                  temp_uvs[2].u = (rect.x + bottomHeight + centerHeight) / atlasWidth;
                  temp_uvs[3].u = (rect.x + rect.height) / atlasWidth;
                  temp_uvs[3].v = rect.y / atlasHeight;
                  temp_uvs[2].v = (rect.y + leftWidth) / atlasHeight;
                  temp_uvs[1].v = (rect.y + leftWidth + centerWidth) / atlasHeight;
                  temp_uvs[0].v = (rect.y + rect.width) / atlasHeight;

                  for (var row = 0; row < 4; ++row) {
                    var rowD = temp_uvs[row];

                    for (var col = 0; col < 4; ++col) {
                      var colD = temp_uvs[3 - col];
                      uvSliced.push({
                        u: rowD.u,
                        v: colD.v
                      });
                    }
                  }
                } else {
                  temp_uvs[0].u = rect.x / atlasWidth;
                  temp_uvs[1].u = (rect.x + leftWidth) / atlasWidth;
                  temp_uvs[2].u = (rect.x + leftWidth + centerWidth) / atlasWidth;
                  temp_uvs[3].u = (rect.x + rect.width) / atlasWidth;
                  temp_uvs[3].v = rect.y / atlasHeight;
                  temp_uvs[2].v = (rect.y + topHeight) / atlasHeight;
                  temp_uvs[1].v = (rect.y + topHeight + centerHeight) / atlasHeight;
                  temp_uvs[0].v = (rect.y + rect.height) / atlasHeight;

                  for (var _row = 0; _row < 4; ++_row) {
                    var _rowD = temp_uvs[_row];

                    for (var _col = 0; _col < 4; ++_col) {
                      var _colD = temp_uvs[_col];
                      uvSliced.push({
                        u: _colD.u,
                        v: _rowD.v
                      });
                    }
                  }
                }
              };

              _proto._calculateUV = function _calculateUV() {
                var rect = this._rect;
                var uv = this.uv;
                var unbiasUV = this.unbiasUV;
                var tex = this.texture;
                var texw = tex.width;
                var texh = tex.height;

                if (this._rotated) {
                  var l = texw === 0 ? 0 : rect.x / texw;
                  var r = texw === 0 ? 1 : (rect.x + rect.height) / texw;
                  var t = texh === 0 ? 0 : rect.y / texh;
                  var b = texh === 0 ? 1 : (rect.y + rect.width) / texh;

                  if (this._isFlipUVX && this._isFlipUVY) {
                    uv[0] = r;
                    uv[1] = b;
                    uv[2] = r;
                    uv[3] = t;
                    uv[4] = l;
                    uv[5] = b;
                    uv[6] = l;
                    uv[7] = t;
                  } else if (this._isFlipUVX) {
                    uv[0] = r;
                    uv[1] = t;
                    uv[2] = r;
                    uv[3] = b;
                    uv[4] = l;
                    uv[5] = t;
                    uv[6] = l;
                    uv[7] = b;
                  } else if (this._isFlipUVY) {
                    uv[0] = l;
                    uv[1] = b;
                    uv[2] = l;
                    uv[3] = t;
                    uv[4] = r;
                    uv[5] = b;
                    uv[6] = r;
                    uv[7] = t;
                  } else {
                    uv[0] = l;
                    uv[1] = t;
                    uv[2] = l;
                    uv[3] = b;
                    uv[4] = r;
                    uv[5] = t;
                    uv[6] = r;
                    uv[7] = b;
                  }

                  var ul = texw === 0 ? 0 : rect.x / texw;
                  var ur = texw === 0 ? 1 : (rect.x + rect.height) / texw;
                  var ut = texh === 0 ? 0 : rect.y / texh;
                  var ub = texh === 0 ? 1 : (rect.y + rect.width) / texh;

                  if (this._isFlipUVX && this._isFlipUVY) {
                    unbiasUV[0] = ur;
                    unbiasUV[1] = ub;
                    unbiasUV[2] = ur;
                    unbiasUV[3] = ut;
                    unbiasUV[4] = ul;
                    unbiasUV[5] = ub;
                    unbiasUV[6] = ul;
                    unbiasUV[7] = ut;
                  } else if (this._isFlipUVX) {
                    unbiasUV[0] = ur;
                    unbiasUV[1] = ut;
                    unbiasUV[2] = ur;
                    unbiasUV[3] = ub;
                    unbiasUV[4] = ul;
                    unbiasUV[5] = ut;
                    unbiasUV[6] = ul;
                    unbiasUV[7] = ub;
                  } else if (this._isFlipUVY) {
                    unbiasUV[0] = ul;
                    unbiasUV[1] = ub;
                    unbiasUV[2] = ul;
                    unbiasUV[3] = ut;
                    unbiasUV[4] = ur;
                    unbiasUV[5] = ub;
                    unbiasUV[6] = ur;
                    unbiasUV[7] = ut;
                  } else {
                    unbiasUV[0] = ul;
                    unbiasUV[1] = ut;
                    unbiasUV[2] = ul;
                    unbiasUV[3] = ub;
                    unbiasUV[4] = ur;
                    unbiasUV[5] = ut;
                    unbiasUV[6] = ur;
                    unbiasUV[7] = ub;
                  }
                } else {
                  var _l = texw === 0 ? 0 : rect.x / texw;

                  var _r = texw === 0 ? 1 : (rect.x + rect.width) / texw;

                  var _b = texh === 0 ? 1 : (rect.y + rect.height) / texh;

                  var _t = texh === 0 ? 0 : rect.y / texh;

                  if (this._isFlipUVX && this._isFlipUVY) {
                    uv[0] = _r;
                    uv[1] = _t;
                    uv[2] = _l;
                    uv[3] = _t;
                    uv[4] = _r;
                    uv[5] = _b;
                    uv[6] = _l;
                    uv[7] = _b;
                  } else if (this._isFlipUVX) {
                    uv[0] = _r;
                    uv[1] = _b;
                    uv[2] = _l;
                    uv[3] = _b;
                    uv[4] = _r;
                    uv[5] = _t;
                    uv[6] = _l;
                    uv[7] = _t;
                  } else if (this._isFlipUVY) {
                    uv[0] = _l;
                    uv[1] = _t;
                    uv[2] = _r;
                    uv[3] = _t;
                    uv[4] = _l;
                    uv[5] = _b;
                    uv[6] = _r;
                    uv[7] = _b;
                  } else {
                    uv[0] = _l;
                    uv[1] = _b;
                    uv[2] = _r;
                    uv[3] = _b;
                    uv[4] = _l;
                    uv[5] = _t;
                    uv[6] = _r;
                    uv[7] = _t;
                  }

                  var _ul = texw === 0 ? 0 : rect.x / texw;

                  var _ur = texw === 0 ? 1 : (rect.x + rect.width) / texw;

                  var _ub = texh === 0 ? 1 : (rect.y + rect.height) / texh;

                  var _ut = texh === 0 ? 0 : rect.y / texh;

                  if (this._isFlipUVX && this._isFlipUVY) {
                    unbiasUV[0] = _ur;
                    unbiasUV[1] = _ut;
                    unbiasUV[2] = _ul;
                    unbiasUV[3] = _ut;
                    unbiasUV[4] = _ur;
                    unbiasUV[5] = _ub;
                    unbiasUV[6] = _ul;
                    unbiasUV[7] = _ub;
                  } else if (this._isFlipUVX) {
                    unbiasUV[0] = _ur;
                    unbiasUV[1] = _ub;
                    unbiasUV[2] = _ul;
                    unbiasUV[3] = _ub;
                    unbiasUV[4] = _ur;
                    unbiasUV[5] = _ut;
                    unbiasUV[6] = _ul;
                    unbiasUV[7] = _ut;
                  } else if (this._isFlipUVY) {
                    unbiasUV[0] = _ul;
                    unbiasUV[1] = _ut;
                    unbiasUV[2] = _ur;
                    unbiasUV[3] = _ut;
                    unbiasUV[4] = _ul;
                    unbiasUV[5] = _ub;
                    unbiasUV[6] = _ur;
                    unbiasUV[7] = _ub;
                  } else {
                    unbiasUV[0] = _ul;
                    unbiasUV[1] = _ub;
                    unbiasUV[2] = _ur;
                    unbiasUV[3] = _ub;
                    unbiasUV[4] = _ul;
                    unbiasUV[5] = _ut;
                    unbiasUV[6] = _ur;
                    unbiasUV[7] = _ut;
                  }
                }

                var uvHashStr = '';

                for (var i = 0; i < uv.length; i++) {
                  uvHashStr += uv[i];
                }

                this.uvHash = murmurhash2_32_gc(uvHashStr, 666);
                var vertices = this.vertices;

                if (vertices) {
                  vertices.nu.length = 0;
                  vertices.nv.length = 0;

                  for (var _i = 0; _i < vertices.u.length; _i++) {
                    vertices.nu[_i] = vertices.u[_i] / texw;
                    vertices.nv[_i] = vertices.v[_i] / texh;
                  }
                }

                this._calculateSlicedUV();
              };

              _proto._setDynamicAtlasFrame = function _setDynamicAtlasFrame(frame) {
                if (!frame) return;
                this._original = {
                  _texture: this._texture,
                  _x: this._rect.x,
                  _y: this._rect.y
                };
                this._texture = frame.texture;
                this._rect.x = frame.x;
                this._rect.y = frame.y;

                this._calculateUV();
              };

              _proto._resetDynamicAtlasFrame = function _resetDynamicAtlasFrame() {
                if (!this._original) return;
                this._rect.x = this._original._x;
                this._rect.y = this._original._y;
                this._texture = this._original._texture;
                this._original = null;

                this._calculateUV();
              };

              _proto._checkPackable = function _checkPackable() {
                var dynamicAtlas = dynamicAtlasManager;
                if (!dynamicAtlas) return;
                var texture = this._texture;

                if (!(texture instanceof Texture2D) || texture.isCompressed) {
                  this._packable = false;
                  return;
                }

                var w = this.width;
                var h = this.height;

                if (!texture.image || w > dynamicAtlas.maxFrameSize || h > dynamicAtlas.maxFrameSize) {
                  this._packable = false;
                  return;
                }

                if (texture.image && texture.image instanceof HTMLCanvasElement) {
                  this._packable = true;
                }
              };

              _proto._serialize = function _serialize(ctxForExporting) {

                return null;
              };

              _proto._deserialize = function _deserialize(serializeData, handle) {
                var data = serializeData;
                var rect = data.rect;

                if (rect) {
                  this._rect = new Rect(rect.x, rect.y, rect.width, rect.height);
                }

                var offset = data.offset;

                if (data.offset) {
                  this._offset = new Vec2(offset.x, offset.y);
                }

                var originalSize = data.originalSize;

                if (data.originalSize) {
                  this._originalSize = new Size(originalSize.width, originalSize.height);
                }

                this._rotated = !!data.rotated;
                this._name = data.name;
                this._packable = !!data.packable;
                var capInsets = data.capInsets;

                if (capInsets) {
                  this._capInsets[INSET_LEFT] = capInsets[INSET_LEFT];
                  this._capInsets[INSET_TOP] = capInsets[INSET_TOP];
                  this._capInsets[INSET_RIGHT] = capInsets[INSET_RIGHT];
                  this._capInsets[INSET_BOTTOM] = capInsets[INSET_BOTTOM];
                }

                this.vertices = data.vertices;

                if (this.vertices) {
                  this.vertices.nu = [];
                  this.vertices.nv = [];
                }
              };

              _proto.clone = function clone() {
                var _v$nu, _v$u, _v$nv, _v$v, _sp$uv, _sp$unbiasUV, _sp$uvSliced, _sp$_capInsets;

                var sp = new SpriteFrame();
                var v = this.vertices;
                sp.vertices = v ? {
                  x: v.x,
                  y: v.y,
                  triangles: v.triangles,
                  nu: (_v$nu = v.nu) === null || _v$nu === void 0 ? void 0 : _v$nu.slice(0),
                  u: (_v$u = v.u) === null || _v$u === void 0 ? void 0 : _v$u.slice(0),
                  nv: (_v$nv = v.nv) === null || _v$nv === void 0 ? void 0 : _v$nv.slice(0),
                  v: (_v$v = v.v) === null || _v$v === void 0 ? void 0 : _v$v.slice(0)
                } : null;

                (_sp$uv = sp.uv).splice.apply(_sp$uv, [0, sp.uv.length].concat(this.uv));

                sp.uvHash = this.uvHash;

                (_sp$unbiasUV = sp.unbiasUV).splice.apply(_sp$unbiasUV, [0, sp.unbiasUV.length].concat(this.unbiasUV));

                (_sp$uvSliced = sp.uvSliced).splice.apply(_sp$uvSliced, [0, sp.uvSliced.length].concat(this.uvSliced));

                sp._rect.set(this._rect);

                sp._offset.set(this._offset);

                sp._originalSize.set(this._originalSize);

                sp._rotated = this._rotated;

                (_sp$_capInsets = sp._capInsets).splice.apply(_sp$_capInsets, [0, sp._capInsets.length].concat(this._capInsets));

                sp._atlasUuid = this._atlasUuid;
                sp._texture = this._texture;
                sp._isFlipUVX = this._isFlipUVX;
                sp._isFlipUVY = this._isFlipUVY;
                return sp;
              };

              _proto._textureLoaded = function _textureLoaded() {
                var tex = this._texture;
                var config = {};
                var isReset = false;

                if (this._rect.width === 0 || this._rect.height === 0 || !this.checkRect(tex)) {
                  config.rect = new Rect(0, 0, tex.width, tex.height);
                  isReset = true;
                }

                if (this._originalSize.width === 0 || this._originalSize.height === 0 || isReset) {
                  config.originalSize = new Size(tex.width, tex.height);
                  isReset = true;
                }

                if (isReset) {
                  this.reset(config);
                  this.onLoaded();
                }

                this._checkPackable();
              };

              _proto._refreshTexture = function _refreshTexture(texture) {
                this._texture = texture;

                if (texture.loaded) {
                  this._textureLoaded();
                } else {
                  texture.once('load', this._textureLoaded, this);
                }
              };

              _proto.initDefault = function initDefault(uuid) {
                _Asset.prototype.initDefault.call(this, uuid);

                var texture = new Texture2D();
                texture.initDefault();

                this._refreshTexture(texture);

                this._calculateUV();
              };

              _proto.validate = function validate() {
                return this._texture && this._rect && this._rect.width !== 0 && this._rect.height !== 0;
              };

              _createClass(SpriteFrame, [{
                key: "insetTop",
                get: function get() {
                  return this._capInsets[INSET_TOP];
                },
                set: function set(value) {
                  if (this._capInsets[INSET_TOP] === value) {
                    return;
                  }

                  this._capInsets[INSET_TOP] = value;

                  if (this._texture) {
                    this._calculateSlicedUV();
                  }
                }
              }, {
                key: "insetBottom",
                get: function get() {
                  return this._capInsets[INSET_BOTTOM];
                },
                set: function set(value) {
                  if (this._capInsets[INSET_BOTTOM] === value) {
                    return;
                  }

                  this._capInsets[INSET_BOTTOM] = value;

                  if (this._texture) {
                    this._calculateSlicedUV();
                  }
                }
              }, {
                key: "insetLeft",
                get: function get() {
                  return this._capInsets[INSET_LEFT];
                },
                set: function set(value) {
                  if (this._capInsets[INSET_LEFT] === value) {
                    return;
                  }

                  this._capInsets[INSET_LEFT] = value;

                  if (this._texture) {
                    this._calculateSlicedUV();
                  }
                }
              }, {
                key: "insetRight",
                get: function get() {
                  return this._capInsets[INSET_RIGHT];
                },
                set: function set(value) {
                  if (this._capInsets[INSET_RIGHT] === value) {
                    return;
                  }

                  this._capInsets[INSET_RIGHT] = value;

                  if (this._texture) {
                    this._calculateSlicedUV();
                  }
                }
              }, {
                key: "rect",
                get: function get() {
                  return this._rect;
                },
                set: function set(value) {
                  if (this._rect.equals(value)) {
                    return;
                  }

                  this._rect.set(value);

                  if (this._texture) {
                    this._calculateUV();
                  }
                }
              }, {
                key: "originalSize",
                get: function get() {
                  return this._originalSize;
                },
                set: function set(value) {
                  if (this._originalSize.equals(value)) {
                    return;
                  }

                  this._originalSize.set(value);

                  if (this._texture) {
                    this._calculateUV();
                  }
                }
              }, {
                key: "offset",
                get: function get() {
                  return this._offset;
                },
                set: function set(value) {
                  this._offset.set(value);
                }
              }, {
                key: "rotated",
                get: function get() {
                  return this._rotated;
                },
                set: function set(rotated) {
                  if (this._rotated === rotated) {
                    return;
                  }

                  this._rotated = rotated;

                  if (this._texture) {
                    this._calculateUV();
                  }
                }
              }, {
                key: "texture",
                get: function get() {
                  return this._texture;
                },
                set: function set(value) {
                  if (!value) {
                    console.warn("Error Texture in " + this.name);
                    return;
                  }

                  this.reset({
                    texture: value
                  }, true);
                }
              }, {
                key: "atlasUuid",
                get: function get() {
                  return this._atlasUuid;
                },
                set: function set(value) {
                  this._atlasUuid = value;
                }
              }, {
                key: "width",
                get: function get() {
                  return this._texture.width;
                }
              }, {
                key: "height",
                get: function get() {
                  return this._texture.height;
                }
              }, {
                key: "_textureSource",
                set: function set(value) {
                  if (window.Build) {
                    this._texture = value;
                    return;
                  }

                  if (value) {
                    this._refreshTexture(value);

                    this._calculateUV();
                  }
                }
              }, {
                key: "flipUVX",
                get: function get() {
                  return this._isFlipUVX;
                },
                set: function set(value) {
                  this._isFlipUVX = value;

                  this._calculateUV();
                }
              }, {
                key: "flipUVY",
                get: function get() {
                  return this._isFlipUVY;
                },
                set: function set(value) {
                  this._isFlipUVY = value;

                  this._calculateUV();
                }
              }, {
                key: "packable",
                get: function get() {
                  return this._packable;
                },
                set: function set(value) {
                  this._packable = value;
                }
              }, {
                key: "original",
                get: function get() {
                  return this._original;
                }
              }]);

              return SpriteFrame;
            }(Asset), _temp$M)) || _class$O));
            legacyCC.SpriteFrame = SpriteFrame;

            var _dec$O, _class$P, _class2$M, _descriptor$C, _temp$N;
            var SpriteAtlas = exports('SpriteAtlas', (_dec$O = ccclass('cc.SpriteAtlas'), _dec$O(_class$P = (_class2$M = (_temp$N = function (_Asset) {
              _inheritsLoose(SpriteAtlas, _Asset);

              function SpriteAtlas() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "spriteFrames", _descriptor$C, _assertThisInitialized(_this));

                return _this;
              }

              var _proto = SpriteAtlas.prototype;

              _proto.getTexture = function getTexture() {
                var keys = Object.keys(this.spriteFrames);

                if (keys.length > 0) {
                  var spriteFrame = this.spriteFrames[keys[0]];
                  return spriteFrame && spriteFrame.texture;
                } else {
                  return null;
                }
              };

              _proto.getSpriteFrame = function getSpriteFrame(key) {
                var sf = this.spriteFrames[key];

                if (!sf) {
                  return null;
                }

                if (!sf.name) {
                  sf.name = key;
                }

                return sf;
              };

              _proto.getSpriteFrames = function getSpriteFrames() {
                var frames = [];
                var spriteFrames = this.spriteFrames;

                for (var _i = 0, _Object$keys = Object.keys(spriteFrames); _i < _Object$keys.length; _i++) {
                  var _key2 = _Object$keys[_i];
                  frames.push(spriteFrames[_key2]);
                }

                return frames;
              };

              _proto._serialize = function _serialize(ctxForExporting) {
              };

              _proto._deserialize = function _deserialize(serializeData, handle) {
                var data = serializeData;
                this._name = data.name;
                var frames = data.spriteFrames;
                this.spriteFrames = createMap();

                for (var i = 0; i < frames.length; i += 2) {
                  handle.result.push(this.spriteFrames, frames[i], frames[i + 1], _getClassId(SpriteFrame));
                }
              };

              return SpriteAtlas;
            }(Asset), _temp$N), (_descriptor$C = _applyDecoratedDescriptor(_class2$M.prototype, "spriteFrames", [serializable, editable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return createMap();
              }
            })), _class2$M)) || _class$P));
            legacyCC.SpriteAtlas = SpriteAtlas;

            var _dec$P, _class$Q;
            var Font = exports('Font', (_dec$P = ccclass('cc.Font'), _dec$P(_class$Q = function (_Asset) {
              _inheritsLoose(Font, _Asset);

              function Font() {
                return _Asset.apply(this, arguments) || this;
              }

              return Font;
            }(Asset)) || _class$Q));
            legacyCC.Font = Font;

            var _dec$Q, _class$R, _class2$N, _descriptor$D, _temp$O;
            var TTFFont = exports('TTFFont', (_dec$Q = ccclass('cc.TTFFont'), _dec$Q(_class$R = (_class2$N = (_temp$O = function (_Font) {
              _inheritsLoose(TTFFont, _Font);

              function TTFFont() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Font.call.apply(_Font, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "_fontFamily", _descriptor$D, _assertThisInitialized(_this));

                return _this;
              }

              var _proto = TTFFont.prototype;

              _proto.initDefault = function initDefault(uuid) {
                this._fontFamily = 'Arial';

                _Font.prototype.initDefault.call(this, uuid);
              };

              _createClass(TTFFont, [{
                key: "_nativeAsset",
                get: function get() {
                  return this._fontFamily;
                },
                set: function set(value) {
                  this._fontFamily = value || 'Arial';
                }
              }, {
                key: "_nativeDep",
                get: function get() {
                  return {
                    uuid: this._uuid,
                    __nativeName__: this._native,
                    ext: extname(this._native),
                    __isNative__: true
                  };
                }
              }]);

              return TTFFont;
            }(Font), _temp$O), (_descriptor$D = _applyDecoratedDescriptor(_class2$N.prototype, "_fontFamily", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _applyDecoratedDescriptor(_class2$N.prototype, "_nativeAsset", [override, string], Object.getOwnPropertyDescriptor(_class2$N.prototype, "_nativeAsset"), _class2$N.prototype), _applyDecoratedDescriptor(_class2$N.prototype, "_nativeDep", [override], Object.getOwnPropertyDescriptor(_class2$N.prototype, "_nativeDep"), _class2$N.prototype)), _class2$N)) || _class$R));
            legacyCC.TTFFont = TTFFont;

            var _dec$R, _dec2$s, _class$S, _class2$O, _descriptor$E, _descriptor2$q, _descriptor3$h, _descriptor4$e, _temp$P;
            var FontLetterDefinition = function FontLetterDefinition() {
              this.u = 0;
              this.v = 0;
              this.w = 0;
              this.h = 0;
              this.offsetX = 0;
              this.offsetY = 0;
              this.textureID = 0;
              this.valid = false;
              this.xAdvance = 0;
            };
            var FontAtlas = function () {
              function FontAtlas(texture) {
                this.letterDefinitions = {};
                this.texture = texture;
              }

              var _proto = FontAtlas.prototype;

              _proto.addLetterDefinitions = function addLetterDefinitions(letter, letterDefinition) {
                this.letterDefinitions[letter] = letterDefinition;
              };

              _proto.cloneLetterDefinition = function cloneLetterDefinition() {
                var copyLetterDefinitions = {};

                for (var _i = 0, _Object$keys = Object.keys(this.letterDefinitions); _i < _Object$keys.length; _i++) {
                  var _key = _Object$keys[_i];
                  var value = new FontLetterDefinition();
                  mixin(value, this.letterDefinitions[_key]);
                  copyLetterDefinitions[_key] = value;
                }

                return copyLetterDefinitions;
              };

              _proto.getTexture = function getTexture() {
                return this.texture;
              };

              _proto.getLetter = function getLetter(key) {
                return this.letterDefinitions[key];
              };

              _proto.getLetterDefinitionForChar = function getLetterDefinitionForChar(_char, labelInfo) {
                var key = _char.charCodeAt(0);

                var hasKey = this.letterDefinitions.hasOwnProperty(key);
                var letter;

                if (hasKey) {
                  letter = this.letterDefinitions[key];
                } else {
                  letter = null;
                }

                return letter;
              };

              _proto.clear = function clear() {
                this.letterDefinitions = {};
              };

              return FontAtlas;
            }();
            var BitmapFont = exports('BitmapFont', (_dec$R = ccclass('cc.BitmapFont'), _dec2$s = type(SpriteFrame), _dec$R(_class$S = (_class2$O = (_temp$P = function (_Font) {
              _inheritsLoose(BitmapFont, _Font);

              function BitmapFont() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key2 = 0; _key2 < _len; _key2++) {
                  args[_key2] = arguments[_key2];
                }

                _this = _Font.call.apply(_Font, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "fntDataStr", _descriptor$E, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "spriteFrame", _descriptor2$q, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "fontSize", _descriptor3$h, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "fntConfig", _descriptor4$e, _assertThisInitialized(_this));

                return _this;
              }

              var _proto2 = BitmapFont.prototype;

              _proto2.onLoaded = function onLoaded() {
                var spriteFrame = this.spriteFrame;

                if (!this.fontDefDictionary && spriteFrame) {
                  this.fontDefDictionary = new FontAtlas(spriteFrame.texture);
                }

                var fntConfig = this.fntConfig;

                if (!fntConfig) {
                  warn('The fnt config is not exists!');
                  return;
                }

                var fontDict = fntConfig.fontDefDictionary;

                for (var fontDef in fontDict) {
                  var letter = new FontLetterDefinition();
                  var rect = fontDict[fontDef].rect;
                  letter.offsetX = fontDict[fontDef].xOffset;
                  letter.offsetY = fontDict[fontDef].yOffset;
                  letter.w = rect.width;
                  letter.h = rect.height;
                  letter.u = rect.x;
                  letter.v = rect.y;
                  letter.textureID = 0;
                  letter.valid = true;
                  letter.xAdvance = fontDict[fontDef].xAdvance;
                  this.fontDefDictionary.addLetterDefinitions(fontDef, letter);
                }
              };

              return BitmapFont;
            }(Font), _temp$P), (_descriptor$E = _applyDecoratedDescriptor(_class2$O.prototype, "fntDataStr", [serializable, editable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return '';
              }
            }), _descriptor2$q = _applyDecoratedDescriptor(_class2$O.prototype, "spriteFrame", [_dec2$s], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor3$h = _applyDecoratedDescriptor(_class2$O.prototype, "fontSize", [serializable, editable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return -1;
              }
            }), _descriptor4$e = _applyDecoratedDescriptor(_class2$O.prototype, "fntConfig", [serializable, editable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            })), _class2$O)) || _class$S));
            legacyCC.BitmapFont = BitmapFont;

            var _dec$S, _class$T;
            var LabelAtlas = exports('LabelAtlas', (_dec$S = ccclass('cc.LabelAtlas'), _dec$S(_class$T = function (_BitmapFont) {
              _inheritsLoose(LabelAtlas, _BitmapFont);

              function LabelAtlas() {
                return _BitmapFont.apply(this, arguments) || this;
              }

              return LabelAtlas;
            }(BitmapFont)) || _class$T));
            legacyCC.LabelAtlas = LabelAtlas;

            var BASELINE_RATIO = exports('BASELINE_RATIO', 0.26);
            var _BASELINE_OFFSET = 0;

            var MIDDLE_RATIO = exports('MIDDLE_RATIO', (BASELINE_RATIO + 1) / 2 - BASELINE_RATIO);
            function getBaselineOffset() {
              return _BASELINE_OFFSET;
            }
            var MAX_CACHE_SIZE = 100;
            var pool$1 = new Pool(2);

            pool$1.get = function () {
              return this._get() || {
                key: '',
                value: 0,
                prev: null,
                next: null
              };
            };

            var LRUCache = function () {
              function LRUCache(size) {
                this.count = 0;
                this.limit = 0;
                this.datas = {};
                this.limit = size;
              }

              var _proto = LRUCache.prototype;

              _proto.moveToHead = function moveToHead(node) {
                node.next = this.head;
                node.prev = null;
                if (this.head) this.head.prev = node;
                this.head = node;
                if (!this.tail) this.tail = node;
                this.count++;
                this.datas[node.key] = node;
              };

              _proto.put = function put(key, value) {
                var node = pool$1.get();
                node.key = key;
                node.value = value;

                if (this.count >= this.limit) {
                  var discard = this.tail;
                  delete this.datas[discard.key];
                  this.count--;
                  this.tail = discard.prev;
                  this.tail.next = null;
                  discard.prev = null;
                  discard.next = null;
                  pool$1.put(discard);
                }

                this.moveToHead(node);
              };

              _proto.remove = function remove(node) {
                if (node.prev) {
                  node.prev.next = node.next;
                } else {
                  this.head = node.next;
                }

                if (node.next) {
                  node.next.prev = node.prev;
                } else {
                  this.tail = node.prev;
                }

                delete this.datas[node.key];
                this.count--;
              };

              _proto.get = function get(key) {
                var node = this.datas[key];

                if (node) {
                  this.remove(node);
                  this.moveToHead(node);
                  return node.value;
                }

                return null;
              };

              _proto.clear = function clear() {
                this.count = 0;
                this.datas = {};
                this.head = null;
                this.tail = null;
              };

              _proto.has = function has(key) {
                return !!this.datas[key];
              };

              _proto["delete"] = function _delete(key) {
                var node = this.datas[key];
                this.remove(node);
              };

              return LRUCache;
            }();

            var measureCache = new LRUCache(MAX_CACHE_SIZE);
            var WORD_REG = /([a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûа-яА-ЯЁё]+|\S)/;
            var SYMBOL_REG = /^[!,.:;'}\]%\?>、‘“》？。，！]/;
            var LAST_WORD_REG = /([a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûаíìÍÌïÁÀáàÉÈÒÓòóŐőÙÚŰúűñÑæÆœŒÃÂãÔõěščřžýáíéóúůťďňĚŠČŘŽÁÍÉÓÚŤżźśóńłęćąŻŹŚÓŃŁĘĆĄ-яА-ЯЁё]+|\S)$/;
            var LAST_ENGLISH_REG = /[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûаíìÍÌïÁÀáàÉÈÒÓòóŐőÙÚŰúűñÑæÆœŒÃÂãÔõěščřžýáíéóúůťďňĚŠČŘŽÁÍÉÓÚŤżźśóńłęćąŻŹŚÓŃŁĘĆĄ-яА-ЯЁё]+$/;
            var FIRST_ENGLISH_REG = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûаíìÍÌïÁÀáàÉÈÒÓòóŐőÙÚŰúűñÑæÆœŒÃÂãÔõěščřžýáíéóúůťďňĚŠČŘŽÁÍÉÓÚŤżźśóńłęćąŻŹŚÓŃŁĘĆĄ-яА-ЯЁё]/;
            function isUnicodeCJK(ch) {
              var __CHINESE_REG = /^[\u4E00-\u9FFF\u3400-\u4DFF]+$/;
              var __JAPANESE_REG = /[\u3000-\u303F]|[\u3040-\u309F]|[\u30A0-\u30FF]|[\uFF00-\uFFEF]|[\u4E00-\u9FAF]|[\u2605-\u2606]|[\u2190-\u2195]|\u203B/g;
              var __KOREAN_REG = /^[\u1100-\u11FF]|[\u3130-\u318F]|[\uA960-\uA97F]|[\uAC00-\uD7AF]|[\uD7B0-\uD7FF]+$/;
              return __CHINESE_REG.test(ch) || __JAPANESE_REG.test(ch) || __KOREAN_REG.test(ch);
            }
            function isUnicodeSpace(ch) {
              var chCode = ch.charCodeAt(0);
              return chCode >= 9 && chCode <= 13 || chCode === 32 || chCode === 133 || chCode === 160 || chCode === 5760 || chCode >= 8192 && chCode <= 8202 || chCode === 8232 || chCode === 8233 || chCode === 8239 || chCode === 8287 || chCode === 12288;
            }
            function safeMeasureText(ctx, string, desc) {
              var font = desc || ctx.font;
              var key = font + "\uD83C\uDFAE" + string;
              var cache = measureCache.get(key);

              if (cache !== null) {
                return cache;
              }

              var metric = ctx.measureText(string);
              var width = metric && metric.width || 0;
              measureCache.put(key, width);
              return width;
            }

            function _safeSubstring(targetString, startIndex, endIndex) {
              var newStartIndex = startIndex;
              var newEndIndex = endIndex;
              var startChar = targetString[startIndex];

              if (startChar >= "\uDC00" && startChar <= "\uDFFF") {
                newStartIndex--;
              }

              if (endIndex !== undefined) {
                if (endIndex - 1 !== startIndex) {
                  var endChar = targetString[endIndex - 1];

                  if (endChar >= "\uD800" && endChar <= "\uDBFF") {
                    newEndIndex--;
                  }
                } else if (startChar >= "\uD800" && startChar <= "\uDBFF") {
                  newEndIndex++;
                }
              }

              return targetString.substring(newStartIndex, newEndIndex);
            }

            function fragmentText(stringToken, allWidth, maxWidth, measureText) {
              var wrappedWords = [];

              if (stringToken.length === 0 || maxWidth < 0) {
                wrappedWords.push('');
                return wrappedWords;
              }

              var text = stringToken;

              while (allWidth > maxWidth && text.length > 1) {
                var fuzzyLen = text.length * (maxWidth / allWidth) | 0;

                var tmpText = _safeSubstring(text, fuzzyLen);

                var width = allWidth - measureText(tmpText);
                var sLine = tmpText;
                var pushNum = 0;
                var checkWhile = 0;
                var checkCount = 10;

                while (width > maxWidth && checkWhile++ < checkCount) {
                  fuzzyLen *= maxWidth / width;
                  fuzzyLen |= 0;
                  tmpText = _safeSubstring(text, fuzzyLen);
                  width = allWidth - measureText(tmpText);
                }

                checkWhile = 0;

                while (width <= maxWidth && checkWhile++ < checkCount) {
                  if (tmpText) {
                    var exec = WORD_REG.exec(tmpText);
                    pushNum = exec ? exec[0].length : 1;
                    sLine = tmpText;
                  }

                  fuzzyLen += pushNum;
                  tmpText = _safeSubstring(text, fuzzyLen);
                  width = allWidth - measureText(tmpText);
                }

                fuzzyLen -= pushNum;

                if (fuzzyLen === 0) {
                  fuzzyLen = 1;
                  sLine = _safeSubstring(text, 1);
                } else if (fuzzyLen === 1 && text[0] >= "\uD800" && text[0] <= "\uDBFF") {
                  fuzzyLen = 2;
                  sLine = _safeSubstring(text, 2);
                }

                var sText = _safeSubstring(text, 0, fuzzyLen);

                var result = void 0;

                {
                  if (SYMBOL_REG.test(sLine || tmpText)) {
                    result = LAST_WORD_REG.exec(sText);
                    fuzzyLen -= result ? result[0].length : 0;

                    if (fuzzyLen === 0) {
                      fuzzyLen = 1;
                    }

                    sLine = _safeSubstring(text, fuzzyLen);
                    sText = _safeSubstring(text, 0, fuzzyLen);
                  }
                }

                if (FIRST_ENGLISH_REG.test(sLine)) {
                  result = LAST_ENGLISH_REG.exec(sText);

                  if (result && sText !== result[0]) {
                    fuzzyLen -= result[0].length;
                    sLine = _safeSubstring(text, fuzzyLen);
                    sText = _safeSubstring(text, 0, fuzzyLen);
                  }
                }

                if (wrappedWords.length === 0) {
                  wrappedWords.push(sText);
                } else {
                  sText = sText.trim();

                  if (sText.length > 0) {
                    wrappedWords.push(sText);
                  }
                }

                text = sLine || tmpText;
                allWidth = measureText(text);
              }

              if (wrappedWords.length === 0) {
                wrappedWords.push(text);
              } else {
                text = text.trim();

                if (text.length > 0) {
                  wrappedWords.push(text);
                }
              }

              return wrappedWords;
            }

            var _canvasPool;

            var CanvasPool = exports('CanvasPool', function () {
              function CanvasPool() {
                this.pool = [];
              }

              CanvasPool.getInstance = function getInstance() {
                if (!_canvasPool) {
                  _canvasPool = new CanvasPool();
                }

                return _canvasPool;
              };

              var _proto = CanvasPool.prototype;

              _proto.get = function get() {
                var data = this.pool.pop();

                if (!data) {
                  var canvas = document.createElement('canvas');
                  var context = canvas.getContext('2d');
                  data = {
                    canvas: canvas,
                    context: context
                  };
                }

                return data;
              };

              _proto.put = function put(canvas) {
                if (this.pool.length >= macro.MAX_LABEL_CANVAS_POOL_SIZE) {
                  return;
                }

                this.pool.push(canvas);
              };

              return CanvasPool;
            }());
            var WHITE = Color.WHITE.clone();
            var space$1 = 0;
            var bleed = 2;

            var FontLetterDefinition$1 = function FontLetterDefinition() {
              this.u = 0;
              this.v = 0;
              this.w = 0;
              this.h = 0;
              this.texture = null;
              this.offsetX = 0;
              this.offsetY = 0;
              this.valid = false;
              this.xAdvance = 0;
            };

            var _backgroundStyle = "rgba(255, 255, 255, " + (1 / 255).toFixed(3) + ")";

            var BASELINE_OFFSET = getBaselineOffset();

            var LetterTexture = function () {
              function LetterTexture(_char, labelInfo) {
                this.image = null;
                this.labelInfo = void 0;
                this["char"] = void 0;
                this.data = null;
                this.canvas = null;
                this.context = null;
                this.width = 0;
                this.height = 0;
                this.offsetY = 0;
                this.hash = void 0;
                this["char"] = _char;
                this.labelInfo = labelInfo;
                this.hash = _char.charCodeAt(0) + labelInfo.hash;
              }

              var _proto2 = LetterTexture.prototype;

              _proto2.updateRenderData = function updateRenderData() {
                this._updateProperties();

                this._updateTexture();
              };

              _proto2.destroy = function destroy() {
                this.image = null;
              };

              _proto2._updateProperties = function _updateProperties() {
                this.data = CanvasPool.getInstance().get();
                this.canvas = this.data.canvas;
                this.context = this.data.context;

                if (this.context) {
                  this.context.font = this.labelInfo.fontDesc;
                  var width = safeMeasureText(this.context, this["char"], this.labelInfo.fontDesc);
                  var blank = this.labelInfo.margin * 2 + bleed;
                  this.width = parseFloat(width.toFixed(2)) + blank;
                  this.height = (1 + BASELINE_RATIO) * this.labelInfo.fontSize + blank;
                  this.offsetY = -(this.labelInfo.fontSize * BASELINE_RATIO) / 2;
                }

                if (this.canvas.width !== this.width) {
                  this.canvas.width = this.width;
                }

                if (this.canvas.height !== this.height) {
                  this.canvas.height = this.height;
                }

                if (!this.image) {
                  this.image = new ImageAsset();
                }

                this.image.reset(this.canvas);
              };

              _proto2._updateTexture = function _updateTexture() {
                if (!this.context || !this.canvas) {
                  return;
                }

                var context = this.context;
                var labelInfo = this.labelInfo;
                var width = this.canvas.width;
                var height = this.canvas.height;
                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;
                var fontSize = labelInfo.fontSize;
                var startX = width / 2;
                var startY = height / 2 + fontSize * MIDDLE_RATIO + fontSize * BASELINE_OFFSET;
                var color = labelInfo.color;
                context.lineJoin = 'round';
                context.fillStyle = "rgba(" + color.r + ", " + color.g + ", " + color.b + ", " + 1 + ")";

                if (labelInfo.isOutlined) {
                  var strokeColor = labelInfo.out || WHITE;
                  context.strokeStyle = "rgba(" + strokeColor.r + ", " + strokeColor.g + ", " + strokeColor.b + ", " + strokeColor.a / 255 + ")";
                  context.lineWidth = labelInfo.margin * 2;
                  context.strokeText(this["char"], startX, startY);
                }

                context.fillText(this["char"], startX, startY);
              };

              return LetterTexture;
            }();

            var LetterRenderTexture = function (_Texture2D) {
              _inheritsLoose(LetterRenderTexture, _Texture2D);

              function LetterRenderTexture() {
                return _Texture2D.apply(this, arguments) || this;
              }

              var _proto3 = LetterRenderTexture.prototype;

              _proto3.initWithSize = function initWithSize(width, height, format) {
                if (format === void 0) {
                  format = PixelFormat.RGBA8888;
                }

                this.reset({
                  width: width,
                  height: height,
                  format: format
                });
                this.loaded = true;
                this.emit('load');
              };

              _proto3.drawTextureAt = function drawTextureAt(image, x, y) {
                var gfxTexture = this.getGFXTexture();

                if (!image || !gfxTexture) {
                  return;
                }

                var gfxDevice = this._getGFXDevice();

                if (!gfxDevice) {
                  console.warn('Unable to get device');
                  return;
                }

                var region = new BufferTextureCopy();
                region.texOffset.x = x;
                region.texOffset.y = y;
                region.texExtent.width = image.width;
                region.texExtent.height = image.height;
                gfxDevice.copyTexImagesToTexture([image.data], gfxTexture, [region]);
              };

              return LetterRenderTexture;
            }(Texture2D);
            var LetterAtlas = function () {
              function LetterAtlas(width, height) {
                this._x = space$1;
                this._y = space$1;
                this._nextY = space$1;
                this._width = 0;
                this._height = 0;
                this._halfBleed = 0;
                this._dirty = false;
                var texture = new LetterRenderTexture();
                texture.initWithSize(width, height);
                this.fontDefDictionary = new FontAtlas(texture);
                this._halfBleed = bleed / 2;
                this._width = width;
                this._height = height;
                director.on(Director.EVENT_BEFORE_SCENE_LAUNCH, this.beforeSceneLoad, this);
              }

              var _proto4 = LetterAtlas.prototype;

              _proto4.insertLetterTexture = function insertLetterTexture(letterTexture) {
                var texture = letterTexture.image;
                var device = director.root.device;

                if (!texture || !this.fontDefDictionary || !device) {
                  return null;
                }

                var width = texture.width;
                var height = texture.height;

                if (this._x + width + space$1 > this._width) {
                  this._x = space$1;
                  this._y = this._nextY;
                }

                if (this._y + height > this._nextY) {
                  this._nextY = this._y + height + space$1;
                }

                if (this._nextY > this._height) {
                  warnID(12100);
                  return null;
                }

                this.fontDefDictionary.texture.drawTextureAt(texture, this._x, this._y);
                this._dirty = true;
                var letterDefinition = new FontLetterDefinition$1();
                letterDefinition.u = this._x + this._halfBleed;
                letterDefinition.v = this._y + this._halfBleed;
                letterDefinition.texture = this.fontDefDictionary.texture;
                letterDefinition.valid = true;
                letterDefinition.w = letterTexture.width - bleed;
                letterDefinition.h = letterTexture.height - bleed;
                letterDefinition.xAdvance = letterDefinition.w;
                letterDefinition.offsetY = letterTexture.offsetY;
                this._x += width + space$1;
                this.fontDefDictionary.addLetterDefinitions(letterTexture.hash, letterDefinition);
                return letterDefinition;
              };

              _proto4.update = function update() {
                if (!this._dirty) {
                  return;
                }

                this._dirty = false;
              };

              _proto4.reset = function reset() {
                this._x = space$1;
                this._y = space$1;
                this._nextY = space$1;
                this.fontDefDictionary.clear();
              };

              _proto4.destroy = function destroy() {
                this.reset();

                if (this.fontDefDictionary) {
                  this.fontDefDictionary.texture.destroy();
                  this.fontDefDictionary.texture = null;
                }
              };

              _proto4.getTexture = function getTexture() {
                return this.fontDefDictionary.getTexture();
              };

              _proto4.beforeSceneLoad = function beforeSceneLoad() {
                this.clearAllCache();
              };

              _proto4.clearAllCache = function clearAllCache() {
                this.destroy();
                var texture = new LetterRenderTexture();
                texture.initWithSize(this._width, this._height);
                this.fontDefDictionary.texture = texture;
              };

              _proto4.getLetter = function getLetter(key) {
                return this.fontDefDictionary.letterDefinitions[key];
              };

              _proto4.getLetterDefinitionForChar = function getLetterDefinitionForChar(_char2, labelInfo) {
                var hash = _char2.charCodeAt(0) + labelInfo.hash;
                var letter = this.fontDefDictionary.letterDefinitions[hash];

                if (!letter) {
                  var temp = new LetterTexture(_char2, labelInfo);
                  temp.updateRenderData();
                  letter = this.insertLetterTexture(temp);
                  temp.destroy();
                }

                return letter;
              };

              _createClass(LetterAtlas, [{
                key: "width",
                get: function get() {
                  return this._width;
                }
              }, {
                key: "height",
                get: function get() {
                  return this._height;
                }
              }]);

              return LetterAtlas;
            }();
            var shareLabelInfo = {
              fontAtlas: null,
              fontSize: 0,
              lineHeight: 0,
              hAlign: 0,
              vAlign: 0,
              hash: '',
              fontFamily: '',
              fontDesc: 'Arial',
              color: Color.WHITE.clone(),
              isOutlined: false,
              out: Color.WHITE.clone(),
              margin: 0
            };
            function computeHash(labelInfo) {
              var hashData = '';
              var color = labelInfo.color.toHEX();
              var out = '';

              if (labelInfo.isOutlined && labelInfo.margin > 0) {
                out = out + labelInfo.margin + labelInfo.out.toHEX();
              }

              return hashData + labelInfo.fontSize + labelInfo.fontFamily + color + out;
            }

            var BaseRenderData = function BaseRenderData() {
              this.material = null;
              this.vertexCount = 0;
              this.indicesCount = 0;
            };
            var RenderData = function (_BaseRenderData) {
              _inheritsLoose(RenderData, _BaseRenderData);

              function RenderData() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _BaseRenderData.call.apply(_BaseRenderData, [this].concat(args)) || this;
                _this.vData = null;
                _this.uvDirty = true;
                _this.vertDirty = true;
                _this._data = [];
                _this._indices = [];
                _this._pivotX = 0;
                _this._pivotY = 0;
                _this._width = 0;
                _this._height = 0;
                return _this;
              }

              RenderData.add = function add() {
                return _pool.add();
              };

              RenderData.remove = function remove(data) {
                var idx = _pool.data.indexOf(data);

                if (idx === -1) {
                  return;
                }

                _pool.data[idx].clear();

                _pool.removeAt(idx);
              };

              var _proto = RenderData.prototype;

              _proto.updateSizeNPivot = function updateSizeNPivot(width, height, pivotX, pivotY) {
                if (width !== this._width || height !== this._height || pivotX !== this._pivotX || pivotY !== this._pivotY) {
                  this._width = width;
                  this._height = height;
                  this._pivotX = pivotX;
                  this._pivotY = pivotY;
                  this.vertDirty = true;
                }
              };

              _proto.clear = function clear() {
                this._data.length = 0;
                this._indices.length = 0;
                this._pivotX = 0;
                this._pivotY = 0;
                this._width = 0;
                this._height = 0;
                this.uvDirty = true;
                this.vertDirty = true;
                this.material = null;
                this.vertexCount = 0;
                this.indicesCount = 0;
              };

              _createClass(RenderData, [{
                key: "dataLength",
                get: function get() {
                  return this._data.length;
                },
                set: function set(length) {
                  var data = this._data;

                  if (data.length !== length) {
                    var value = data.length;
                    var i = 0;

                    for (i = length; i < value; i++) {
                      _dataPool.free(data[i]);
                    }

                    for (i = value; i < length; i++) {
                      data[i] = _dataPool.alloc();
                    }

                    data.length = length;
                  }
                }
              }, {
                key: "data",
                get: function get() {
                  return this._data;
                }
              }]);

              return RenderData;
            }(BaseRenderData);
            var MeshRenderData = function (_BaseRenderData2) {
              _inheritsLoose(MeshRenderData, _BaseRenderData2);

              function MeshRenderData(vertexFloatCnt) {
                var _this2;

                if (vertexFloatCnt === void 0) {
                  vertexFloatCnt = 9;
                }

                _this2 = _BaseRenderData2.call(this) || this;
                _this2.vData = void 0;
                _this2.iData = void 0;
                _this2.vertexStart = 0;
                _this2.indicesStart = 0;
                _this2.byteStart = 0;
                _this2.byteCount = 0;
                _this2.lastFilledIndices = 0;
                _this2.lastFilledVertex = 0;
                _this2._formatByte = void 0;
                _this2._formatByte = vertexFloatCnt * Float32Array.BYTES_PER_ELEMENT;
                _this2.vData = new Float32Array(256 * vertexFloatCnt * Float32Array.BYTES_PER_ELEMENT);
                _this2.iData = new Uint16Array(256 * 6);
                return _this2;
              }

              MeshRenderData.add = function add() {
                return _meshDataPool.add();
              };

              MeshRenderData.remove = function remove(data) {
                var idx = _meshDataPool.data.indexOf(data);

                if (idx === -1) {
                  return;
                }

                _meshDataPool.data[idx].reset();

                _meshDataPool.removeAt(idx);
              };

              var _proto2 = MeshRenderData.prototype;

              _proto2.request = function request(vertexCount, indicesCount) {
                var byteOffset = this.byteCount + vertexCount * this._formatByte;
                this.reserve(vertexCount, indicesCount);
                this.vertexCount += vertexCount;
                this.indicesCount += indicesCount;
                this.byteCount = byteOffset;
                return true;
              };

              _proto2.reserve = function reserve(vertexCount, indicesCount) {
                var newVBytes = this.byteCount + vertexCount * this._formatByte;
                var newICount = this.indicesCount + indicesCount;

                if (vertexCount + this.vertexCount > 65535) {
                  return false;
                }

                var byteLength = this.vData.byteLength;
                var indicesLength = this.iData.length;
                var vCount = this.vData.length;
                var iCount = this.iData.length;

                if (newVBytes > byteLength || newICount > indicesLength) {
                  while (byteLength < newVBytes || indicesLength < newICount) {
                    vCount *= 2;
                    iCount *= 2;
                    byteLength = vCount * 4;
                    indicesLength = iCount;
                  }

                  this._reallocBuffer(vCount, iCount);
                }

                return true;
              };

              _proto2.advance = function advance(vertexCount, indicesCount) {
                this.vertexCount += vertexCount;
                this.indicesCount += indicesCount;
                this.byteCount += vertexCount * this._formatByte;
              };

              _proto2.reset = function reset() {
                this.vertexCount = 0;
                this.indicesCount = 0;
                this.byteCount = 0;
                this.vertexStart = 0;
                this.indicesStart = 0;
                this.byteStart = 0;
                this.lastFilledIndices = 0;
                this.lastFilledVertex = 0;
              };

              _proto2._reallocBuffer = function _reallocBuffer(vCount, iCount) {
                var oldVData = this.vData;
                this.vData = new Float32Array(vCount);
                this.vData.set(oldVData, 0);
                var oldIData = this.iData;
                this.iData = new Uint16Array(iCount);
                this.iData.set(oldIData, 0);
              };

              _createClass(MeshRenderData, [{
                key: "formatByte",
                get: function get() {
                  return this._formatByte;
                },
                set: function set(value) {
                  this._formatByte = value;
                }
              }, {
                key: "floatStride",
                get: function get() {
                  return this._formatByte >> 2;
                }
              }, {
                key: "vDataOffset",
                get: function get() {
                  return this.byteCount >>> 2;
                }
              }]);

              return MeshRenderData;
            }(BaseRenderData);
            var QuadRenderData = function (_MeshRenderData) {
              _inheritsLoose(QuadRenderData, _MeshRenderData);

              function QuadRenderData() {
                return _MeshRenderData.apply(this, arguments) || this;
              }

              var _proto3 = QuadRenderData.prototype;

              _proto3._fillQuadBuffer = function _fillQuadBuffer() {
                var count = this.iData.length / 6;
                var buffer = this.iData;

                for (var i = 0, idx = 0; i < count; i++) {
                  var vId = i * 4;
                  buffer[idx++] = vId;
                  buffer[idx++] = vId + 1;
                  buffer[idx++] = vId + 2;
                  buffer[idx++] = vId + 1;
                  buffer[idx++] = vId + 3;
                  buffer[idx++] = vId + 2;
                }
              };

              _proto3._reallocBuffer = function _reallocBuffer(vCount, iCount) {
                _MeshRenderData.prototype._reallocBuffer.call(this, vCount, iCount);

                this._fillQuadBuffer();
              };

              return QuadRenderData;
            }(MeshRenderData);

            var _dataPool = new Pool$1(function () {
              return {
                x: 0,
                y: 0,
                z: 0,
                u: 0,
                v: 0,
                color: Color.WHITE.clone()
              };
            }, 128);

            var _pool = new RecyclePool(function () {
              return new RenderData();
            }, 32);

            var _meshDataPool = new RecyclePool(function () {
              return new MeshRenderData();
            }, 32);

            var _dec$T, _dec2$t, _dec3$l, _dec4$g, _dec5$c, _dec6$7, _dec7$5, _dec8$5, _class$U, _class2$P, _descriptor$F, _descriptor2$r, _class3$i, _temp$Q;

            var _vec2a = new Vec2();

            var _vec2b = new Vec2();

            var _mat4_temp = new Mat4();

            var _matrix = new Mat4();

            var _worldMatrix$1 = new Mat4();

            var _zeroMatrix = new Mat4(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);

            var _rect = new Rect();

            var UITransform = function (v) { return exports({ UITransform: v, UITransformComponent: v }), v; }((_dec$T = ccclass('cc.UITransform'), _dec2$t = help(), _dec3$l = executionOrder(110), _dec4$g = menu(), _dec5$c = displayOrder(), _dec6$7 = tooltip(), _dec7$5 = displayOrder(), _dec8$5 = tooltip(), _dec$T(_class$U = _dec2$t(_class$U = _dec3$l(_class$U = _dec4$g(_class$U = disallowMultiple(_class$U = executeInEditMode(_class$U = (_class2$P = (_temp$Q = _class3$i = function (_Component) {
              _inheritsLoose(UITransform, _Component);

              function UITransform() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Component.call.apply(_Component, [this].concat(args)) || this;
                _this._priority = 0;

                _initializerDefineProperty(_this, "_contentSize", _descriptor$F, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_anchorPoint", _descriptor2$r, _assertThisInitialized(_this));

                return _this;
              }

              var _proto = UITransform.prototype;

              _proto.__preload = function __preload() {
                this.node._uiProps.uiTransformComp = this;
              };

              _proto.onLoad = function onLoad() {
                if (this.node.parent) {
                  UITransform.insertChangeMap(this.node.parent);
                }
              };

              _proto.onEnable = function onEnable() {
                this.node.on(SystemEventType.PARENT_CHANGED, this._parentChanged, this);

                this._markRenderDataDirty();
              };

              _proto.onDisable = function onDisable() {
                this.node.off(SystemEventType.PARENT_CHANGED, this._parentChanged, this);
              };

              _proto.onDestroy = function onDestroy() {
                this.node._uiProps.uiTransformComp = null;
              };

              _proto.setContentSize = function setContentSize(size, height) {
                var locContentSize = this._contentSize;

                if (height === undefined) {
                  size = size;

                  if (size.width === locContentSize.width && size.height === locContentSize.height) {
                    return;
                  }

                  locContentSize.width = size.width;
                  locContentSize.height = size.height;
                } else {
                  if (size === locContentSize.width && height === locContentSize.height) {
                    return;
                  }

                  locContentSize.width = size;
                  locContentSize.height = height;
                }

                {
                  this.node.emit(SystemEventType.SIZE_CHANGED);
                }

                this._markRenderDataDirty();
              };

              _proto.setAnchorPoint = function setAnchorPoint(point, y) {
                var locAnchorPoint = this._anchorPoint;

                if (y === undefined) {
                  point = point;

                  if (point.x === locAnchorPoint.x && point.y === locAnchorPoint.y) {
                    return;
                  }

                  locAnchorPoint.x = point.x;
                  locAnchorPoint.y = point.y;
                } else {
                  if (point === locAnchorPoint.x && y === locAnchorPoint.y) {
                    return;
                  }

                  locAnchorPoint.x = point;
                  locAnchorPoint.y = y;
                }

                this.node.emit(SystemEventType.ANCHOR_CHANGED, this._anchorPoint);

                this._markRenderDataDirty();
              };

              _proto.isHit = function isHit(point, listener) {
                var w = this._contentSize.width;
                var h = this._contentSize.height;
                var cameraPt = _vec2a;
                var testPt = _vec2b;

                var cameras = this._getRenderScene().cameras;

                for (var i = 0; i < cameras.length; i++) {
                  var camera = cameras[i];
                  if (!(camera.visibility & this.node.layer)) continue;
                  camera.node.getWorldRT(_mat4_temp);
                  var m12 = _mat4_temp.m12;
                  var m13 = _mat4_temp.m13;
                  var center = legacyCC.visibleRect.center;
                  _mat4_temp.m12 = center.x - (_mat4_temp.m00 * m12 + _mat4_temp.m04 * m13);
                  _mat4_temp.m13 = center.y - (_mat4_temp.m01 * m12 + _mat4_temp.m05 * m13);
                  Mat4.invert(_mat4_temp, _mat4_temp);
                  Vec2.transformMat4(cameraPt, point, _mat4_temp);
                  this.node.getWorldMatrix(_worldMatrix$1);
                  Mat4.invert(_mat4_temp, _worldMatrix$1);

                  if (Mat4.strictEquals(_mat4_temp, _zeroMatrix)) {
                    continue;
                  }

                  Vec2.transformMat4(testPt, cameraPt, _mat4_temp);
                  testPt.x += this._anchorPoint.x * w;
                  testPt.y += this._anchorPoint.y * h;
                  var hit = false;

                  if (testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h) {
                    hit = true;

                    if (listener && listener.mask) {
                      var mask = listener.mask;
                      var parent = this.node;
                      var length = mask ? mask.length : 0;

                      for (var _i = 0, j = 0; parent && j < length; ++_i, parent = parent.parent) {
                        var temp = mask[j];

                        if (_i === temp.index) {
                          if (parent === temp.comp.node) {
                            var comp = temp.comp;

                            if (comp && comp._enabled && !comp.isHit(cameraPt)) {
                              hit = false;
                              break;
                            }

                            j++;
                          } else {
                            mask.length = j;
                            break;
                          }
                        } else if (_i > temp.index) {
                          mask.length = j;
                          break;
                        }
                      }
                    }
                  }

                  if (hit) {
                    return true;
                  }
                }

                return false;
              };

              _proto.convertToNodeSpaceAR = function convertToNodeSpaceAR(worldPoint, out) {
                this.node.getWorldMatrix(_worldMatrix$1);
                Mat4.invert(_mat4_temp, _worldMatrix$1);

                if (!out) {
                  out = new Vec3();
                }

                return Vec3.transformMat4(out, worldPoint, _mat4_temp);
              };

              _proto.convertToWorldSpaceAR = function convertToWorldSpaceAR(nodePoint, out) {
                this.node.getWorldMatrix(_worldMatrix$1);

                if (!out) {
                  out = new Vec3();
                }

                return Vec3.transformMat4(out, nodePoint, _worldMatrix$1);
              };

              _proto.getBoundingBox = function getBoundingBox() {
                Mat4.fromRTS(_matrix, this.node.getRotation(), this.node.getPosition(), this.node.getScale());
                var width = this._contentSize.width;
                var height = this._contentSize.height;
                var rect = new Rect(-this._anchorPoint.x * width, -this._anchorPoint.y * height, width, height);
                rect.transformMat4(_matrix);
                return rect;
              };

              _proto.getBoundingBoxToWorld = function getBoundingBoxToWorld() {
                if (this.node.parent) {
                  this.node.parent.getWorldMatrix(_worldMatrix$1);
                  return this.getBoundingBoxTo(_worldMatrix$1);
                }

                return this.getBoundingBox();
              };

              _proto.getBoundingBoxTo = function getBoundingBoxTo(parentMat) {
                Mat4.fromRTS(_matrix, this.node.getRotation(), this.node.getPosition(), this.node.getScale());
                var width = this._contentSize.width;
                var height = this._contentSize.height;
                var rect = new Rect(-this._anchorPoint.x * width, -this._anchorPoint.y * height, width, height);
                Mat4.multiply(_worldMatrix$1, parentMat, _matrix);
                rect.transformMat4(_worldMatrix$1);

                if (!this.node.children) {
                  return rect;
                }

                var locChildren = this.node.children;

                for (var _iterator = _createForOfIteratorHelperLoose(locChildren), _step; !(_step = _iterator()).done;) {
                  var child = _step.value;

                  if (child && child.active) {
                    var uiTransform = child.getComponent(UITransform);

                    if (uiTransform) {
                      var childRect = uiTransform.getBoundingBoxTo(parentMat);

                      if (childRect) {
                        Rect.union(rect, rect, childRect);
                      }
                    }
                  }
                }

                return rect;
              };

              _proto.getComputeAABB = function getComputeAABB(out) {
                var width = this._contentSize.width;
                var height = this._contentSize.height;

                _rect.set(-this._anchorPoint.x * width, -this._anchorPoint.y * height, width, height);

                _rect.transformMat4(this.node.worldMatrix);

                var px = _rect.x + _rect.width * 0.5;
                var py = _rect.y + _rect.height * 0.5;
                var pz = this.node.worldPosition.z;
                var w = _rect.width / 2;
                var h = _rect.height / 2;
                var l = 0.001;

                if (out != null) {
                  AABB.set(out, px, py, pz, w, h, l);
                  return out;
                } else {
                  return new AABB(px, py, pz, w, h, l);
                }
              };

              _proto._parentChanged = function _parentChanged(node) {
                if (this.node.getComponent('cc.RenderRoot2D')) {
                  return;
                }

                if (this.node.parent) {
                  UITransform.insertChangeMap(this.node.parent);
                }
              };

              _proto._markRenderDataDirty = function _markRenderDataDirty() {
                var uiComp = this.node._uiProps.uiComp;

                if (uiComp) {
                  uiComp.markForUpdateRenderData();
                }
              };

              UITransform.insertChangeMap = function insertChangeMap(node) {
                var key = node.uuid;

                if (!UITransform.priorityChangeNodeMap.has(key)) {
                  UITransform.priorityChangeNodeMap.set(key, node);
                }
              };

              UITransform._sortChildrenSibling = function _sortChildrenSibling(node) {
                var siblings = node.children;

                if (siblings) {
                  siblings.sort(function (a, b) {
                    var aComp = a._uiProps.uiTransformComp;
                    var bComp = b._uiProps.uiTransformComp;
                    var ca = aComp ? aComp._priority : 0;
                    var cb = bComp ? bComp._priority : 0;
                    var diff = ca - cb;
                    if (diff === 0) return a.getSiblingIndex() - b.getSiblingIndex();
                    return diff;
                  });
                }
              };

              UITransform._sortSiblings = function _sortSiblings() {
                UITransform.priorityChangeNodeMap.forEach(function (node, ID) {
                  UITransform._sortChildrenSibling(node);

                  node._updateSiblingIndex();

                  node.emit('childrenSiblingOrderChanged');
                });
                UITransform.priorityChangeNodeMap.clear();
              };

              UITransform._cleanChangeMap = function _cleanChangeMap() {
                UITransform.priorityChangeNodeMap.clear();
              };

              _createClass(UITransform, [{
                key: "contentSize",
                get: function get() {
                  return this._contentSize;
                },
                set: function set(value) {
                  if (this._contentSize.equals(value)) {
                    return;
                  }

                  this._contentSize.set(value);

                  {
                    this.node.emit(SystemEventType.SIZE_CHANGED);
                  }

                  this._markRenderDataDirty();
                }
              }, {
                key: "width",
                get: function get() {
                  return this._contentSize.width;
                },
                set: function set(value) {
                  if (this._contentSize.width === value) {
                    return;
                  }

                  this._contentSize.width = value;

                  {
                    this.node.emit(SystemEventType.SIZE_CHANGED);
                  }

                  this._markRenderDataDirty();
                }
              }, {
                key: "height",
                get: function get() {
                  return this._contentSize.height;
                },
                set: function set(value) {
                  if (this.contentSize.height === value) {
                    return;
                  }

                  this._contentSize.height = value;

                  {
                    this.node.emit(SystemEventType.SIZE_CHANGED);
                  }

                  this._markRenderDataDirty();
                }
              }, {
                key: "anchorPoint",
                get: function get() {
                  return this._anchorPoint;
                },
                set: function set(value) {
                  if (this._anchorPoint.equals(value)) {
                    return;
                  }

                  this._anchorPoint.set(value);

                  this.node.emit(SystemEventType.ANCHOR_CHANGED, this._anchorPoint);

                  this._markRenderDataDirty();
                }
              }, {
                key: "anchorX",
                get: function get() {
                  return this._anchorPoint.x;
                },
                set: function set(value) {
                  if (this._anchorPoint.x === value) {
                    return;
                  }

                  this._anchorPoint.x = value;
                  this.node.emit(SystemEventType.ANCHOR_CHANGED, this._anchorPoint);

                  this._markRenderDataDirty();
                }
              }, {
                key: "anchorY",
                get: function get() {
                  return this._anchorPoint.y;
                },
                set: function set(value) {
                  if (this._anchorPoint.y === value) {
                    return;
                  }

                  this._anchorPoint.y = value;
                  this.node.emit(SystemEventType.ANCHOR_CHANGED, this._anchorPoint);

                  this._markRenderDataDirty();
                }
              }, {
                key: "priority",
                get: function get() {
                  return this._priority;
                },
                set: function set(value) {
                  if (this._priority === value) {
                    return;
                  }

                  if (this.node.getComponent('cc.RenderRoot2D')) {
                    warnID(6706);
                    return;
                  }

                  this._priority = value;

                  if (this.node.parent) {
                    UITransform.insertChangeMap(this.node.parent);
                  }
                }
              }, {
                key: "visibility",
                get: function get() {
                  var camera = director.root.batcher2D.getFirstRenderCamera(this.node);
                  return camera ? camera.visibility : 0;
                }
              }, {
                key: "cameraPriority",
                get: function get() {
                  var camera = director.root.batcher2D.getFirstRenderCamera(this.node);
                  return camera ? camera.priority : 0;
                }
              }]);

              return UITransform;
            }(Component), _class3$i.EventType = SystemEventType, _class3$i.priorityChangeNodeMap = new Map(), _temp$Q), (_applyDecoratedDescriptor(_class2$P.prototype, "contentSize", [_dec5$c, _dec6$7], Object.getOwnPropertyDescriptor(_class2$P.prototype, "contentSize"), _class2$P.prototype), _applyDecoratedDescriptor(_class2$P.prototype, "anchorPoint", [_dec7$5, _dec8$5], Object.getOwnPropertyDescriptor(_class2$P.prototype, "anchorPoint"), _class2$P.prototype), _descriptor$F = _applyDecoratedDescriptor(_class2$P.prototype, "_contentSize", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new Size(100, 100);
              }
            }), _descriptor2$r = _applyDecoratedDescriptor(_class2$P.prototype, "_anchorPoint", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new Vec2(0.5, 0.5);
              }
            })), _class2$P)) || _class$U) || _class$U) || _class$U) || _class$U) || _class$U) || _class$U));
            director.on(Director.EVENT_AFTER_UPDATE, UITransform._sortSiblings);
            director.on(Director.EVENT_BEFORE_SCENE_LAUNCH, UITransform._cleanChangeMap);

            var Stage;

            (function (Stage) {
              Stage[Stage["DISABLED"] = 0] = "DISABLED";
              Stage[Stage["CLEAR"] = 1] = "CLEAR";
              Stage[Stage["ENTER_LEVEL"] = 2] = "ENTER_LEVEL";
              Stage[Stage["ENABLED"] = 3] = "ENABLED";
              Stage[Stage["EXIT_LEVEL"] = 4] = "EXIT_LEVEL";
              Stage[Stage["CLEAR_INVERTED"] = 5] = "CLEAR_INVERTED";
              Stage[Stage["ENTER_LEVEL_INVERTED"] = 6] = "ENTER_LEVEL_INVERTED";
            })(Stage || (Stage = {}));

            var StencilManager = exports('StencilManager', function () {
              function StencilManager() {
                this.stage = Stage.DISABLED;
                this._maskStack = [];
                this._stencilPattern = {
                  stencilTest: true,
                  func: ComparisonFunc.ALWAYS,
                  stencilMask: 0xffff,
                  writeMask: 0xffff,
                  failOp: StencilOp.KEEP,
                  zFailOp: StencilOp.KEEP,
                  passOp: StencilOp.KEEP,
                  ref: 1
                };
                this.stencilStateMap = new Map();
                this.stencilStateMapWithDepth = new Map();
              }

              var _proto = StencilManager.prototype;

              _proto.pushMask = function pushMask(mask) {
                this._maskStack.push(mask);
              };

              _proto.clear = function clear(comp) {
                comp.stencilStage = comp.inverted ? Stage.CLEAR_INVERTED : Stage.CLEAR;
              };

              _proto.enterLevel = function enterLevel(comp) {
                comp.graphics.stencilStage = comp.inverted ? Stage.ENTER_LEVEL_INVERTED : Stage.ENTER_LEVEL;
              };

              _proto.enableMask = function enableMask() {
                this.stage = Stage.ENABLED;
              };

              _proto.exitMask = function exitMask() {
                if (this._maskStack.length === 0) {
                  return;
                }

                this._maskStack.pop();

                if (this._maskStack.length === 0) {
                  this.stage = Stage.DISABLED;
                } else {
                  this.stage = Stage.ENABLED;
                }
              };

              _proto.getWriteMask = function getWriteMask() {
                return 1 << this._maskStack.length - 1;
              };

              _proto.getExitWriteMask = function getExitWriteMask() {
                return 1 << this._maskStack.length;
              };

              _proto.getStencilRef = function getStencilRef() {
                var result = 0;

                for (var i = 0; i < this._maskStack.length; ++i) {
                  result += 0x00000001 << i;
                }

                return result;
              };

              _proto.reset = function reset() {
                this._maskStack.length = 0;
                this.stage = Stage.DISABLED;
              };

              _proto.destroy = function destroy() {
                this.stencilStateMap.forEach(function (value, key) {
                  value.destroy();
                });
                this.stencilStateMap.clear();
              };

              _proto.getStencilStage = function getStencilStage(stage, mat) {
                var key = 0;
                var depthTest = false;
                var depthWrite = false;
                var depthFunc = ComparisonFunc.LESS;
                var cacheMap = this.stencilStateMap;

                if (mat && mat.passes[0]) {
                  var pass = mat.passes[0];
                  var dss = pass.depthStencilState;
                  var depthTestValue = 0;
                  var depthWriteValue = 0;
                  if (dss.depthTest) depthTestValue = 1;
                  if (dss.depthWrite) depthWriteValue = 1;
                  key = depthTestValue | depthWriteValue << 1 | dss.depthFunc << 2 | stage << 6 | this._maskStack.length << 9;
                  depthTest = dss.depthTest;
                  depthWrite = dss.depthWrite;
                  depthFunc = dss.depthFunc;
                  cacheMap = this.stencilStateMapWithDepth;
                } else {
                  key = stage << 16 | this._maskStack.length;
                }

                if (cacheMap && cacheMap.has(key)) {
                  return cacheMap.get(key);
                }

                this.setStateFromStage(stage);
                var depthStencilState = new DepthStencilState(depthTest, depthWrite, depthFunc, this._stencilPattern.stencilTest, this._stencilPattern.func, this._stencilPattern.stencilMask, this._stencilPattern.writeMask, this._stencilPattern.failOp, this._stencilPattern.zFailOp, this._stencilPattern.passOp, this._stencilPattern.ref, this._stencilPattern.stencilTest, this._stencilPattern.func, this._stencilPattern.stencilMask, this._stencilPattern.writeMask, this._stencilPattern.failOp, this._stencilPattern.zFailOp, this._stencilPattern.passOp, this._stencilPattern.ref);
                cacheMap.set(key, depthStencilState);
                return depthStencilState;
              };

              _proto.getStencilHash = function getStencilHash(stage) {
                return stage << 8 | this._maskStack.length;
              };

              _proto.setStateFromStage = function setStateFromStage(stage) {
                var pattern = this._stencilPattern;

                if (stage === Stage.DISABLED) {
                  pattern.stencilTest = false;
                  pattern.func = ComparisonFunc.ALWAYS;
                  pattern.failOp = StencilOp.KEEP;
                  pattern.stencilMask = pattern.writeMask = 0xffff;
                  pattern.ref = 1;
                } else {
                  pattern.stencilTest = true;

                  if (stage === Stage.ENABLED) {
                    pattern.func = ComparisonFunc.EQUAL;
                    pattern.failOp = StencilOp.KEEP;
                    pattern.stencilMask = pattern.ref = this.getStencilRef();
                    pattern.writeMask = this.getWriteMask();
                  } else if (stage === Stage.CLEAR) {
                    pattern.func = ComparisonFunc.NEVER;
                    pattern.failOp = StencilOp.ZERO;
                    pattern.writeMask = pattern.stencilMask = pattern.ref = this.getWriteMask();
                  } else if (stage === Stage.CLEAR_INVERTED) {
                    pattern.func = ComparisonFunc.NEVER;
                    pattern.failOp = StencilOp.REPLACE;
                    pattern.writeMask = pattern.stencilMask = pattern.ref = this.getWriteMask();
                  } else if (stage === Stage.ENTER_LEVEL) {
                    pattern.func = ComparisonFunc.NEVER;
                    pattern.failOp = StencilOp.REPLACE;
                    pattern.writeMask = pattern.stencilMask = pattern.ref = this.getWriteMask();
                  } else if (stage === Stage.ENTER_LEVEL_INVERTED) {
                    pattern.func = ComparisonFunc.NEVER;
                    pattern.failOp = StencilOp.ZERO;
                    pattern.writeMask = pattern.stencilMask = pattern.ref = this.getWriteMask();
                  }
                }
              };

              _createClass(StencilManager, [{
                key: "pattern",
                get: function get() {
                  return this._stencilPattern;
                }
              }]);

              return StencilManager;
            }());
            StencilManager.sharedManager = null;
            StencilManager.sharedManager = new StencilManager();

            var _dec$U, _dec2$u, _dec3$m, _dec4$h, _dec5$d, _dec6$8, _dec7$6, _dec8$6, _dec9$5, _class$V, _class2$Q, _descriptor$G, _descriptor2$s, _descriptor3$i, _descriptor4$f, _descriptor5$b, _class3$j, _temp$R;
            ccenum(BlendFactor);
            var InstanceMaterialType;

            (function (InstanceMaterialType) {
              InstanceMaterialType[InstanceMaterialType["ADD_COLOR"] = 0] = "ADD_COLOR";
              InstanceMaterialType[InstanceMaterialType["ADD_COLOR_AND_TEXTURE"] = 1] = "ADD_COLOR_AND_TEXTURE";
              InstanceMaterialType[InstanceMaterialType["GRAYSCALE"] = 2] = "GRAYSCALE";
              InstanceMaterialType[InstanceMaterialType["USE_ALPHA_SEPARATED"] = 3] = "USE_ALPHA_SEPARATED";
              InstanceMaterialType[InstanceMaterialType["USE_ALPHA_SEPARATED_AND_GRAY"] = 4] = "USE_ALPHA_SEPARATED_AND_GRAY";
            })(InstanceMaterialType || (InstanceMaterialType = exports('InstanceMaterialType', {})));
            var Renderable2D = function (v) { return exports({ Renderable2D: v, RenderComponent: v, UIRenderable: v }), v; }((_dec$U = ccclass('cc.Renderable2D'), _dec2$u = requireComponent(UITransform), _dec3$m = visible(), _dec4$h = type(Material), _dec5$d = type(Material), _dec6$8 = displayOrder(), _dec7$6 = displayName(), _dec8$6 = displayOrder(), _dec9$5 = tooltip(), _dec$U(_class$V = _dec2$u(_class$V = disallowMultiple(_class$V = executeInEditMode(_class$V = (_class2$Q = (_temp$R = _class3$j = function (_RenderableComponent) {
              _inheritsLoose(Renderable2D, _RenderableComponent);

              function Renderable2D() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _RenderableComponent.call.apply(_RenderableComponent, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "_materials", _descriptor$G, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_customMaterial", _descriptor2$s, _assertThisInitialized(_this));

                _this.stencilStage = Stage.DISABLED;

                _initializerDefineProperty(_this, "_srcBlendFactor", _descriptor3$i, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_dstBlendFactor", _descriptor4$f, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_color", _descriptor5$b, _assertThisInitialized(_this));

                _this._assembler = null;
                _this._postAssembler = null;
                _this._renderData = null;
                _this._renderDataFlag = true;
                _this._renderFlag = true;
                _this._delegateSrc = null;
                _this._instanceMaterialType = InstanceMaterialType.ADD_COLOR_AND_TEXTURE;
                _this._blendState = new BlendState();
                _this._blendHash = 0;
                _this._colorDirty = true;
                _this._cacheAlpha = 1;
                _this._lastParent = null;
                return _this;
              }

              var _proto = Renderable2D.prototype;

              _proto.updateMaterial = function updateMaterial() {
                if (this._customMaterial) {
                  this.setMaterial(this._customMaterial, 0);
                  this._blendHash = -1;
                  return;
                }

                var mat = this._updateBuiltinMaterial();

                this.setMaterial(mat, 0);

                this._updateBlendFunc();
              };

              _proto.updateBlendHash = function updateBlendHash() {
                var dst = this._blendState.targets[0].blendDst << 4;
                this._blendHash = dst | this._blendState.targets[0].blendSrc;
              };

              _proto.__preload = function __preload() {
                this.node._uiProps.uiComp = this;

                if (this._flushAssembler) {
                  this._flushAssembler();
                }
              };

              _proto.onEnable = function onEnable() {
                this.node.on(SystemEventType.ANCHOR_CHANGED, this._nodeStateChange, this);
                this.node.on(SystemEventType.SIZE_CHANGED, this._nodeStateChange, this);
                this.updateMaterial();
                this._renderFlag = this._canRender();
              };

              _proto.onRestore = function onRestore() {
                this.updateMaterial();
                this._renderFlag = this._canRender();
              };

              _proto.onDisable = function onDisable() {
                this.node.off(SystemEventType.ANCHOR_CHANGED, this._nodeStateChange, this);
                this.node.off(SystemEventType.SIZE_CHANGED, this._nodeStateChange, this);
                this._renderFlag = false;
              };

              _proto.onDestroy = function onDestroy() {
                if (this.node._uiProps.uiComp === this) {
                  this.node._uiProps.uiComp = null;
                }

                this.destroyRenderData();

                if (this._materialInstances) {
                  for (var i = 0; i < this._materialInstances.length; i++) {
                    this._materialInstances[i] && this._materialInstances[i].destroy();
                  }
                }

                this._renderData = null;

                if (this._blendState) {
                  this._blendState.destroy();
                }
              };

              _proto.markForUpdateRenderData = function markForUpdateRenderData(enable) {
                if (enable === void 0) {
                  enable = true;
                }

                this._renderFlag = this._canRender();

                if (enable && this._renderFlag) {
                  var renderData = this._renderData;

                  if (renderData) {
                    renderData.vertDirty = true;
                  }

                  this._renderDataFlag = enable;
                } else if (!enable) {
                  this._renderDataFlag = enable;
                }
              };

              _proto.requestRenderData = function requestRenderData() {
                var data = RenderData.add();
                this._renderData = data;
                return data;
              };

              _proto.destroyRenderData = function destroyRenderData() {
                if (!this._renderData) {
                  return;
                }

                RenderData.remove(this._renderData);
                this._renderData = null;
              };

              _proto.updateAssembler = function updateAssembler(render) {
                this._updateColor();

                if (this._renderFlag) {
                  this._checkAndUpdateRenderData();

                  this._render(render);
                }
              };

              _proto.postUpdateAssembler = function postUpdateAssembler(render) {
                if (this._renderFlag) {
                  this._postRender(render);
                }
              };

              _proto._render = function _render(render) {};

              _proto._postRender = function _postRender(render) {};

              _proto._checkAndUpdateRenderData = function _checkAndUpdateRenderData() {
                if (this._renderDataFlag) {
                  this._assembler.updateRenderData(this);

                  this._renderDataFlag = false;
                }
              };

              _proto._canRender = function _canRender() {
                return this.isValid && this.getMaterial(0) !== null && this.enabled && (this._delegateSrc ? this._delegateSrc.activeInHierarchy : this.enabledInHierarchy) && this.node._uiProps.opacity > 0;
              };

              _proto._postCanRender = function _postCanRender() {};

              _proto._updateColor = function _updateColor() {
                this._updateWorldAlpha();

                if (this._colorDirty && this._assembler && this._assembler.updateColor) {
                  this._assembler.updateColor(this);

                  this._colorDirty = false;
                }
              };

              _proto._updateWorldAlpha = function _updateWorldAlpha() {
                var localAlpha = this.color.a / 255;
                if (localAlpha === 1) localAlpha = this.node._uiProps.localOpacity;
                var parent = this.node.parent;
                var alpha = parent && parent._uiProps ? parent._uiProps.opacity * localAlpha : localAlpha;
                this.node._uiProps.opacity = alpha;
                this._colorDirty = this._colorDirty || alpha !== this._cacheAlpha;
                this._cacheAlpha = alpha;
              };

              _proto._updateBlendFunc = function _updateBlendFunc() {
                var target = this._blendState.targets[0];

                if (!target) {
                  target = new BlendTarget();

                  this._blendState.setTarget(0, target);
                }

                if (target.blendDst !== this._dstBlendFactor || target.blendSrc !== this._srcBlendFactor) {
                  target.blend = true;
                  target.blendDstAlpha = BlendFactor.ONE_MINUS_SRC_ALPHA;
                  target.blendDst = this._dstBlendFactor;
                  target.blendSrc = this._srcBlendFactor;
                }

                this.updateBlendHash();
              };

              _proto.getBlendState = function getBlendState() {
                return this._blendState;
              };

              _proto._nodeStateChange = function _nodeStateChange(transformType) {
                if (this._renderData) {
                  this.markForUpdateRenderData();
                }

                for (var i = 0; i < this.node.children.length; ++i) {
                  var child = this.node.children[i];
                  var renderComp = child.getComponent(Renderable2D);

                  if (renderComp) {
                    renderComp.markForUpdateRenderData();
                  }
                }
              };

              _proto._updateBuiltinMaterial = function _updateBuiltinMaterial() {
                var mat;

                switch (this._instanceMaterialType) {
                  case InstanceMaterialType.ADD_COLOR:
                    mat = builtinResMgr.get('ui-base-material');
                    break;

                  case InstanceMaterialType.GRAYSCALE:
                    mat = builtinResMgr.get('ui-sprite-gray-material');
                    break;

                  case InstanceMaterialType.USE_ALPHA_SEPARATED:
                    mat = builtinResMgr.get('ui-sprite-alpha-sep-material');
                    break;

                  case InstanceMaterialType.USE_ALPHA_SEPARATED_AND_GRAY:
                    mat = builtinResMgr.get('ui-sprite-gray-alpha-sep-material');
                    break;

                  default:
                    mat = builtinResMgr.get('ui-sprite-material');
                    break;
                }

                return mat;
              };

              _proto._setCacheAlpha = function _setCacheAlpha(value) {
                this._cacheAlpha = value;
              };

              _createClass(Renderable2D, [{
                key: "sharedMaterials",
                get: function get() {
                  return  this._materials;
                },
                set: function set(val) {
                  for (var i = 0; i < val.length; i++) {
                    if (val[i] !== this._materials[i]) {
                      this.setMaterial(val[i], i);
                    }
                  }

                  if (val.length < this._materials.length) {
                    for (var _i = val.length; _i < this._materials.length; _i++) {
                      this.setMaterial(null, _i);
                    }

                    this._materials.splice(val.length);
                  }
                }
              }, {
                key: "customMaterial",
                get: function get() {
                  return this._customMaterial;
                },
                set: function set(val) {
                  this._customMaterial = val;
                  this.updateMaterial();
                }
              }, {
                key: "srcBlendFactor",
                get: function get() {
                  if ( this._customMaterial) {
                    warnID(12001);
                  }

                  return this._srcBlendFactor;
                },
                set: function set(value) {
                  if (this._customMaterial) {
                    warnID(12001);
                    return;
                  }

                  if (this._srcBlendFactor === value) {
                    return;
                  }

                  this._srcBlendFactor = value;

                  this._updateBlendFunc();
                }
              }, {
                key: "dstBlendFactor",
                get: function get() {
                  if ( this._customMaterial) {
                    warnID(12001);
                  }

                  return this._dstBlendFactor;
                },
                set: function set(value) {
                  if (this._customMaterial) {
                    warnID(12001);
                    return;
                  }

                  if (this._dstBlendFactor === value) {
                    return;
                  }

                  this._dstBlendFactor = value;

                  this._updateBlendFunc();
                }
              }, {
                key: "color",
                get: function get() {
                  return this._color;
                },
                set: function set(value) {
                  if (this._color.equals(value)) {
                    return;
                  }

                  this._color.set(value);

                  this._colorDirty = true;
                }
              }, {
                key: "renderData",
                get: function get() {
                  return this._renderData;
                }
              }, {
                key: "delegateSrc",
                set: function set(value) {
                  this._delegateSrc = value;
                }
              }, {
                key: "blendHash",
                get: function get() {
                  return this._blendHash;
                }
              }]);

              return Renderable2D;
            }(RenderableComponent), _class3$j.BlendState = BlendFactor, _class3$j.Assembler = null, _class3$j.PostAssembler = null, _temp$R), (_descriptor$G = _applyDecoratedDescriptor(_class2$Q.prototype, "_materials", [override], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _applyDecoratedDescriptor(_class2$Q.prototype, "sharedMaterials", [override, _dec3$m], Object.getOwnPropertyDescriptor(_class2$Q.prototype, "sharedMaterials"), _class2$Q.prototype), _descriptor2$s = _applyDecoratedDescriptor(_class2$Q.prototype, "_customMaterial", [_dec4$h], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _applyDecoratedDescriptor(_class2$Q.prototype, "customMaterial", [_dec5$d, _dec6$8, _dec7$6], Object.getOwnPropertyDescriptor(_class2$Q.prototype, "customMaterial"), _class2$Q.prototype), _applyDecoratedDescriptor(_class2$Q.prototype, "color", [_dec8$6, _dec9$5], Object.getOwnPropertyDescriptor(_class2$Q.prototype, "color"), _class2$Q.prototype), _descriptor3$i = _applyDecoratedDescriptor(_class2$Q.prototype, "_srcBlendFactor", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return BlendFactor.SRC_ALPHA;
              }
            }), _descriptor4$f = _applyDecoratedDescriptor(_class2$Q.prototype, "_dstBlendFactor", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return BlendFactor.ONE_MINUS_SRC_ALPHA;
              }
            }), _descriptor5$b = _applyDecoratedDescriptor(_class2$Q.prototype, "_color", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return Color.WHITE.clone();
              }
            })), _class2$Q)) || _class$V) || _class$V) || _class$V) || _class$V));
            legacyCC.internal.Renderable2D = Renderable2D;

            var _dec$V, _dec2$v, _dec3$n, _dec4$i, _dec5$e, _dec6$9, _dec7$7, _dec8$7, _dec9$6, _dec10$5, _dec11$4, _dec12$4, _dec13$4, _dec14$4, _dec15$4, _dec16$4, _dec17$4, _dec18$4, _dec19$4, _dec20$4, _dec21$4, _dec22$4, _dec23$4, _dec24$4, _dec25$4, _dec26$4, _dec27$3, _dec28$3, _dec29$3, _dec30$3, _dec31$3, _dec32$2, _dec33$2, _dec34$2, _dec35$2, _dec36$2, _dec37$2, _dec38$2, _dec39$2, _dec40$2, _class$W, _class2$R, _descriptor$H, _descriptor2$t, _descriptor3$j, _descriptor4$g, _descriptor5$c, _descriptor6$7, _descriptor7$6, _descriptor8$6, _descriptor9$5, _descriptor10$5, _descriptor11$5, _descriptor12$4, _descriptor13$4, _descriptor14$4, _descriptor15$4, _descriptor16$4, _class3$k, _temp$S;
            var HorizontalTextAlignment;

            (function (HorizontalTextAlignment) {
              HorizontalTextAlignment[HorizontalTextAlignment["LEFT"] = 0] = "LEFT";
              HorizontalTextAlignment[HorizontalTextAlignment["CENTER"] = 1] = "CENTER";
              HorizontalTextAlignment[HorizontalTextAlignment["RIGHT"] = 2] = "RIGHT";
            })(HorizontalTextAlignment || (HorizontalTextAlignment = exports('HorizontalTextAlignment', {})));

            ccenum(HorizontalTextAlignment);
            var VerticalTextAlignment;

            (function (VerticalTextAlignment) {
              VerticalTextAlignment[VerticalTextAlignment["TOP"] = 0] = "TOP";
              VerticalTextAlignment[VerticalTextAlignment["CENTER"] = 1] = "CENTER";
              VerticalTextAlignment[VerticalTextAlignment["BOTTOM"] = 2] = "BOTTOM";
            })(VerticalTextAlignment || (VerticalTextAlignment = exports('VerticalTextAlignment', {})));

            ccenum(VerticalTextAlignment);
            var Overflow;

            (function (Overflow) {
              Overflow[Overflow["NONE"] = 0] = "NONE";
              Overflow[Overflow["CLAMP"] = 1] = "CLAMP";
              Overflow[Overflow["SHRINK"] = 2] = "SHRINK";
              Overflow[Overflow["RESIZE_HEIGHT"] = 3] = "RESIZE_HEIGHT";
            })(Overflow || (Overflow = exports('Overflow', {})));

            ccenum(Overflow);
            var CacheMode;

            (function (CacheMode) {
              CacheMode[CacheMode["NONE"] = 0] = "NONE";
              CacheMode[CacheMode["BITMAP"] = 1] = "BITMAP";
              CacheMode[CacheMode["CHAR"] = 2] = "CHAR";
            })(CacheMode || (CacheMode = exports('CacheMode', {})));

            ccenum(CacheMode);
            var Label = function (v) { return exports({ Label: v, LabelComponent: v }), v; }((_dec$V = ccclass('cc.Label'), _dec2$v = help(), _dec3$n = executionOrder(110), _dec4$i = menu(), _dec5$e = displayOrder(), _dec6$9 = tooltip(), _dec7$7 = type(HorizontalTextAlignment), _dec8$7 = displayOrder(), _dec9$6 = tooltip(), _dec10$5 = type(VerticalTextAlignment), _dec11$4 = displayOrder(), _dec12$4 = tooltip(), _dec13$4 = displayOrder(), _dec14$4 = tooltip(), _dec15$4 = displayOrder(), _dec16$4 = visible(), _dec17$4 = tooltip(), _dec18$4 = displayOrder(), _dec19$4 = tooltip(), _dec20$4 = type(Overflow), _dec21$4 = displayOrder(), _dec22$4 = tooltip(), _dec23$4 = displayOrder(), _dec24$4 = tooltip(), _dec25$4 = type(Font), _dec26$4 = displayOrder(), _dec27$3 = visible(), _dec28$3 = tooltip(), _dec29$3 = displayOrder(), _dec30$3 = tooltip(), _dec31$3 = type(CacheMode), _dec32$2 = displayOrder(), _dec33$2 = tooltip(), _dec34$2 = displayOrder(), _dec35$2 = tooltip(), _dec36$2 = displayOrder(), _dec37$2 = tooltip(), _dec38$2 = displayOrder(), _dec39$2 = tooltip(), _dec40$2 = visible(), _dec$V(_class$W = _dec2$v(_class$W = _dec3$n(_class$W = _dec4$i(_class$W = (_class2$R = (_temp$S = _class3$k = function (_Renderable2D) {
              _inheritsLoose(Label, _Renderable2D);

              function Label() {
                var _this;

                _this = _Renderable2D.call(this) || this;

                _initializerDefineProperty(_this, "_string", _descriptor$H, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_horizontalAlign", _descriptor2$t, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_verticalAlign", _descriptor3$j, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_actualFontSize", _descriptor4$g, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_fontSize", _descriptor5$c, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_fontFamily", _descriptor6$7, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_lineHeight", _descriptor7$6, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_overflow", _descriptor8$6, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_enableWrapText", _descriptor9$5, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_font", _descriptor10$5, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_isSystemFontUsed", _descriptor11$5, _assertThisInitialized(_this));

                _this._spacingX = 0;

                _initializerDefineProperty(_this, "_isItalic", _descriptor12$4, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_isBold", _descriptor13$4, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_isUnderline", _descriptor14$4, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_underlineHeight", _descriptor15$4, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_cacheMode", _descriptor16$4, _assertThisInitialized(_this));

                _this._N$file = null;
                _this._texture = null;
                _this._ttfSpriteFrame = null;
                _this._userDefinedFont = null;
                _this._assemblerData = null;
                _this._fontAtlas = null;
                _this._letterTexture = null;

                _this._ttfSpriteFrame = null;
                return _this;
              }

              var _proto = Label.prototype;

              _proto.onEnable = function onEnable() {
                _Renderable2D.prototype.onEnable.call(this);

                if (!this._font && !this._isSystemFontUsed) {
                  this.useSystemFont = true;
                }

                if (this._isSystemFontUsed && !this._fontFamily) {
                  this.fontFamily = 'Arial';
                }

                this.updateRenderData(true);
              };

              _proto.onDisable = function onDisable() {
                _Renderable2D.prototype.onDisable.call(this);
              };

              _proto.onDestroy = function onDestroy() {
                if (this._assembler && this._assembler.resetAssemblerData) {
                  this._assembler.resetAssemblerData(this._assemblerData);
                }

                this._assemblerData = null;

                if (this._ttfSpriteFrame) {
                  var tex = this._ttfSpriteFrame.texture;

                  if (tex && this._ttfSpriteFrame.original === null) {
                    var tex2d = tex;

                    if (tex2d.image) {
                      tex2d.image.destroy();
                    }

                    tex.destroy();
                  }

                  this._ttfSpriteFrame = null;
                }

                this._letterTexture = null;

                _Renderable2D.prototype.onDestroy.call(this);
              };

              _proto.updateRenderData = function updateRenderData(force) {
                if (force === void 0) {
                  force = false;
                }

                this.markForUpdateRenderData();

                if (force) {
                  this._flushAssembler();

                  if (this.renderData) this.renderData.vertDirty = true;

                  this._applyFontTexture();
                }
              };

              _proto._render = function _render(render) {
                render.commitComp(this, this._texture, this._assembler, null);
              };

              _proto._updateColor = function _updateColor() {
                if (this._font instanceof BitmapFont) {
                  this._updateWorldAlpha();

                  this._colorDirty = false;
                } else {
                  this._updateWorldAlpha();

                  if (this._colorDirty) {
                    this.updateRenderData(false);
                    this._colorDirty = false;
                  } else if (this._cacheAlpha !== this.node._uiProps.opacity && this._renderFlag && this._assembler && this._assembler.updateOpacity) {
                    this._assembler.updateOpacity(this);

                    this._cacheAlpha = this.node._uiProps.opacity;
                  }
                }
              };

              _proto._canRender = function _canRender() {
                if (!_Renderable2D.prototype._canRender.call(this) || !this._string) {
                  return false;
                }

                var font = this._font;

                if (font && font instanceof BitmapFont) {
                  var spriteFrame = font.spriteFrame;

                  if (!spriteFrame || !spriteFrame.textureLoaded()) {
                    return false;
                  }
                }

                return true;
              };

              _proto._flushAssembler = function _flushAssembler() {
                var assembler = Label.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.material;
                  }
                }
              };

              _proto._applyFontTexture = function _applyFontTexture() {
                var _this2 = this;

                var font = this._font;

                if (font instanceof BitmapFont) {
                  var spriteFrame = font.spriteFrame;

                  var onBMFontTextureLoaded = function onBMFontTextureLoaded() {
                    _this2._texture = spriteFrame;

                    _this2.changeMaterialForDefine();

                    if (_this2._assembler) {
                      _this2._assembler.updateRenderData(_this2);
                    }
                  };

                  if (spriteFrame) {
                    if (spriteFrame.loaded || spriteFrame.textureLoaded) {
                      onBMFontTextureLoaded();
                    } else {
                      spriteFrame.once('load', onBMFontTextureLoaded, this);
                    }
                  }
                } else {
                  if (this.cacheMode === CacheMode.CHAR) {
                    this._letterTexture = this._assembler.getAssemblerData();
                    this._texture = this._letterTexture;
                  } else if (!this._ttfSpriteFrame) {
                    this._ttfSpriteFrame = new SpriteFrame();
                    this._assemblerData = this._assembler.getAssemblerData();
                    var image = new ImageAsset(this._assemblerData.canvas);
                    var tex = image._texture;
                    this._ttfSpriteFrame.texture = tex;
                  }

                  if (this.cacheMode !== CacheMode.CHAR) {
                    this._texture = this._ttfSpriteFrame;
                  }

                  this.changeMaterialForDefine();
                  this._assembler && this._assembler.updateRenderData(this);
                }
              };

              _proto.changeMaterialForDefine = function changeMaterialForDefine() {
                if (!this._texture) {
                  return;
                }

                var value = false;

                if (this.cacheMode !== CacheMode.CHAR) {
                  var spriteFrame = this._texture;
                  var texture = spriteFrame.texture;

                  if (texture instanceof TextureBase) {
                    var format = texture.getPixelFormat();
                    value = format === PixelFormat.RGBA_ETC1 || format === PixelFormat.RGB_A_PVRTC_4BPPV1 || format === PixelFormat.RGB_A_PVRTC_2BPPV1;
                  }
                }

                if (value) {
                  this._instanceMaterialType = InstanceMaterialType.USE_ALPHA_SEPARATED;
                } else {
                  this._instanceMaterialType = InstanceMaterialType.ADD_COLOR_AND_TEXTURE;
                }

                this.updateMaterial();
              };

              _createClass(Label, [{
                key: "string",
                get: function get() {
                  return this._string;
                },
                set: function set(value) {
                  value += '';

                  if (this._string === value) {
                    return;
                  }

                  this._string = value;
                  this.updateRenderData();
                }
              }, {
                key: "horizontalAlign",
                get: function get() {
                  return this._horizontalAlign;
                },
                set: function set(value) {
                  if (this._horizontalAlign === value) {
                    return;
                  }

                  this._horizontalAlign = value;
                  this.updateRenderData();
                }
              }, {
                key: "verticalAlign",
                get: function get() {
                  return this._verticalAlign;
                },
                set: function set(value) {
                  if (this._verticalAlign === value) {
                    return;
                  }

                  this._verticalAlign = value;
                  this.updateRenderData();
                }
              }, {
                key: "actualFontSize",
                get: function get() {
                  return this._actualFontSize;
                },
                set: function set(value) {
                  this._actualFontSize = value;
                }
              }, {
                key: "fontSize",
                get: function get() {
                  return this._fontSize;
                },
                set: function set(value) {
                  if (this._fontSize === value) {
                    return;
                  }

                  this._fontSize = value;
                  this.updateRenderData();
                }
              }, {
                key: "fontFamily",
                get: function get() {
                  return this._fontFamily;
                },
                set: function set(value) {
                  if (this._fontFamily === value) {
                    return;
                  }

                  this._fontFamily = value;
                  this.updateRenderData();
                }
              }, {
                key: "lineHeight",
                get: function get() {
                  return this._lineHeight;
                },
                set: function set(value) {
                  if (this._lineHeight === value) {
                    return;
                  }

                  this._lineHeight = value;
                  this.updateRenderData();
                }
              }, {
                key: "overflow",
                get: function get() {
                  return this._overflow;
                },
                set: function set(value) {
                  if (this._overflow === value) {
                    return;
                  }

                  this._overflow = value;
                  this.updateRenderData();
                }
              }, {
                key: "enableWrapText",
                get: function get() {
                  return this._enableWrapText;
                },
                set: function set(value) {
                  if (this._enableWrapText === value) {
                    return;
                  }

                  this._enableWrapText = value;
                  this.updateRenderData();
                }
              }, {
                key: "font",
                get: function get() {
                  return this._font;
                },
                set: function set(value) {
                  if (this._font === value) {
                    return;
                  }

                  this._isSystemFontUsed = !value;

                  this._font = value;

                  if (this._renderData) {
                    this.destroyRenderData();
                    this._renderData = null;
                  }

                  this._fontAtlas = null;
                  this.updateRenderData(true);
                }
              }, {
                key: "useSystemFont",
                get: function get() {
                  return this._isSystemFontUsed;
                },
                set: function set(value) {
                  if (this._isSystemFontUsed === value) {
                    return;
                  }

                  this.destroyRenderData();
                  this._renderData = null;

                  this._isSystemFontUsed = !!value;

                  if (value) {
                    this.font = null;
                  }

                  this._flushAssembler();

                  this.updateRenderData();
                }
              }, {
                key: "cacheMode",
                get: function get() {
                  return this._cacheMode;
                },
                set: function set(value) {
                  if (this._cacheMode === value) {
                    return;
                  }

                  if (this._cacheMode === CacheMode.BITMAP && !(this._font instanceof BitmapFont) && this._ttfSpriteFrame) {
                    this._ttfSpriteFrame._resetDynamicAtlasFrame();
                  }

                  if (this._cacheMode === CacheMode.CHAR) {
                    this._ttfSpriteFrame = null;
                  }

                  this._cacheMode = value;
                  this.updateRenderData(true);
                }
              }, {
                key: "spriteFrame",
                get: function get() {
                  return this._texture;
                }
              }, {
                key: "ttfSpriteFrame",
                get: function get() {
                  return this._ttfSpriteFrame;
                }
              }, {
                key: "isBold",
                get: function get() {
                  return this._isBold;
                },
                set: function set(value) {
                  if (this._isBold === value) {
                    return;
                  }

                  this._isBold = value;
                  this.updateRenderData();
                }
              }, {
                key: "isItalic",
                get: function get() {
                  return this._isItalic;
                },
                set: function set(value) {
                  if (this._isItalic === value) {
                    return;
                  }

                  this._isItalic = value;
                  this.updateRenderData();
                }
              }, {
                key: "isUnderline",
                get: function get() {
                  return this._isUnderline;
                },
                set: function set(value) {
                  if (this._isUnderline === value) {
                    return;
                  }

                  this._isUnderline = value;
                  this.updateRenderData();
                }
              }, {
                key: "underlineHeight",
                get: function get() {
                  return this._underlineHeight;
                },
                set: function set(value) {
                  if (this._underlineHeight === value) return;
                  this._underlineHeight = value;
                  this.updateRenderData();
                }
              }, {
                key: "assemblerData",
                get: function get() {
                  return this._assemblerData;
                }
              }, {
                key: "fontAtlas",
                get: function get() {
                  return this._fontAtlas;
                },
                set: function set(value) {
                  this._fontAtlas = value;
                }
              }, {
                key: "spacingX",
                get: function get() {
                  return this._spacingX;
                },
                set: function set(value) {
                  if (this._spacingX === value) {
                    return;
                  }

                  this._spacingX = value;
                  this.updateRenderData();
                }
              }, {
                key: "_bmFontOriginalSize",
                get: function get() {
                  if (this._font instanceof BitmapFont) {
                    return this._font.fontSize;
                  } else {
                    return -1;
                  }
                }
              }]);

              return Label;
            }(Renderable2D), _class3$k.HorizontalAlign = HorizontalTextAlignment, _class3$k.VerticalAlign = VerticalTextAlignment, _class3$k.Overflow = Overflow, _class3$k.CacheMode = CacheMode, _class3$k._canvasPool = CanvasPool.getInstance(), _temp$S), (_applyDecoratedDescriptor(_class2$R.prototype, "string", [_dec5$e, _dec6$9, multiline], Object.getOwnPropertyDescriptor(_class2$R.prototype, "string"), _class2$R.prototype), _applyDecoratedDescriptor(_class2$R.prototype, "horizontalAlign", [_dec7$7, _dec8$7, _dec9$6], Object.getOwnPropertyDescriptor(_class2$R.prototype, "horizontalAlign"), _class2$R.prototype), _applyDecoratedDescriptor(_class2$R.prototype, "verticalAlign", [_dec10$5, _dec11$4, _dec12$4], Object.getOwnPropertyDescriptor(_class2$R.prototype, "verticalAlign"), _class2$R.prototype), _applyDecoratedDescriptor(_class2$R.prototype, "fontSize", [_dec13$4, _dec14$4], Object.getOwnPropertyDescriptor(_class2$R.prototype, "fontSize"), _class2$R.prototype), _applyDecoratedDescriptor(_class2$R.prototype, "fontFamily", [_dec15$4, _dec16$4, _dec17$4], Object.getOwnPropertyDescriptor(_class2$R.prototype, "fontFamily"), _class2$R.prototype), _applyDecoratedDescriptor(_class2$R.prototype, "lineHeight", [_dec18$4, _dec19$4], Object.getOwnPropertyDescriptor(_class2$R.prototype, "lineHeight"), _class2$R.prototype), _applyDecoratedDescriptor(_class2$R.prototype, "overflow", [_dec20$4, _dec21$4, _dec22$4], Object.getOwnPropertyDescriptor(_class2$R.prototype, "overflow"), _class2$R.prototype), _applyDecoratedDescriptor(_class2$R.prototype, "enableWrapText", [_dec23$4, _dec24$4], Object.getOwnPropertyDescriptor(_class2$R.prototype, "enableWrapText"), _class2$R.prototype), _applyDecoratedDescriptor(_class2$R.prototype, "font", [_dec25$4, _dec26$4, _dec27$3, _dec28$3], Object.getOwnPropertyDescriptor(_class2$R.prototype, "font"), _class2$R.prototype), _applyDecoratedDescriptor(_class2$R.prototype, "useSystemFont", [_dec29$3, _dec30$3], Object.getOwnPropertyDescriptor(_class2$R.prototype, "useSystemFont"), _class2$R.prototype), _applyDecoratedDescriptor(_class2$R.prototype, "cacheMode", [_dec31$3, _dec32$2, _dec33$2], Object.getOwnPropertyDescriptor(_class2$R.prototype, "cacheMode"), _class2$R.prototype), _applyDecoratedDescriptor(_class2$R.prototype, "isBold", [_dec34$2, _dec35$2], Object.getOwnPropertyDescriptor(_class2$R.prototype, "isBold"), _class2$R.prototype), _applyDecoratedDescriptor(_class2$R.prototype, "isItalic", [_dec36$2, _dec37$2], Object.getOwnPropertyDescriptor(_class2$R.prototype, "isItalic"), _class2$R.prototype), _applyDecoratedDescriptor(_class2$R.prototype, "isUnderline", [_dec38$2, _dec39$2], Object.getOwnPropertyDescriptor(_class2$R.prototype, "isUnderline"), _class2$R.prototype), _applyDecoratedDescriptor(_class2$R.prototype, "underlineHeight", [_dec40$2, editable], Object.getOwnPropertyDescriptor(_class2$R.prototype, "underlineHeight"), _class2$R.prototype), _descriptor$H = _applyDecoratedDescriptor(_class2$R.prototype, "_string", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 'label';
              }
            }), _descriptor2$t = _applyDecoratedDescriptor(_class2$R.prototype, "_horizontalAlign", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return HorizontalTextAlignment.CENTER;
              }
            }), _descriptor3$j = _applyDecoratedDescriptor(_class2$R.prototype, "_verticalAlign", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return VerticalTextAlignment.CENTER;
              }
            }), _descriptor4$g = _applyDecoratedDescriptor(_class2$R.prototype, "_actualFontSize", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor5$c = _applyDecoratedDescriptor(_class2$R.prototype, "_fontSize", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 40;
              }
            }), _descriptor6$7 = _applyDecoratedDescriptor(_class2$R.prototype, "_fontFamily", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 'Arial';
              }
            }), _descriptor7$6 = _applyDecoratedDescriptor(_class2$R.prototype, "_lineHeight", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 40;
              }
            }), _descriptor8$6 = _applyDecoratedDescriptor(_class2$R.prototype, "_overflow", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return Overflow.NONE;
              }
            }), _descriptor9$5 = _applyDecoratedDescriptor(_class2$R.prototype, "_enableWrapText", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _descriptor10$5 = _applyDecoratedDescriptor(_class2$R.prototype, "_font", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor11$5 = _applyDecoratedDescriptor(_class2$R.prototype, "_isSystemFontUsed", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _descriptor12$4 = _applyDecoratedDescriptor(_class2$R.prototype, "_isItalic", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor13$4 = _applyDecoratedDescriptor(_class2$R.prototype, "_isBold", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor14$4 = _applyDecoratedDescriptor(_class2$R.prototype, "_isUnderline", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor15$4 = _applyDecoratedDescriptor(_class2$R.prototype, "_underlineHeight", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 2;
              }
            }), _descriptor16$4 = _applyDecoratedDescriptor(_class2$R.prototype, "_cacheMode", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return CacheMode.NONE;
              }
            })), _class2$R)) || _class$W) || _class$W) || _class$W) || _class$W));

            var LineCap;

            (function (LineCap) {
              LineCap[LineCap["BUTT"] = 0] = "BUTT";
              LineCap[LineCap["ROUND"] = 1] = "ROUND";
              LineCap[LineCap["SQUARE"] = 2] = "SQUARE";
            })(LineCap || (LineCap = {}));

            ccenum(LineCap);
            var LineJoin;

            (function (LineJoin) {
              LineJoin[LineJoin["BEVEL"] = 0] = "BEVEL";
              LineJoin[LineJoin["ROUND"] = 1] = "ROUND";
              LineJoin[LineJoin["MITER"] = 2] = "MITER";
            })(LineJoin || (LineJoin = {}));

            ccenum(LineJoin);
            var PointFlags;

            (function (PointFlags) {
              PointFlags[PointFlags["PT_CORNER"] = 1] = "PT_CORNER";
              PointFlags[PointFlags["PT_LEFT"] = 2] = "PT_LEFT";
              PointFlags[PointFlags["PT_BEVEL"] = 4] = "PT_BEVEL";
              PointFlags[PointFlags["PT_INNERBEVEL"] = 8] = "PT_INNERBEVEL";
            })(PointFlags || (PointFlags = {}));

            ccenum(PointFlags);

            var PI = Math.PI;
            var min$2 = Math.min;
            var max$3 = Math.max;
            var cos$1 = Math.cos;
            var sin = Math.sin;
            var abs$1 = Math.abs;
            var sign$1 = Math.sign;
            var KAPPA90 = 0.5522847493;
            function arc(ctx, cx, cy, r, startAngle, endAngle, counterclockwise) {
              counterclockwise = counterclockwise || false;
              var a = 0;
              var da = 0;
              var hda = 0;
              var kappa = 0;
              var dx = 0;
              var dy = 0;
              var x = 0;
              var y = 0;
              var tanx = 0;
              var tany = 0;
              var px = 0;
              var py = 0;
              var ptanx = 0;
              var ptany = 0;
              var i = 0;
              var ndivs = 0;
              da = endAngle - startAngle;

              if (counterclockwise) {
                if (abs$1(da) >= PI * 2) {
                  da = PI * 2;
                } else {
                  while (da < 0) {
                    da += PI * 2;
                  }
                }
              } else if (abs$1(da) >= PI * 2) {
                da = -PI * 2;
              } else {
                while (da > 0) {
                  da -= PI * 2;
                }
              }

              ndivs = max$3(1, min$2(abs$1(da) / (PI * 0.5) + 0.5, 5)) | 0;
              hda = da / ndivs / 2.0;
              kappa = abs$1(4.0 / 3.0 * (1 - cos$1(hda)) / sin(hda));

              if (!counterclockwise) {
                kappa = -kappa;
              }

              for (i = 0; i <= ndivs; i++) {
                a = startAngle + da * (i / ndivs);
                dx = cos$1(a);
                dy = sin(a);
                x = cx + dx * r;
                y = cy + dy * r;
                tanx = -dy * r * kappa;
                tany = dx * r * kappa;

                if (i === 0) {
                  ctx.moveTo(x, y);
                } else {
                  ctx.bezierCurveTo(px + ptanx, py + ptany, x - tanx, y - tany, x, y);
                }

                px = x;
                py = y;
                ptanx = tanx;
                ptany = tany;
              }
            }
            function ellipse(ctx, cx, cy, rx, ry) {
              ctx.moveTo(cx - rx, cy);
              ctx.bezierCurveTo(cx - rx, cy + ry * KAPPA90, cx - rx * KAPPA90, cy + ry, cx, cy + ry);
              ctx.bezierCurveTo(cx + rx * KAPPA90, cy + ry, cx + rx, cy + ry * KAPPA90, cx + rx, cy);
              ctx.bezierCurveTo(cx + rx, cy - ry * KAPPA90, cx + rx * KAPPA90, cy - ry, cx, cy - ry);
              ctx.bezierCurveTo(cx - rx * KAPPA90, cy - ry, cx - rx, cy - ry * KAPPA90, cx - rx, cy);
              ctx.close();
            }
            function roundRect(ctx, x, y, w, h, r) {
              if (r < 0.1) {
                ctx.rect(x, y, w, h);
              } else {
                var rx = min$2(r, abs$1(w) * 0.5) * sign$1(w);
                var ry = min$2(r, abs$1(h) * 0.5) * sign$1(h);
                ctx.moveTo(x, y + ry);
                ctx.lineTo(x, y + h - ry);
                ctx.bezierCurveTo(x, y + h - ry * (1 - KAPPA90), x + rx * (1 - KAPPA90), y + h, x + rx, y + h);
                ctx.lineTo(x + w - rx, y + h);
                ctx.bezierCurveTo(x + w - rx * (1 - KAPPA90), y + h, x + w, y + h - ry * (1 - KAPPA90), x + w, y + h - ry);
                ctx.lineTo(x + w, y + ry);
                ctx.bezierCurveTo(x + w, y + ry * (1 - KAPPA90), x + w - rx * (1 - KAPPA90), y, x + w - rx, y);
                ctx.lineTo(x + rx, y);
                ctx.bezierCurveTo(x + rx * (1 - KAPPA90), y, x, y + ry * (1 - KAPPA90), x, y + ry);
                ctx.close();
              }
            }
            function tesselateBezier(ctx, x1, y1, x2, y2, x3, y3, x4, y4, level, type) {
              var x12 = 0;
              var y12 = 0;
              var x23 = 0;
              var y23 = 0;
              var x34 = 0;
              var y34 = 0;
              var x123 = 0;
              var y123 = 0;
              var x234 = 0;
              var y234 = 0;
              var x1234 = 0;
              var y1234 = 0;
              var dx = 0;
              var dy = 0;
              var d2 = 0;
              var d3 = 0;

              if (level > 10) {
                return;
              }

              x12 = (x1 + x2) * 0.5;
              y12 = (y1 + y2) * 0.5;
              x23 = (x2 + x3) * 0.5;
              y23 = (y2 + y3) * 0.5;
              x34 = (x3 + x4) * 0.5;
              y34 = (y3 + y4) * 0.5;
              x123 = (x12 + x23) * 0.5;
              y123 = (y12 + y23) * 0.5;
              dx = x4 - x1;
              dy = y4 - y1;
              d2 = abs$1((x2 - x4) * dy - (y2 - y4) * dx);
              d3 = abs$1((x3 - x4) * dy - (y3 - y4) * dx);

              if ((d2 + d3) * (d2 + d3) < ctx.tessTol * (dx * dx + dy * dy)) {
                ctx.addPoint(x4, y4, type === 0 ? type | PointFlags.PT_BEVEL : type);
                return;
              }

              x234 = (x23 + x34) * 0.5;
              y234 = (y23 + y34) * 0.5;
              x1234 = (x123 + x234) * 0.5;
              y1234 = (y123 + y234) * 0.5;
              tesselateBezier(ctx, x1, y1, x12, y12, x123, y123, x1234, y1234, level + 1, 0);
              tesselateBezier(ctx, x1234, y1234, x234, y234, x34, y34, x4, y4, level + 1, type);
            }

            var Point = function (_Vec) {
              _inheritsLoose(Point, _Vec);

              function Point(x, y) {
                var _this;

                _this = _Vec.call(this, x, y) || this;
                _this.dx = 0;
                _this.dy = 0;
                _this.dmx = 0;
                _this.dmy = 0;
                _this.flags = 0;
                _this.len = 0;

                _this.reset();

                return _this;
              }

              var _proto = Point.prototype;

              _proto.reset = function reset() {
                this.dx = 0;
                this.dy = 0;
                this.dmx = 0;
                this.dmy = 0;
                this.flags = 0;
                this.len = 0;
              };

              return Point;
            }(Vec2);
            var Path = function () {
              function Path() {
                this.closed = false;
                this.bevel = 0;
                this.complex = true;
                this.points = [];
                this.reset();
              }

              var _proto2 = Path.prototype;

              _proto2.reset = function reset() {
                this.closed = false;
                this.bevel = 0;
                this.complex = true;

                if (this.points) {
                  this.points.length = 0;
                } else {
                  this.points = [];
                }
              };

              return Path;
            }();
            var Impl = function () {
              function Impl() {
                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.WHITE.clone();
                this.lineCap = LineCap.BUTT;
                this.strokeColor = Color.BLACK.clone();
                this.lineJoin = LineJoin.MITER;
                this.lineWidth = 0;
                this.pointsOffset = 0;
                this._commandX = 0;
                this._commandY = 0;
                this._points = [];
                this._renderDataList = [];
                this._curPath = null;
              }

              var _proto3 = Impl.prototype;

              _proto3.moveTo = function moveTo(x, y) {
                if (this.updatePathOffset) {
                  this.pathOffset = this.pathLength;
                  this.updatePathOffset = false;
                }

                this._addPath();

                this.addPoint(x, y, PointFlags.PT_CORNER);
                this._commandX = x;
                this._commandY = y;
              };

              _proto3.lineTo = function lineTo(x, y) {
                this.addPoint(x, y, PointFlags.PT_CORNER);
                this._commandX = x;
                this._commandY = y;
              };

              _proto3.bezierCurveTo = function bezierCurveTo(c1x, c1y, c2x, c2y, x, y) {
                var path = this._curPath;
                var last = path.points[path.points.length - 1];

                if (!last) {
                  return;
                }

                if (last.x === c1x && last.y === c1y && c2x === x && c2y === y) {
                  this.lineTo(x, y);
                  return;
                }

                tesselateBezier(this, last.x, last.y, c1x, c1y, c2x, c2y, x, y, 0, PointFlags.PT_CORNER);
                this._commandX = x;
                this._commandY = y;
              };

              _proto3.quadraticCurveTo = function quadraticCurveTo(cx, cy, x, y) {
                var x0 = this._commandX;
                var y0 = this._commandY;
                this.bezierCurveTo(x0 + 2.0 / 3.0 * (cx - x0), y0 + 2.0 / 3.0 * (cy - y0), x + 2.0 / 3.0 * (cx - x), y + 2.0 / 3.0 * (cy - y), x, y);
              };

              _proto3.arc = function arc$1(cx, cy, r, startAngle, endAngle, counterclockwise) {
                arc(this, cx, cy, r, startAngle, endAngle, counterclockwise);
              };

              _proto3.ellipse = function ellipse$1(cx, cy, rx, ry) {
                ellipse(this, cx, cy, rx, ry);

                this._curPath.complex = false;
              };

              _proto3.circle = function circle(cx, cy, r) {
                ellipse(this, cx, cy, r, r);

                this._curPath.complex = false;
              };

              _proto3.rect = function rect(x, y, w, h) {
                this.moveTo(x, y);
                this.lineTo(x + w, y);
                this.lineTo(x + w, y + h);
                this.lineTo(x, y + h);
                this.close();
                this._curPath.complex = false;
              };

              _proto3.roundRect = function roundRect$1(x, y, w, h, r) {
                roundRect(this, x, y, w, h, r);

                this._curPath.complex = false;
              };

              _proto3.clear = function clear() {
                this.pathLength = 0;
                this.pathOffset = 0;
                this.pointsOffset = 0;
                this.dataOffset = 0;
                this._curPath = null;
                this.paths.length = 0;
                this._points.length = 0;
                var dataList = this._renderDataList;

                for (var i = 0, l = dataList.length; i < l; i++) {
                  var data = dataList[i];

                  if (!data) {
                    continue;
                  }

                  MeshRenderData.remove(data);
                }

                this._renderDataList.length = 0;
              };

              _proto3.close = function close() {
                this._curPath.closed = true;
              };

              _proto3.requestRenderData = function requestRenderData() {
                var renderData = MeshRenderData.add();

                this._renderDataList.push(renderData);

                return renderData;
              };

              _proto3.getRenderDataList = function getRenderDataList() {
                if (this._renderDataList.length === 0) {
                  this.requestRenderData();
                }

                return this._renderDataList;
              };

              _proto3.addPoint = function addPoint(x, y, flags) {
                var path = this._curPath;

                if (!path) {
                  return;
                }

                var points = this._points;
                var pathPoints = path.points;
                var offset = this.pointsOffset++;
                var pt = points[offset];

                if (!pt) {
                  pt = new Point(x, y);
                  points.push(pt);
                } else {
                  pt.x = x;
                  pt.y = y;
                }

                pt.flags = flags;
                pathPoints.push(pt);
              };

              _proto3._addPath = function _addPath() {
                var offset = this.pathLength;
                var path = this.paths[offset];

                if (!path) {
                  path = new Path();
                  this.paths.push(path);
                } else {
                  path.reset();
                }

                this.pathLength++;
                this._curPath = path;
                return path;
              };

              return Impl;
            }();

            var vfmt = [new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F)];
            var vfmtPosColor = [new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), new Attribute(AttributeName.ATTR_COLOR, Format.RGBA32F)];
            var vfmtPosUvColor = [new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), new Attribute(AttributeName.ATTR_TEX_COORD, Format.RG32F), new Attribute(AttributeName.ATTR_COLOR, Format.RGBA32F)];
            var vfmtPosUvTwoColor = [new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), new Attribute(AttributeName.ATTR_TEX_COORD, Format.RG32F), new Attribute(AttributeName.ATTR_COLOR, Format.RGBA32F), new Attribute(AttributeName.ATTR_COLOR2, Format.RGBA32F)];
            function getComponentPerVertex(attrs) {
              var count = 0;

              for (var i = 0; i < attrs.length; i++) {
                var attr = attrs[i];
                var info = FormatInfos[attr.format];
                count += info.count;
              }

              return count;
            }
            function getAttributeStride(attrs) {
              var count = 0;

              for (var i = 0; i < attrs.length; i++) {
                var attr = attrs[i];
                var info = FormatInfos[attr.format];
                count += info.size;
              }

              return count;
            }
            legacyCC.internal.vfmtPosUvColor = vfmtPosUvColor;
            legacyCC.internal.vfmtPosUvTwoColor = vfmtPosUvTwoColor;

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

            var _dec$W, _dec2$w, _dec3$o, _dec4$j, _dec5$f, _dec6$a, _dec7$8, _dec8$8, _dec9$7, _dec10$6, _dec11$5, _dec12$5, _class$X, _class2$S, _descriptor$I, _descriptor2$u, _descriptor3$k, _descriptor4$h, _descriptor5$d, _descriptor6$8, _class3$l, _temp$T;
            var attributes = vfmtPosColor.concat([new Attribute('a_dist', Format.R32F)]);
            var componentPerVertex = getComponentPerVertex(attributes);
            var stride = getAttributeStride(attributes);
            var Graphics = function (v) { return exports({ Graphics: v, GraphicsComponent: v }), v; }((_dec$W = ccclass('cc.Graphics'), _dec2$w = help(), _dec3$o = executionOrder(110), _dec4$j = menu(), _dec5$f = type(LineJoin), _dec6$a = tooltip(), _dec7$8 = type(LineCap), _dec8$8 = tooltip(), _dec9$7 = tooltip(), _dec10$6 = tooltip(), _dec11$5 = tooltip(), _dec12$5 = visible(), _dec$W(_class$X = _dec2$w(_class$X = _dec3$o(_class$X = _dec4$j(_class$X = (_class2$S = (_temp$T = _class3$l = function (_Renderable2D) {
              _inheritsLoose(Graphics, _Renderable2D);

              function Graphics() {
                var _this;

                _this = _Renderable2D.call(this) || this;
                _this.impl = null;
                _this.model = null;

                _initializerDefineProperty(_this, "_lineWidth", _descriptor$I, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_strokeColor", _descriptor2$u, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_lineJoin", _descriptor3$k, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_lineCap", _descriptor4$h, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_fillColor", _descriptor5$d, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_miterLimit", _descriptor6$8, _assertThisInitialized(_this));

                _this._isDrawing = false;
                _this._isNeedUploadData = true;
                _this._graphicsUseSubMeshes = [];
                _this._instanceMaterialType = InstanceMaterialType.ADD_COLOR;
                _this.impl = new Impl();
                return _this;
              }

              var _proto = Graphics.prototype;

              _proto.onRestore = function onRestore() {
                if (!this.impl) {
                  this._flushAssembler();
                }
              };

              _proto.onLoad = function onLoad() {
                this.model = director.root.createModel(Model);
                this.model.node = this.model.transform = this.node;

                this._flushAssembler();
              };

              _proto.onEnable = function onEnable() {
                _Renderable2D.prototype.onEnable.call(this);

                this._updateMtlForGraphics();
              };

              _proto.onDisable = function onDisable() {
                _Renderable2D.prototype.onDisable.call(this);
              };

              _proto.onDestroy = function onDestroy() {
                _Renderable2D.prototype.onDestroy.call(this);

                this._sceneGetter = null;

                if (this.model) {
                  director.root.destroyModel(this.model);
                  this.model = null;
                }

                var subMeshLength = this._graphicsUseSubMeshes.length;

                if (subMeshLength > 0) {
                  for (var i = 0; i < subMeshLength; ++i) {
                    this._graphicsUseSubMeshes[i].destroy();
                  }

                  this._graphicsUseSubMeshes.length = 0;
                }

                if (!this.impl) {
                  return;
                }

                this._isDrawing = false;
                this.impl.clear();
                this.impl = null;
              };

              _proto.moveTo = function moveTo(x, y) {
                if (!this.impl) {
                  return;
                }

                this.impl.moveTo(x, y);
              };

              _proto.lineTo = function lineTo(x, y) {
                if (!this.impl) {
                  return;
                }

                this.impl.lineTo(x, y);
              };

              _proto.bezierCurveTo = function bezierCurveTo(c1x, c1y, c2x, c2y, x, y) {
                if (!this.impl) {
                  return;
                }

                this.impl.bezierCurveTo(c1x, c1y, c2x, c2y, x, y);
              };

              _proto.quadraticCurveTo = function quadraticCurveTo(cx, cy, x, y) {
                if (!this.impl) {
                  return;
                }

                this.impl.quadraticCurveTo(cx, cy, x, y);
              };

              _proto.arc = function arc(cx, cy, r, startAngle, endAngle, counterclockwise) {
                if (!this.impl) {
                  return;
                }

                this.impl.arc(cx, cy, r, startAngle, endAngle, counterclockwise);
              };

              _proto.ellipse = function ellipse(cx, cy, rx, ry) {
                if (!this.impl) {
                  return;
                }

                this.impl.ellipse(cx, cy, rx, ry);
              };

              _proto.circle = function circle(cx, cy, r) {
                if (!this.impl) {
                  return;
                }

                this.impl.circle(cx, cy, r);
              };

              _proto.rect = function rect(x, y, w, h) {
                if (!this.impl) {
                  return;
                }

                this.impl.rect(x, y, w, h);
              };

              _proto.roundRect = function roundRect(x, y, w, h, r) {
                if (!this.impl) {
                  return;
                }

                this.impl.roundRect(x, y, w, h, r);
              };

              _proto.fillRect = function fillRect(x, y, w, h) {
                this.rect(x, y, w, h);
                this.fill();
              };

              _proto.clear = function clear() {
                if (!this.impl) {
                  return;
                }

                this.impl.clear();
                this._isDrawing = false;

                if (this.model) {
                  for (var i = 0; i < this.model.subModels.length; i++) {
                    var subModel = this.model.subModels[i];
                    subModel.inputAssembler.indexCount = 0;
                  }
                }

                this.markForUpdateRenderData();
              };

              _proto.close = function close() {
                if (!this.impl) {
                  return;
                }

                this.impl.close();
              };

              _proto.stroke = function stroke() {
                if (!this._assembler) {
                  this._flushAssembler();
                }

                this._isDrawing = true;
                this._isNeedUploadData = true;

                this._assembler.stroke(this);
              };

              _proto.fill = function fill() {
                if (!this._assembler) {
                  this._flushAssembler();
                }

                this._isDrawing = true;
                this._isNeedUploadData = true;

                this._assembler.fill(this);
              };

              _proto._updateMtlForGraphics = function _updateMtlForGraphics() {
                var mat;

                if (this._customMaterial) {
                  mat = this.getMaterialInstance(0);
                } else {
                  mat = builtinResMgr.get('ui-graphics-material');
                  this.setMaterial(mat, 0);
                  mat = this.getMaterialInstance(0);
                  mat.recompileShaders({
                    USE_LOCAL: true
                  });
                }
              };

              _proto.activeSubModel = function activeSubModel(idx) {
                if (!this.model) {
                  warnID(4500, this.node.name);
                  return;
                }

                if (this.model.subModels.length <= idx) {
                  var gfxDevice = legacyCC.director.root.device;
                  var vertexBuffer = gfxDevice.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, 65535 * stride, stride));
                  var indexBuffer = gfxDevice.createBuffer(new BufferInfo(BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, 65535 * Uint16Array.BYTES_PER_ELEMENT * 2, Uint16Array.BYTES_PER_ELEMENT));
                  var renderMesh = new RenderingSubMesh([vertexBuffer], attributes, PrimitiveMode.TRIANGLE_LIST, indexBuffer);
                  renderMesh.subMeshIdx = 0;
                  this.model.initSubModel(idx, renderMesh, this.getMaterialInstance(0));

                  this._graphicsUseSubMeshes.push(renderMesh);
                }
              };

              _proto._uploadData = function _uploadData(render) {
                var impl = this.impl;

                if (!impl) {
                  return;
                }

                var renderDataList = impl && impl.getRenderDataList();

                if (renderDataList.length <= 0 || !this.model) {
                  return;
                }

                var subModelList = this.model.subModels;

                for (var i = 0; i < renderDataList.length; i++) {
                  var renderData = renderDataList[i];
                  var ia = subModelList[i].inputAssembler;

                  if (renderData.lastFilledVertex === renderData.vertexStart) {
                    continue;
                  }

                  var vb = new Float32Array(renderData.vData.buffer, 0, renderData.vertexStart * componentPerVertex);
                  ia.vertexBuffers[0].update(vb);
                  ia.vertexCount = renderData.vertexStart;
                  var ib = new Uint16Array(renderData.iData.buffer, 0, renderData.indicesStart);
                  ia.indexBuffer.update(ib);
                  ia.indexCount = renderData.indicesStart;
                  renderData.lastFilledVertex = renderData.vertexStart;
                  renderData.lastFilledIndices = renderData.indicesStart;
                }

                render.removeUploadBuffersFunc(this);
                this._isNeedUploadData = false;
              };

              _proto._render = function _render(render) {
                if (this._isNeedUploadData) {
                  if (this.impl) {
                    var renderDataList = this.impl.getRenderDataList();
                    var len = this.model.subModels.length;

                    if (renderDataList.length > len) {
                      for (var i = len; i < renderDataList.length; i++) {
                        this.activeSubModel(i);
                      }
                    }
                  }

                  render.addUploadBuffersFunc(this, this._uploadData);
                }

                render.commitModel(this, this.model, this.getMaterialInstance(0));
              };

              _proto._flushAssembler = function _flushAssembler() {
                var assembler = Graphics.Assembler.getAssembler(this);

                if (this._assembler !== assembler) {
                  this._assembler = assembler;
                }
              };

              _proto._canRender = function _canRender() {
                if (!_Renderable2D.prototype._canRender.call(this)) {
                  return false;
                }

                return !!this.model && this._isDrawing;
              };

              _createClass(Graphics, [{
                key: "lineWidth",
                get: function get() {
                  return this._lineWidth;
                },
                set: function set(value) {
                  this._lineWidth = value;

                  if (!this.impl) {
                    return;
                  }

                  this.impl.lineWidth = value;
                }
              }, {
                key: "lineJoin",
                get: function get() {
                  return this._lineJoin;
                },
                set: function set(value) {
                  this._lineJoin = value;

                  if (!this.impl) {
                    return;
                  }

                  this.impl.lineJoin = value;
                }
              }, {
                key: "lineCap",
                get: function get() {
                  return this._lineCap;
                },
                set: function set(value) {
                  this._lineCap = value;

                  if (!this.impl) {
                    return;
                  }

                  this.impl.lineCap = value;
                }
              }, {
                key: "strokeColor",
                get: function get() {
                  return this._strokeColor;
                },
                set: function set(value) {
                  if (!this.impl) {
                    return;
                  }

                  this._strokeColor.set(value);

                  this.impl.strokeColor = this._strokeColor;
                }
              }, {
                key: "fillColor",
                get: function get() {
                  return this._fillColor;
                },
                set: function set(value) {
                  if (!this.impl) {
                    return;
                  }

                  this._fillColor.set(value);

                  this.impl.fillColor = this._fillColor;
                }
              }, {
                key: "miterLimit",
                get: function get() {
                  return this._miterLimit;
                },
                set: function set(value) {
                  this._miterLimit = value;
                }
              }, {
                key: "color",
                get: function get() {
                  return this._color;
                },
                set: function set(value) {
                  if (this._color === value) {
                    return;
                  }

                  this._color.set(value);
                }
              }, {
                key: "srcBlendFactor",
                get: function get() {
                  return this._srcBlendFactor;
                },
                set: function set(value) {}
              }, {
                key: "dstBlendFactor",
                get: function get() {
                  return this._dstBlendFactor;
                },
                set: function set(value) {}
              }]);

              return Graphics;
            }(Renderable2D), _class3$l.LineJoin = LineJoin, _class3$l.LineCap = LineCap, _temp$T), (_applyDecoratedDescriptor(_class2$S.prototype, "lineWidth", [editable], Object.getOwnPropertyDescriptor(_class2$S.prototype, "lineWidth"), _class2$S.prototype), _applyDecoratedDescriptor(_class2$S.prototype, "lineJoin", [_dec5$f, _dec6$a], Object.getOwnPropertyDescriptor(_class2$S.prototype, "lineJoin"), _class2$S.prototype), _applyDecoratedDescriptor(_class2$S.prototype, "lineCap", [_dec7$8, _dec8$8], Object.getOwnPropertyDescriptor(_class2$S.prototype, "lineCap"), _class2$S.prototype), _applyDecoratedDescriptor(_class2$S.prototype, "strokeColor", [_dec9$7], Object.getOwnPropertyDescriptor(_class2$S.prototype, "strokeColor"), _class2$S.prototype), _applyDecoratedDescriptor(_class2$S.prototype, "fillColor", [_dec10$6], Object.getOwnPropertyDescriptor(_class2$S.prototype, "fillColor"), _class2$S.prototype), _applyDecoratedDescriptor(_class2$S.prototype, "miterLimit", [_dec11$5], Object.getOwnPropertyDescriptor(_class2$S.prototype, "miterLimit"), _class2$S.prototype), _applyDecoratedDescriptor(_class2$S.prototype, "color", [override, _dec12$5], Object.getOwnPropertyDescriptor(_class2$S.prototype, "color"), _class2$S.prototype), _descriptor$I = _applyDecoratedDescriptor(_class2$S.prototype, "_lineWidth", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1;
              }
            }), _descriptor2$u = _applyDecoratedDescriptor(_class2$S.prototype, "_strokeColor", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return Color.BLACK.clone();
              }
            }), _descriptor3$k = _applyDecoratedDescriptor(_class2$S.prototype, "_lineJoin", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return LineJoin.MITER;
              }
            }), _descriptor4$h = _applyDecoratedDescriptor(_class2$S.prototype, "_lineCap", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return LineCap.BUTT;
              }
            }), _descriptor5$d = _applyDecoratedDescriptor(_class2$S.prototype, "_fillColor", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return Color.WHITE.clone();
              }
            }), _descriptor6$8 = _applyDecoratedDescriptor(_class2$S.prototype, "_miterLimit", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 10;
              }
            })), _class2$S)) || _class$X) || _class$X) || _class$X) || _class$X));

            var _dec$X, _dec2$x, _dec3$p, _dec4$k, _dec5$g, _dec6$b, _dec7$9, _dec8$9, _dec9$8, _dec10$7, _dec11$6, _dec12$6, _dec13$5, _dec14$5, _dec15$5, _dec16$5, _class$Y, _class2$T, _descriptor$J, _descriptor2$v, _descriptor3$l, _descriptor4$i, _descriptor5$e, _class3$m, _temp$U;

            var _worldMatrix$2 = new Mat4();

            var _vec2_temp = new Vec2();

            var _mat4_temp$1 = new Mat4();

            var _circlePoints = [];

            function _calculateCircle(center, radius, segments) {
              _circlePoints.length = 0;
              var anglePerStep = Math.PI * 2 / segments;

              for (var step = 0; step < segments; ++step) {
                _circlePoints.push(new Vec3(radius.x * Math.cos(anglePerStep * step) + center.x, radius.y * Math.sin(anglePerStep * step) + center.y, 0));
              }

              return _circlePoints;
            }

            var MaskType;

            (function (MaskType) {
              MaskType[MaskType["RECT"] = 0] = "RECT";
              MaskType[MaskType["ELLIPSE"] = 1] = "ELLIPSE";
              MaskType[MaskType["GRAPHICS_STENCIL"] = 2] = "GRAPHICS_STENCIL";
              MaskType[MaskType["IMAGE_STENCIL"] = 3] = "IMAGE_STENCIL";
            })(MaskType || (MaskType = {}));

            ccenum(MaskType);
            var SEGMENTS_MIN = 3;
            var SEGMENTS_MAX = 10000;
            var Mask = function (v) { return exports({ Mask: v, MaskComponent: v }), v; }((_dec$X = ccclass('cc.Mask'), _dec2$x = help(), _dec3$p = executionOrder(110), _dec4$k = menu(), _dec5$g = type(MaskType), _dec6$b = displayOrder(), _dec7$9 = tooltip(), _dec8$9 = displayOrder(), _dec9$8 = tooltip(), _dec10$7 = visible(), _dec11$6 = type(SpriteFrame), _dec12$6 = visible(), _dec13$5 = visible(), _dec14$5 = range(), _dec15$5 = visible(), _dec16$5 = visible(), _dec$X(_class$Y = _dec2$x(_class$Y = _dec3$p(_class$Y = _dec4$k(_class$Y = (_class2$T = (_temp$U = _class3$m = function (_Renderable2D) {
              _inheritsLoose(Mask, _Renderable2D);

              function Mask() {
                var _this;

                _this = _Renderable2D.call(this) || this;
                _this._clearStencilMtl = null;
                _this._clearModel = null;

                _initializerDefineProperty(_this, "_type", _descriptor$J, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_inverted", _descriptor2$v, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_segments", _descriptor3$l, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_spriteFrame", _descriptor4$i, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_alphaThreshold", _descriptor5$e, _assertThisInitialized(_this));

                _this._graphics = null;
                _this._clearModelMesh = null;
                _this._instanceMaterialType = InstanceMaterialType.ADD_COLOR;
                return _this;
              }

              var _proto = Mask.prototype;

              _proto.onLoad = function onLoad() {
                this._createClearModel();

                this._createGraphics();

                if (this._graphics) {
                  this._graphics.onLoad();
                }
              };

              _proto.onEnable = function onEnable() {
                _Renderable2D.prototype.onEnable.call(this);

                this._updateGraphics();
              };

              _proto.onRestore = function onRestore() {
                this._createGraphics();

                _Renderable2D.prototype.updateMaterial.call(this);

                this._updateGraphics();

                this._renderFlag = this._canRender();
              };

              _proto.onDisable = function onDisable() {
                _Renderable2D.prototype.onDisable.call(this);

                this._disableGraphics();
              };

              _proto.onDestroy = function onDestroy() {
                _Renderable2D.prototype.onDestroy.call(this);

                if (this._clearModel && this._clearModelMesh) {
                  director.root.destroyModel(this._clearModel);

                  this._clearModelMesh.destroy();
                }

                if (this._clearStencilMtl) {
                  this._clearStencilMtl.destroy();
                }

                this._removeGraphics();
              };

              _proto.isHit = function isHit(cameraPt) {
                var uiTrans = this.node._uiProps.uiTransformComp;
                var size = uiTrans.contentSize;
                var w = size.width;
                var h = size.height;
                var testPt = _vec2_temp;
                this.node.getWorldMatrix(_worldMatrix$2);
                Mat4.invert(_mat4_temp$1, _worldMatrix$2);
                Vec2.transformMat4(testPt, cameraPt, _mat4_temp$1);
                var ap = uiTrans.anchorPoint;
                testPt.x += ap.x * w;
                testPt.y += ap.y * h;
                var result = false;

                if (this.type === MaskType.RECT || this.type === MaskType.GRAPHICS_STENCIL) {
                  result = testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h;
                } else if (this.type === MaskType.ELLIPSE) {
                  var rx = w / 2;
                  var ry = h / 2;
                  var px = testPt.x - 0.5 * w;
                  var py = testPt.y - 0.5 * h;
                  result = px * px / (rx * rx) + py * py / (ry * ry) < 1;
                }

                if (this._inverted) {
                  result = !result;
                }

                return result;
              };

              _proto._render = function _render(render) {
                render.commitComp(this, null, this._assembler, null);
              };

              _proto._postRender = function _postRender(render) {
                if (!this._postAssembler) {
                  return;
                }

                render.commitComp(this, null, this._postAssembler, null);
              };

              _proto._nodeStateChange = function _nodeStateChange(type) {
                _Renderable2D.prototype._nodeStateChange.call(this, type);

                this._updateGraphics();
              };

              _proto._canRender = function _canRender() {
                if (!_Renderable2D.prototype._canRender.call(this)) {
                  return false;
                }

                return this._graphics !== null && (this._type !== MaskType.IMAGE_STENCIL || this._spriteFrame !== null);
              };

              _proto._flushAssembler = function _flushAssembler() {
                var assembler = Mask.Assembler.getAssembler(this);
                var posAssembler = Mask.PostAssembler.getAssembler(this);

                if (this._assembler !== assembler) {
                  this.destroyRenderData();
                  this._assembler = assembler;
                }

                if (this._postAssembler !== posAssembler) {
                  this._postAssembler = posAssembler;
                }

                this._useRenderData();
              };

              _proto._createGraphics = function _createGraphics() {
                if (!this._graphics) {
                  var graphics = this._graphics = new Graphics();
                  graphics._objFlags |= CCObject.Flags.IsOnLoadCalled;
                  graphics.node = this.node;
                  graphics.node.getWorldMatrix();
                  graphics.lineWidth = 0;
                  var color = Color.WHITE.clone();
                  color.a = 0;
                  graphics.fillColor = color;
                }

                this._updateMaterial();
              };

              _proto._updateGraphics = function _updateGraphics() {
                if (!this._graphics || this._type !== MaskType.RECT && this._type !== MaskType.ELLIPSE) {
                  return;
                }

                var uiTrans = this.node._uiProps.uiTransformComp;
                var graphics = this._graphics;
                graphics.clear();
                var size = uiTrans.contentSize;
                var width = size.width;
                var height = size.height;
                var ap = uiTrans.anchorPoint;
                var x = -width * ap.x;
                var y = -height * ap.y;

                if (this._type === MaskType.RECT) {
                  graphics.rect(x, y, width, height);
                } else if (this._type === MaskType.ELLIPSE) {
                  var center = new Vec3(x + width / 2, y + height / 2, 0);
                  var radius = new Vec3(width / 2, height / 2, 0);

                  var points = _calculateCircle(center, radius, this._segments);

                  for (var i = 0; i < points.length; ++i) {
                    var point = points[i];

                    if (i === 0) {
                      graphics.moveTo(point.x, point.y);
                    } else {
                      graphics.lineTo(point.x, point.y);
                    }
                  }

                  graphics.close();
                }

                graphics.fill();
              };

              _proto._createClearModel = function _createClearModel() {
                if (!this._clearModel) {
                  var mtl = builtinResMgr.get('default-clear-stencil');
                  this._clearStencilMtl = new MaterialInstance({
                    parent: mtl,
                    owner: this,
                    subModelIdx: 0
                  });
                  this._clearModel = director.root.createModel(Model);
                  this._clearModel.node = this._clearModel.transform = this.node;
                  var stride = getAttributeStride(vfmt);
                  var gfxDevice = legacyCC.director.root.device;
                  var vertexBuffer = gfxDevice.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, 4 * stride, stride));
                  var vb = new Float32Array([-1, -1, 0, 1, -1, 0, -1, 1, 0, 1, 1, 0]);
                  vertexBuffer.update(vb);
                  var indexBuffer = gfxDevice.createBuffer(new BufferInfo(BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, 6 * Uint16Array.BYTES_PER_ELEMENT, Uint16Array.BYTES_PER_ELEMENT));
                  var ib = new Uint16Array([0, 1, 2, 2, 1, 3]);
                  indexBuffer.update(ib);
                  this._clearModelMesh = new RenderingSubMesh([vertexBuffer], vfmt, PrimitiveMode.TRIANGLE_LIST, indexBuffer);
                  this._clearModelMesh.subMeshIdx = 0;

                  this._clearModel.initSubModel(0, this._clearModelMesh, this._clearStencilMtl);
                }
              };

              _proto._updateMaterial = function _updateMaterial() {
                if (this._graphics) {
                  var target = this._graphics;
                  target.stencilStage = Stage.DISABLED;
                  var mat;

                  if (this._type === MaskType.IMAGE_STENCIL) {
                    mat = builtinResMgr.get('ui-alpha-test-material');
                    target.setMaterial(mat, 0);
                    mat = target.getMaterialInstance(0);
                    mat.setProperty('alphaThreshold', this._alphaThreshold);
                  } else {
                    mat = builtinResMgr.get('ui-graphics-material');
                    target.setMaterial(mat, 0);
                    target.getMaterialInstance(0);
                  }
                }
              };

              _proto._disableGraphics = function _disableGraphics() {
                if (this._graphics) {
                  this._graphics.onDisable();
                }
              };

              _proto._removeGraphics = function _removeGraphics() {
                if (this._graphics) {
                  this._graphics.destroy();

                  this._graphics._destroyImmediate();

                  this._graphics = null;
                }
              };

              _proto._useRenderData = function _useRenderData() {
                if (this._type === MaskType.IMAGE_STENCIL && !this._renderData) {
                  if (this._assembler && this._assembler.createData) {
                    this._renderData = this._assembler.createData(this);
                    this.markForUpdateRenderData();
                  }
                }
              };

              _createClass(Mask, [{
                key: "type",
                get: function get() {
                  return this._type;
                },
                set: function set(value) {
                  if (this._type === value) {
                    return;
                  }

                  this._type = value;
                  this.markForUpdateRenderData(false);

                  this._updateMaterial();

                  if (this._type !== MaskType.IMAGE_STENCIL) {
                    this._spriteFrame = null;

                    this._updateGraphics();

                    if (this._renderData) {
                      this.destroyRenderData();
                      this._renderData = null;
                    }
                  } else {
                    this._useRenderData();

                    if (this._graphics) {
                      this._graphics.clear();
                    }
                  }
                }
              }, {
                key: "inverted",
                get: function get() {
                  return this._inverted;
                },
                set: function set(value) {
                  if (legacyCC.game.renderType === Game.RENDER_TYPE_CANVAS) {
                    warnID(4202);
                    return;
                  }

                  this._inverted = value;
                  this.stencilStage = Stage.DISABLED;

                  if (this._graphics) {
                    this._graphics.stencilStage = Stage.DISABLED;
                  }
                }
              }, {
                key: "segments",
                get: function get() {
                  return this._segments;
                },
                set: function set(value) {
                  if (this._segments === value) {
                    return;
                  }

                  this._segments = clamp(value, SEGMENTS_MIN, SEGMENTS_MAX);

                  this._updateGraphics();
                }
              }, {
                key: "spriteFrame",
                get: function get() {
                  return this._spriteFrame;
                },
                set: function set(value) {
                  if (this._spriteFrame === value) {
                    return;
                  }

                  var lastSp = this._spriteFrame;
                  this._spriteFrame = value;

                  if (this._type === MaskType.IMAGE_STENCIL) {
                    if (!lastSp && value) {
                      this.markForUpdateRenderData();
                    }
                  }
                }
              }, {
                key: "alphaThreshold",
                get: function get() {
                  return this._alphaThreshold;
                },
                set: function set(value) {
                  if (this._alphaThreshold === value) {
                    return;
                  }

                  this._alphaThreshold = value;

                  if (this.type === MaskType.IMAGE_STENCIL && this._graphics) {
                    var mat = this._graphics.getMaterialInstance(0);

                    mat.setProperty('alphaThreshold', this._alphaThreshold);
                  }
                }
              }, {
                key: "graphics",
                get: function get() {
                  return this._graphics;
                }
              }, {
                key: "dstBlendFactor",
                get: function get() {
                  return this._dstBlendFactor;
                },
                set: function set(value) {
                  if (this._dstBlendFactor === value) {
                    return;
                  }

                  this._dstBlendFactor = value;

                  this._updateBlendFunc();
                }
              }, {
                key: "srcBlendFactor",
                get: function get() {
                  return this._srcBlendFactor;
                },
                set: function set(value) {
                  if (this._srcBlendFactor === value) {
                    return;
                  }

                  this._srcBlendFactor = value;

                  this._updateBlendFunc();
                }
              }, {
                key: "color",
                get: function get() {
                  return this._color;
                },
                set: function set(value) {
                  if (this._color === value) {
                    return;
                  }

                  this._color.set(value);

                  this.markForUpdateRenderData();
                }
              }, {
                key: "customMaterial",
                get: function get() {
                  return this._customMaterial;
                },
                set: function set(val) {}
              }]);

              return Mask;
            }(Renderable2D), _class3$m.Type = MaskType, _temp$U), (_applyDecoratedDescriptor(_class2$T.prototype, "type", [_dec5$g, _dec6$b, _dec7$9], Object.getOwnPropertyDescriptor(_class2$T.prototype, "type"), _class2$T.prototype), _applyDecoratedDescriptor(_class2$T.prototype, "inverted", [_dec8$9, _dec9$8], Object.getOwnPropertyDescriptor(_class2$T.prototype, "inverted"), _class2$T.prototype), _applyDecoratedDescriptor(_class2$T.prototype, "segments", [_dec10$7], Object.getOwnPropertyDescriptor(_class2$T.prototype, "segments"), _class2$T.prototype), _applyDecoratedDescriptor(_class2$T.prototype, "spriteFrame", [_dec11$6, _dec12$6], Object.getOwnPropertyDescriptor(_class2$T.prototype, "spriteFrame"), _class2$T.prototype), _applyDecoratedDescriptor(_class2$T.prototype, "alphaThreshold", [_dec13$5, _dec14$5, slide], Object.getOwnPropertyDescriptor(_class2$T.prototype, "alphaThreshold"), _class2$T.prototype), _applyDecoratedDescriptor(_class2$T.prototype, "color", [override, _dec15$5], Object.getOwnPropertyDescriptor(_class2$T.prototype, "color"), _class2$T.prototype), _applyDecoratedDescriptor(_class2$T.prototype, "customMaterial", [override, _dec16$5], Object.getOwnPropertyDescriptor(_class2$T.prototype, "customMaterial"), _class2$T.prototype), _descriptor$J = _applyDecoratedDescriptor(_class2$T.prototype, "_type", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return MaskType.RECT;
              }
            }), _descriptor2$v = _applyDecoratedDescriptor(_class2$T.prototype, "_inverted", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor3$l = _applyDecoratedDescriptor(_class2$T.prototype, "_segments", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 64;
              }
            }), _descriptor4$i = _applyDecoratedDescriptor(_class2$T.prototype, "_spriteFrame", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor5$e = _applyDecoratedDescriptor(_class2$T.prototype, "_alphaThreshold", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0.1;
              }
            })), _class2$T)) || _class$Y) || _class$Y) || _class$Y) || _class$Y));
            NodeEventProcessor._comp = Mask;
            legacyCC.Mask = Mask;

            var eventRegx = /^(click)(\s)*=|(param)(\s)*=/;
            var imageAttrReg = /(\s)*src(\s)*=|(\s)*height(\s)*=|(\s)*width(\s)*=|(\s)*align(\s)*=|(\s)*offset(\s)*=|(\s)*click(\s)*=|(\s)*param(\s)*=/;
            var HtmlTextParser = exports('HtmlTextParser', function () {
              function HtmlTextParser() {
                this._specialSymbolArray = [];
                this._stack = [];
                this._resultObjectArray = [];

                this._specialSymbolArray.push([/&lt;/g, '<']);

                this._specialSymbolArray.push([/&gt;/g, '>']);

                this._specialSymbolArray.push([/&amp;/g, '&']);

                this._specialSymbolArray.push([/&quot;/g, '"']);

                this._specialSymbolArray.push([/&apos;/g, '\'']);
              }

              var _proto = HtmlTextParser.prototype;

              _proto.parse = function parse(htmlString) {
                this._resultObjectArray.length = 0;
                this._stack.length = 0;
                var startIndex = 0;
                var length = htmlString.length;

                while (startIndex < length) {
                  var tagEndIndex = htmlString.indexOf('>', startIndex);
                  var tagBeginIndex = -1;

                  if (tagEndIndex >= 0) {
                    tagBeginIndex = htmlString.lastIndexOf('<', tagEndIndex);
                    var noTagBegin = tagBeginIndex < startIndex - 1;

                    if (noTagBegin) {
                      tagBeginIndex = htmlString.indexOf('<', tagEndIndex + 1);
                      tagEndIndex = htmlString.indexOf('>', tagBeginIndex + 1);
                    }
                  }

                  if (tagBeginIndex < 0) {
                    this._stack.pop();

                    this._processResult(htmlString.substring(startIndex));

                    startIndex = length;
                  } else {
                    var newStr = htmlString.substring(startIndex, tagBeginIndex);
                    var tagStr = htmlString.substring(tagBeginIndex + 1, tagEndIndex);
                    if (tagStr === '') newStr = htmlString.substring(startIndex, tagEndIndex + 1);

                    this._processResult(newStr);

                    if (tagEndIndex === -1) {
                      tagEndIndex = tagBeginIndex;
                    } else if (htmlString.charAt(tagBeginIndex + 1) === '/') {
                      this._stack.pop();
                    } else {
                      this._addToStack(tagStr);
                    }

                    startIndex = tagEndIndex + 1;
                  }
                }

                return this._resultObjectArray;
              };

              _proto._attributeToObject = function _attributeToObject(attribute) {
                attribute = attribute.trim();
                var obj = {};
                var header = /^(color|size)(\s)*=/.exec(attribute);
                var tagName = '';
                var nextSpace = 0;
                var eventHanlderString = '';

                if (header) {
                  tagName = header[0];
                  attribute = attribute.substring(tagName.length).trim();

                  if (attribute === '') {
                    return obj;
                  }

                  nextSpace = attribute.indexOf(' ');

                  switch (tagName[0]) {
                    case 'c':
                      if (nextSpace > -1) {
                        obj.color = attribute.substring(0, nextSpace).trim();
                      } else {
                        obj.color = attribute;
                      }

                      break;

                    case 's':
                      obj.size = parseInt(attribute);
                      break;
                  }

                  if (nextSpace > -1) {
                    eventHanlderString = attribute.substring(nextSpace + 1).trim();
                    obj.event = this._processEventHandler(eventHanlderString);
                  }

                  return obj;
                }

                header = /^(br(\s)*\/)/.exec(attribute);

                if (header && header[0].length > 0) {
                  tagName = header[0].trim();

                  if (tagName.startsWith('br') && tagName[tagName.length - 1] === '/') {
                    obj.isNewLine = true;

                    this._resultObjectArray.push({
                      text: '',
                      style: {
                        isNewLine: true
                      }
                    });

                    return obj;
                  }
                }

                header = /^(img(\s)*src(\s)*=[^>]+\/)/.exec(attribute);
                var remainingArgument = '';

                if (header && header[0].length > 0) {
                  tagName = header[0].trim();

                  if (tagName.startsWith('img') && tagName[tagName.length - 1] === '/') {
                    header = imageAttrReg.exec(attribute);
                    var tagValue;
                    var isValidImageTag = false;

                    while (header) {
                      attribute = attribute.substring(attribute.indexOf(header[0]));
                      tagName = attribute.substr(0, header[0].length);
                      remainingArgument = attribute.substring(tagName.length).trim();
                      nextSpace = remainingArgument.indexOf(' ');
                      tagValue = nextSpace > -1 ? remainingArgument.substr(0, nextSpace) : remainingArgument;
                      tagName = tagName.replace(/[^a-zA-Z]/g, '').trim();
                      tagName = tagName.toLowerCase();
                      attribute = remainingArgument.substring(nextSpace).trim();
                      if (tagValue.endsWith('/')) tagValue = tagValue.slice(0, -1);

                      if (tagName === 'src') {
                        switch (tagValue.charCodeAt(0)) {
                          case 34:
                          case 39:
                            isValidImageTag = true;
                            tagValue = tagValue.slice(1, -1);
                            break;
                        }

                        obj.isImage = true;
                        obj.src = tagValue;
                      } else if (tagName === 'height') {
                        obj.imageHeight = parseInt(tagValue);
                      } else if (tagName === 'width') {
                        obj.imageWidth = parseInt(tagValue);
                      } else if (tagName === 'align') {
                        switch (tagValue.charCodeAt(0)) {
                          case 34:
                          case 39:
                            tagValue = tagValue.slice(1, -1);
                            break;
                        }

                        obj.imageAlign = tagValue.toLowerCase();
                      } else if (tagName === 'offset') {
                        obj.imageOffset = tagValue;
                      } else if (tagName === 'click') {
                        obj.event = this._processEventHandler(tagName + "=" + tagValue);
                      }

                      if (obj.event && tagName === 'param') {
                        obj.event[tagName] = tagValue.replace(/^"|"$/g, '');
                      }

                      header = imageAttrReg.exec(attribute);
                    }

                    if (isValidImageTag && obj.isImage) {
                      this._resultObjectArray.push({
                        text: '',
                        style: obj
                      });
                    }

                    return {};
                  }
                }

                header = /^(outline(\s)*[^>]*)/.exec(attribute);

                if (header) {
                  attribute = header[0].substring('outline'.length).trim();
                  var defaultOutlineObject = {
                    color: '#ffffff',
                    width: 1
                  };

                  if (attribute) {
                    var outlineAttrReg = /(\s)*color(\s)*=|(\s)*width(\s)*=|(\s)*click(\s)*=|(\s)*param(\s)*=/;
                    header = outlineAttrReg.exec(attribute);

                    var _tagValue;

                    while (header) {
                      attribute = attribute.substring(attribute.indexOf(header[0]));
                      tagName = attribute.substr(0, header[0].length);
                      remainingArgument = attribute.substring(tagName.length).trim();
                      nextSpace = remainingArgument.indexOf(' ');

                      if (nextSpace > -1) {
                        _tagValue = remainingArgument.substr(0, nextSpace);
                      } else {
                        _tagValue = remainingArgument;
                      }

                      tagName = tagName.replace(/[^a-zA-Z]/g, '').trim();
                      tagName = tagName.toLowerCase();
                      attribute = remainingArgument.substring(nextSpace).trim();

                      if (tagName === 'click') {
                        obj.event = this._processEventHandler(tagName + "=" + _tagValue);
                      } else if (tagName === 'color') {
                        defaultOutlineObject.color = _tagValue;
                      } else if (tagName === 'width') {
                        defaultOutlineObject.width = parseInt(_tagValue);
                      }

                      if (obj.event && tagName === 'param') {
                        obj.event[tagName] = _tagValue.replace(/^"|"$/g, '');
                      }

                      header = outlineAttrReg.exec(attribute);
                    }
                  }

                  obj.outline = defaultOutlineObject;
                }

                header = /^(on|u|b|i)(\s)*/.exec(attribute);

                if (header && header[0].length > 0) {
                  tagName = header[0];
                  attribute = attribute.substring(tagName.length).trim();

                  switch (tagName[0]) {
                    case 'u':
                      obj.underline = true;
                      break;

                    case 'i':
                      obj.italic = true;
                      break;

                    case 'b':
                      obj.bold = true;
                      break;
                  }

                  if (attribute === '') {
                    return obj;
                  }

                  obj.event = this._processEventHandler(attribute);
                }

                return obj;
              };

              _proto._processEventHandler = function _processEventHandler(eventString) {
                var obj = {};
                var index = 0;
                var isValidTag = false;
                var eventNames = eventRegx.exec(eventString);

                while (eventNames) {
                  var eventName = eventNames[0];
                  var eventValue = '';
                  isValidTag = false;
                  eventString = eventString.substring(eventName.length).trim();

                  if (eventString.charAt(0) === '"') {
                    index = eventString.indexOf('"', 1);

                    if (index > -1) {
                      eventValue = eventString.substring(1, index).trim();
                      isValidTag = true;
                    }

                    index++;
                  } else if (eventString.charAt(0) === '\'') {
                    index = eventString.indexOf('\'', 1);

                    if (index > -1) {
                      eventValue = eventString.substring(1, index).trim();
                      isValidTag = true;
                    }

                    index++;
                  } else {
                    var match = /(\S)+/.exec(eventString);

                    if (match) {
                      eventValue = match[0];
                    } else {
                      eventValue = '';
                    }

                    index = eventValue.length;
                  }

                  if (isValidTag) {
                    eventName = eventName.substring(0, eventName.length - 1).trim();
                    obj[eventName] = eventValue;
                  }

                  eventString = eventString.substring(index).trim();
                  eventNames = eventRegx.exec(eventString);
                }

                return obj;
              };

              _proto._addToStack = function _addToStack(attribute) {
                var obj = this._attributeToObject(attribute);

                if (this._stack.length === 0) {
                  this._stack.push(obj);
                } else {
                  if (obj.isNewLine || obj.isImage) {
                    return;
                  }

                  var previousTagObj = this._stack[this._stack.length - 1];

                  for (var key in previousTagObj) {
                    if (!obj[key]) {
                      obj[key] = previousTagObj[key];
                    }
                  }

                  this._stack.push(obj);
                }
              };

              _proto._processResult = function _processResult(value) {
                if (value.length === 0) {
                  return;
                }

                value = this._escapeSpecialSymbol(value);

                if (this._stack.length > 0) {
                  this._resultObjectArray.push({
                    text: value,
                    style: this._stack[this._stack.length - 1]
                  });
                } else {
                  this._resultObjectArray.push({
                    text: value
                  });
                }
              };

              _proto._escapeSpecialSymbol = function _escapeSpecialSymbol(str) {
                for (var _iterator = _createForOfIteratorHelperLoose(this._specialSymbolArray), _step; !(_step = _iterator()).done;) {
                  var symbolArr = _step.value;
                  var key = symbolArr[0];
                  var value = symbolArr[1];
                  str = str.replace(key, value);
                }

                return str;
              };

              return HtmlTextParser;
            }());

            var _dec$Y, _dec2$y, _dec3$q, _dec4$l, _dec5$h, _dec6$c, _dec7$a, _class$Z, _class2$U, _descriptor$K, _descriptor2$w, _temp$V;
            var LabelOutline = function (v) { return exports({ LabelOutline: v, LabelOutlineComponent: v }), v; }((_dec$Y = ccclass('cc.LabelOutline'), _dec2$y = help(), _dec3$q = executionOrder(110), _dec4$l = menu(), _dec5$h = requireComponent(Label), _dec6$c = tooltip(), _dec7$a = tooltip(), _dec$Y(_class$Z = _dec2$y(_class$Z = _dec3$q(_class$Z = _dec4$l(_class$Z = _dec5$h(_class$Z = executeInEditMode(_class$Z = (_class2$U = (_temp$V = function (_Component) {
              _inheritsLoose(LabelOutline, _Component);

              function LabelOutline() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Component.call.apply(_Component, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "_color", _descriptor$K, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_width", _descriptor2$w, _assertThisInitialized(_this));

                return _this;
              }

              var _proto = LabelOutline.prototype;

              _proto.onEnable = function onEnable() {
                this._updateRenderData();
              };

              _proto.onDisable = function onDisable() {
                this._updateRenderData();
              };

              _proto._updateRenderData = function _updateRenderData() {
                var label = this.node.getComponent(Label);

                if (label) {
                  label.updateRenderData(true);
                }
              };

              _createClass(LabelOutline, [{
                key: "color",
                get: function get() {
                  return this._color;
                },
                set: function set(value) {
                  if (this._color === value) {
                    return;
                  }

                  this._color.set(value);

                  this._updateRenderData();
                }
              }, {
                key: "width",
                get: function get() {
                  return this._width;
                },
                set: function set(value) {
                  if (this._width === value) {
                    return;
                  }

                  this._width = value;

                  this._updateRenderData();
                }
              }]);

              return LabelOutline;
            }(Component), _temp$V), (_descriptor$K = _applyDecoratedDescriptor(_class2$U.prototype, "_color", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new Color(0, 0, 0, 255);
              }
            }), _descriptor2$w = _applyDecoratedDescriptor(_class2$U.prototype, "_width", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 2;
              }
            }), _applyDecoratedDescriptor(_class2$U.prototype, "color", [_dec6$c], Object.getOwnPropertyDescriptor(_class2$U.prototype, "color"), _class2$U.prototype), _applyDecoratedDescriptor(_class2$U.prototype, "width", [_dec7$a], Object.getOwnPropertyDescriptor(_class2$U.prototype, "width"), _class2$U.prototype)), _class2$U)) || _class$Z) || _class$Z) || _class$Z) || _class$Z) || _class$Z) || _class$Z));

            var _dec$Z, _dec2$z, _dec3$r, _dec4$m, _dec5$i, _dec6$d, _dec7$b, _dec8$a, _dec9$9, _dec10$8, _dec11$7, _dec12$7, _dec13$6, _dec14$6, _dec15$6, _dec16$6, _dec17$5, _dec18$5, _dec19$5, _dec20$5, _dec21$5, _dec22$5, _dec23$5, _dec24$5, _dec25$5, _class$_, _class2$V, _descriptor$L, _descriptor2$x, _descriptor3$m, _descriptor4$j, _descriptor5$f, _descriptor6$9, _descriptor7$7, _descriptor8$7, _descriptor9$6, _descriptor10$6, _class3$n, _temp$W;
            var SpriteType;

            (function (SpriteType) {
              SpriteType[SpriteType["SIMPLE"] = 0] = "SIMPLE";
              SpriteType[SpriteType["SLICED"] = 1] = "SLICED";
              SpriteType[SpriteType["TILED"] = 2] = "TILED";
              SpriteType[SpriteType["FILLED"] = 3] = "FILLED";
            })(SpriteType || (SpriteType = {}));

            ccenum(SpriteType);
            var FillType;

            (function (FillType) {
              FillType[FillType["HORIZONTAL"] = 0] = "HORIZONTAL";
              FillType[FillType["VERTICAL"] = 1] = "VERTICAL";
              FillType[FillType["RADIAL"] = 2] = "RADIAL";
            })(FillType || (FillType = {}));

            ccenum(FillType);
            var SizeMode;

            (function (SizeMode) {
              SizeMode[SizeMode["CUSTOM"] = 0] = "CUSTOM";
              SizeMode[SizeMode["TRIMMED"] = 1] = "TRIMMED";
              SizeMode[SizeMode["RAW"] = 2] = "RAW";
            })(SizeMode || (SizeMode = {}));

            ccenum(SizeMode);
            var EventType$1;

            (function (EventType) {
              EventType["SPRITE_FRAME_CHANGED"] = "spriteframe-changed";
            })(EventType$1 || (EventType$1 = {}));

            var Sprite = function (v) { return exports({ Sprite: v, SpriteComponent: v }), v; }((_dec$Z = ccclass('cc.Sprite'), _dec2$z = help(), _dec3$r = executionOrder(110), _dec4$m = menu(), _dec5$i = type(SpriteAtlas), _dec6$d = displayOrder(), _dec7$b = tooltip(), _dec8$a = type(SpriteFrame), _dec9$9 = displayOrder(), _dec10$8 = tooltip(), _dec11$7 = type(SpriteType), _dec12$7 = displayOrder(), _dec13$6 = tooltip(), _dec14$6 = type(FillType), _dec15$6 = tooltip(), _dec16$6 = tooltip(), _dec17$5 = range(), _dec18$5 = tooltip(), _dec19$5 = range(), _dec20$5 = tooltip(), _dec21$5 = displayOrder(), _dec22$5 = tooltip(), _dec23$5 = type(SizeMode), _dec24$5 = displayOrder(), _dec25$5 = tooltip(), _dec$Z(_class$_ = _dec2$z(_class$_ = _dec3$r(_class$_ = _dec4$m(_class$_ = (_class2$V = (_temp$W = _class3$n = function (_Renderable2D) {
              _inheritsLoose(Sprite, _Renderable2D);

              function Sprite() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Renderable2D.call.apply(_Renderable2D, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "_spriteFrame", _descriptor$L, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_type", _descriptor2$x, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_fillType", _descriptor3$m, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_sizeMode", _descriptor4$j, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_fillCenter", _descriptor5$f, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_fillStart", _descriptor6$9, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_fillRange", _descriptor7$7, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_isTrimmedMode", _descriptor8$7, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_useGrayscale", _descriptor9$6, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_atlas", _descriptor10$6, _assertThisInitialized(_this));

                return _this;
              }

              var _proto = Sprite.prototype;

              _proto.__preload = function __preload() {
                this.changeMaterialForDefine();

                _Renderable2D.prototype.__preload.call(this);

                if (this._spriteFrame) {
                  this._spriteFrame.once('load', this._onTextureLoaded, this);
                }
              };

              _proto.onEnable = function onEnable() {
                _Renderable2D.prototype.onEnable.call(this);

                this._activateMaterial();

                this._markForUpdateUvDirty();
              };

              _proto.onDestroy = function onDestroy() {
                this.destroyRenderData();

                if (this._spriteFrame && !this._spriteFrame.loaded) {
                  this._spriteFrame.off('load', this._onTextureLoaded, this);
                }

                _Renderable2D.prototype.onDestroy.call(this);
              };

              _proto.changeSpriteFrameFromAtlas = function changeSpriteFrameFromAtlas(name) {
                if (!this._atlas) {
                  console.warn('SpriteAtlas is null.');
                  return;
                }

                var sprite = this._atlas.getSpriteFrame(name);

                this.spriteFrame = sprite;
              };

              _proto.changeMaterialForDefine = function changeMaterialForDefine() {
                var texture;
                var lastInstanceMaterialType = this._instanceMaterialType;

                if (this._spriteFrame) {
                  texture = this._spriteFrame.texture;
                }

                var value = false;

                if (texture instanceof TextureBase) {
                  var format = texture.getPixelFormat();
                  value = format === PixelFormat.RGBA_ETC1 || format === PixelFormat.RGB_A_PVRTC_4BPPV1 || format === PixelFormat.RGB_A_PVRTC_2BPPV1;
                }

                if (value && this.grayscale) {
                  this._instanceMaterialType = InstanceMaterialType.USE_ALPHA_SEPARATED_AND_GRAY;
                } else if (value) {
                  this._instanceMaterialType = InstanceMaterialType.USE_ALPHA_SEPARATED;
                } else if (this.grayscale) {
                  this._instanceMaterialType = InstanceMaterialType.GRAYSCALE;
                } else {
                  this._instanceMaterialType = InstanceMaterialType.ADD_COLOR_AND_TEXTURE;
                }

                if (lastInstanceMaterialType !== this._instanceMaterialType) {
                  this.updateMaterial();
                }
              };

              _proto._updateBuiltinMaterial = function _updateBuiltinMaterial() {
                var mat = _Renderable2D.prototype._updateBuiltinMaterial.call(this);

                if (this.spriteFrame && this.spriteFrame.texture instanceof RenderTexture) {
                  var defines = _extends({
                    SAMPLE_FROM_RT: true
                  }, mat.passes[0].defines);

                  var renderMat = new Material();
                  renderMat.initialize({
                    effectAsset: mat.effectAsset,
                    defines: defines
                  });
                  mat = renderMat;
                }

                return mat;
              };

              _proto._render = function _render(render) {
                render.commitComp(this, this._spriteFrame, this._assembler, null);
              };

              _proto._canRender = function _canRender() {
                if (!_Renderable2D.prototype._canRender.call(this)) {
                  return false;
                }

                var spriteFrame = this._spriteFrame;

                if (!spriteFrame || !spriteFrame.textureLoaded()) {
                  return false;
                }

                return true;
              };

              _proto._flushAssembler = function _flushAssembler() {
                var assembler = Sprite.Assembler.getAssembler(this);

                if (this._assembler !== assembler) {
                  this.destroyRenderData();
                  this._assembler = assembler;
                }

                if (!this._renderData) {
                  if (this._assembler && this._assembler.createData) {
                    this._renderData = this._assembler.createData(this);
                    this._renderData.material = this.getRenderMaterial(0);
                    this.markForUpdateRenderData();
                    this._colorDirty = true;

                    this._updateColor();
                  }
                }
              };

              _proto._applySpriteSize = function _applySpriteSize() {
                if (this._spriteFrame) {
                  if (!this._spriteFrame.isDefault) {
                    if (SizeMode.RAW === this._sizeMode) {
                      var size = this._spriteFrame.originalSize;

                      this.node._uiProps.uiTransformComp.setContentSize(size);
                    } else if (SizeMode.TRIMMED === this._sizeMode) {
                      var rect = this._spriteFrame.getRect();

                      this.node._uiProps.uiTransformComp.setContentSize(rect.width, rect.height);
                    }
                  }

                  this._activateMaterial();
                }
              };

              _proto._resized = function _resized() {
                {
                  return;
                }
              };

              _proto._activateMaterial = function _activateMaterial() {
                var spriteFrame = this._spriteFrame;
                var material = this.getRenderMaterial(0);

                if (legacyCC.game.renderType !== legacyCC.game.RENDER_TYPE_CANVAS) {
                  if (spriteFrame) {
                    if (material) {
                      this.markForUpdateRenderData();
                    }
                  }

                  if (this._renderData) {
                    this._renderData.material = material;
                  }
                } else {
                  this.markForUpdateRenderData();
                }
              };

              _proto._onTextureLoaded = function _onTextureLoaded() {
                if (!this.isValid) {
                  return;
                }

                this.changeMaterialForDefine();

                this._applySpriteSize();
              };

              _proto._applySpriteFrame = function _applySpriteFrame(oldFrame) {
                var spriteFrame = this._spriteFrame;

                if (this._renderData) {
                  if (oldFrame && !oldFrame.loaded) {
                    oldFrame.off('load', this._onTextureLoaded, this);
                  }

                  if (!this._renderData.uvDirty) {
                    if (oldFrame && spriteFrame) {
                      this._renderData.uvDirty = oldFrame.uvHash !== spriteFrame.uvHash;
                    } else {
                      this._renderData.uvDirty = true;
                    }
                  }

                  this._renderDataFlag = this._renderData.uvDirty;
                }

                var textureChanged = false;

                if (spriteFrame) {
                  if (!oldFrame || oldFrame.texture !== spriteFrame.texture) {
                    textureChanged = true;
                  }

                  if (spriteFrame.loaded) {
                    if (textureChanged) {
                      this._onTextureLoaded();
                    } else {
                      this._applySpriteSize();
                    }
                  } else {
                    spriteFrame.once('load', this._onTextureLoaded, this);
                  }
                }
              };

              _proto._markForUpdateUvDirty = function _markForUpdateUvDirty() {
                if (this._renderData) {
                  this._renderData.uvDirty = true;
                  this._renderDataFlag = true;
                }
              };

              _createClass(Sprite, [{
                key: "spriteAtlas",
                get: function get() {
                  return this._atlas;
                },
                set: function set(value) {
                  if (this._atlas === value) {
                    return;
                  }

                  this._atlas = value;
                }
              }, {
                key: "spriteFrame",
                get: function get() {
                  return this._spriteFrame;
                },
                set: function set(value) {
                  if (this._spriteFrame === value) {
                    return;
                  }

                  var lastSprite = this._spriteFrame;
                  this._spriteFrame = value;
                  this.markForUpdateRenderData(false);

                  this._applySpriteFrame(lastSprite);
                }
              }, {
                key: "type",
                get: function get() {
                  return this._type;
                },
                set: function set(value) {
                  if (this._type !== value) {
                    this._type = value;

                    this._flushAssembler();
                  }
                }
              }, {
                key: "fillType",
                get: function get() {
                  return this._fillType;
                },
                set: function set(value) {
                  if (this._fillType !== value) {
                    if (value === FillType.RADIAL || this._fillType === FillType.RADIAL) {
                      this.destroyRenderData();
                      this._renderData = null;
                    } else if (this._renderData) {
                      this.markForUpdateRenderData(true);
                    }
                  }

                  this._fillType = value;

                  this._flushAssembler();
                }
              }, {
                key: "fillCenter",
                get: function get() {
                  return this._fillCenter;
                },
                set: function set(value) {
                  this._fillCenter.x = value.x;
                  this._fillCenter.y = value.y;

                  if (this._type === SpriteType.FILLED && this._renderData) {
                    this.markForUpdateRenderData();
                  }
                }
              }, {
                key: "fillStart",
                get: function get() {
                  return this._fillStart;
                },
                set: function set(value) {
                  this._fillStart = clamp(value, -1, 1);

                  if (this._type === SpriteType.FILLED && this._renderData) {
                    this.markForUpdateRenderData();
                    this._renderData.uvDirty = true;
                  }
                }
              }, {
                key: "fillRange",
                get: function get() {
                  return this._fillRange;
                },
                set: function set(value) {
                  this._fillRange = clamp(value, -1, 1);

                  if (this._type === SpriteType.FILLED && this._renderData) {
                    this.markForUpdateRenderData();
                    this._renderData.uvDirty = true;
                  }
                }
              }, {
                key: "trim",
                get: function get() {
                  return this._isTrimmedMode;
                },
                set: function set(value) {
                  if (this._isTrimmedMode === value) {
                    return;
                  }

                  this._isTrimmedMode = value;

                  if (this._type === SpriteType.SIMPLE && this._renderData) {
                    this.markForUpdateRenderData(true);
                  }
                }
              }, {
                key: "grayscale",
                get: function get() {
                  return this._useGrayscale;
                },
                set: function set(value) {
                  if (this._useGrayscale === value) {
                    return;
                  }

                  this._useGrayscale = value;

                  if (value === true) {
                    this._instanceMaterialType = InstanceMaterialType.GRAYSCALE;
                  } else {
                    this._instanceMaterialType = InstanceMaterialType.ADD_COLOR_AND_TEXTURE;
                  }

                  this.updateMaterial();
                }
              }, {
                key: "sizeMode",
                get: function get() {
                  return this._sizeMode;
                },
                set: function set(value) {
                  if (this._sizeMode === value) {
                    return;
                  }

                  this._sizeMode = value;

                  if (value !== SizeMode.CUSTOM) {
                    this._applySpriteSize();
                  }
                }
              }]);

              return Sprite;
            }(Renderable2D), _class3$n.FillType = FillType, _class3$n.Type = SpriteType, _class3$n.SizeMode = SizeMode, _class3$n.EventType = EventType$1, _temp$W), (_applyDecoratedDescriptor(_class2$V.prototype, "spriteAtlas", [_dec5$i, _dec6$d, _dec7$b], Object.getOwnPropertyDescriptor(_class2$V.prototype, "spriteAtlas"), _class2$V.prototype), _applyDecoratedDescriptor(_class2$V.prototype, "spriteFrame", [_dec8$a, _dec9$9, _dec10$8], Object.getOwnPropertyDescriptor(_class2$V.prototype, "spriteFrame"), _class2$V.prototype), _applyDecoratedDescriptor(_class2$V.prototype, "type", [_dec11$7, _dec12$7, _dec13$6], Object.getOwnPropertyDescriptor(_class2$V.prototype, "type"), _class2$V.prototype), _applyDecoratedDescriptor(_class2$V.prototype, "fillType", [_dec14$6, _dec15$6], Object.getOwnPropertyDescriptor(_class2$V.prototype, "fillType"), _class2$V.prototype), _applyDecoratedDescriptor(_class2$V.prototype, "fillCenter", [_dec16$6], Object.getOwnPropertyDescriptor(_class2$V.prototype, "fillCenter"), _class2$V.prototype), _applyDecoratedDescriptor(_class2$V.prototype, "fillStart", [_dec17$5, _dec18$5], Object.getOwnPropertyDescriptor(_class2$V.prototype, "fillStart"), _class2$V.prototype), _applyDecoratedDescriptor(_class2$V.prototype, "fillRange", [_dec19$5, _dec20$5], Object.getOwnPropertyDescriptor(_class2$V.prototype, "fillRange"), _class2$V.prototype), _applyDecoratedDescriptor(_class2$V.prototype, "trim", [_dec21$5, _dec22$5], Object.getOwnPropertyDescriptor(_class2$V.prototype, "trim"), _class2$V.prototype), _applyDecoratedDescriptor(_class2$V.prototype, "grayscale", [editable], Object.getOwnPropertyDescriptor(_class2$V.prototype, "grayscale"), _class2$V.prototype), _applyDecoratedDescriptor(_class2$V.prototype, "sizeMode", [_dec23$5, _dec24$5, _dec25$5], Object.getOwnPropertyDescriptor(_class2$V.prototype, "sizeMode"), _class2$V.prototype), _descriptor$L = _applyDecoratedDescriptor(_class2$V.prototype, "_spriteFrame", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor2$x = _applyDecoratedDescriptor(_class2$V.prototype, "_type", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return SpriteType.SIMPLE;
              }
            }), _descriptor3$m = _applyDecoratedDescriptor(_class2$V.prototype, "_fillType", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return FillType.HORIZONTAL;
              }
            }), _descriptor4$j = _applyDecoratedDescriptor(_class2$V.prototype, "_sizeMode", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return SizeMode.TRIMMED;
              }
            }), _descriptor5$f = _applyDecoratedDescriptor(_class2$V.prototype, "_fillCenter", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new Vec2(0, 0);
              }
            }), _descriptor6$9 = _applyDecoratedDescriptor(_class2$V.prototype, "_fillStart", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor7$7 = _applyDecoratedDescriptor(_class2$V.prototype, "_fillRange", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor8$7 = _applyDecoratedDescriptor(_class2$V.prototype, "_isTrimmedMode", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _descriptor9$6 = _applyDecoratedDescriptor(_class2$V.prototype, "_useGrayscale", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor10$6 = _applyDecoratedDescriptor(_class2$V.prototype, "_atlas", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            })), _class2$V)) || _class$_) || _class$_) || _class$_) || _class$_));

            var _dec$_, _dec2$A, _dec3$s, _dec4$n, _class$$;
            var RenderRoot2D = exports('RenderRoot2D', (_dec$_ = ccclass('cc.RenderRoot2D'), _dec2$A = executionOrder(100), _dec3$s = menu(), _dec4$n = requireComponent(UITransform), _dec$_(_class$$ = _dec2$A(_class$$ = _dec3$s(_class$$ = _dec4$n(_class$$ = disallowMultiple(_class$$ = executeInEditMode(_class$$ = function (_Component) {
              _inheritsLoose(RenderRoot2D, _Component);

              function RenderRoot2D() {
                return _Component.apply(this, arguments) || this;
              }

              var _proto = RenderRoot2D.prototype;

              _proto.onEnable = function onEnable() {
                legacyCC.director.root.batcher2D.addScreen(this);
              };

              _proto.onDisable = function onDisable() {
                legacyCC.director.root.batcher2D.removeScreen(this);
              };

              _proto.onDestroy = function onDestroy() {
                legacyCC.director.root.batcher2D.removeScreen(this);
              };

              return RenderRoot2D;
            }(Component)) || _class$$) || _class$$) || _class$$) || _class$$) || _class$$) || _class$$));

            var _dec$$, _dec2$B, _dec3$t, _dec4$o, _dec5$j, _dec6$e, _dec7$c, _dec8$b, _class$10, _class2$W, _descriptor$M, _descriptor2$y, _temp$X;

            var _worldPos = new Vec3();

            var RenderMode = Enum({
              OVERLAY: 0,
              INTERSPERSE: 1
            });
            var Canvas = function (v) { return exports({ Canvas: v, CanvasComponent: v }), v; }((_dec$$ = ccclass('cc.Canvas'), _dec2$B = help(), _dec3$t = executionOrder(100), _dec4$o = menu(), _dec5$j = type(Camera$1), _dec6$e = tooltip(), _dec7$c = tooltip(), _dec8$b = type(Camera$1), _dec$$(_class$10 = _dec2$B(_class$10 = _dec3$t(_class$10 = _dec4$o(_class$10 = executeInEditMode(_class$10 = disallowMultiple(_class$10 = (_class2$W = (_temp$X = function (_RenderRoot2D) {
              _inheritsLoose(Canvas, _RenderRoot2D);

              function Canvas() {
                var _this;

                _this = _RenderRoot2D.call(this) || this;

                _initializerDefineProperty(_this, "_cameraComponent", _descriptor$M, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_alignCanvasWithScreen", _descriptor2$y, _assertThisInitialized(_this));

                _this._thisOnCameraResized = void 0;
                _this._fitDesignResolution = void 0;
                _this._pos = new Vec3();
                _this._renderMode = RenderMode.OVERLAY;
                _this._thisOnCameraResized = _this._onResizeCamera.bind(_assertThisInitialized(_this));

                return _this;
              }

              var _proto = Canvas.prototype;

              _proto.__preload = function __preload() {
                var widget = this.getComponent('cc.Widget');

                if (widget) {
                  widget.updateAlignment();
                }

                {
                  if (this._cameraComponent) {
                    this._cameraComponent._createCamera();
                  }
                }

                this._onResizeCamera();

                this.node.on(SystemEventType.TRANSFORM_CHANGED, this._thisOnCameraResized);
              };

              _proto.onDestroy = function onDestroy() {
                _RenderRoot2D.prototype.onDestroy.call(this);

                this.node.off(SystemEventType.TRANSFORM_CHANGED, this._thisOnCameraResized);
              };

              _proto._onResizeCamera = function _onResizeCamera() {
                if (this._cameraComponent && this._alignCanvasWithScreen) {
                  if (this._cameraComponent.targetTexture) {
                    var win = this._cameraComponent.targetTexture.window;

                    if (this._cameraComponent.camera) {
                      this._cameraComponent.camera.setFixedSize(win.width, win.height);
                    }

                    this._cameraComponent.orthoHeight = visibleRect.height / 2;
                  } else if (game.canvas) {
                    var size = game.canvas;

                    if (this._cameraComponent.camera) {
                      this._cameraComponent.camera.resize(size.width, size.height);
                    }

                    this._cameraComponent.orthoHeight = game.canvas.height / view.getScaleY() / 2;
                  }

                  this.node.getWorldPosition(_worldPos);

                  this._cameraComponent.node.setWorldPosition(_worldPos.x, _worldPos.y, 1000);
                }
              };

              _proto._getViewPriority = function _getViewPriority() {
                if (this._cameraComponent) {
                  var _this$cameraComponent;

                  var priority = (_this$cameraComponent = this.cameraComponent) === null || _this$cameraComponent === void 0 ? void 0 : _this$cameraComponent.priority;
                  priority = this._renderMode === RenderMode.OVERLAY ? priority | 1 << 30 : priority & ~(1 << 30);
                  return priority;
                }

                return 0;
              };

              _createClass(Canvas, [{
                key: "renderMode",
                get: function get() {
                  return this._renderMode;
                },
                set: function set(val) {
                  this._renderMode = val;

                  if (this._cameraComponent) {
                    this._cameraComponent.priority = this._getViewPriority();
                  }
                }
              }, {
                key: "cameraComponent",
                get: function get() {
                  return this._cameraComponent;
                },
                set: function set(value) {
                  if (this._cameraComponent === value) {
                    return;
                  }

                  this._cameraComponent = value;

                  this._onResizeCamera();
                }
              }, {
                key: "alignCanvasWithScreen",
                get: function get() {
                  return this._alignCanvasWithScreen;
                },
                set: function set(value) {
                  this._alignCanvasWithScreen = value;

                  this._onResizeCamera();
                }
              }]);

              return Canvas;
            }(RenderRoot2D), _temp$X), (_applyDecoratedDescriptor(_class2$W.prototype, "cameraComponent", [_dec5$j, _dec6$e], Object.getOwnPropertyDescriptor(_class2$W.prototype, "cameraComponent"), _class2$W.prototype), _applyDecoratedDescriptor(_class2$W.prototype, "alignCanvasWithScreen", [_dec7$c], Object.getOwnPropertyDescriptor(_class2$W.prototype, "alignCanvasWithScreen"), _class2$W.prototype), _descriptor$M = _applyDecoratedDescriptor(_class2$W.prototype, "_cameraComponent", [_dec8$b], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor2$y = _applyDecoratedDescriptor(_class2$W.prototype, "_alignCanvasWithScreen", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            })), _class2$W)) || _class$10) || _class$10) || _class$10) || _class$10) || _class$10) || _class$10));
            legacyCC.Canvas = Canvas;

            var _dec$10, _dec2$C, _dec3$u, _class$11, _temp$Y;
            var UIComponent = exports('UIComponent', (_dec$10 = ccclass('cc.UIComponent'), _dec2$C = requireComponent(UITransform), _dec3$u = executionOrder(110), _dec$10(_class$11 = _dec2$C(_class$11 = _dec3$u(_class$11 = disallowMultiple(_class$11 = executeInEditMode(_class$11 = (_temp$Y = function (_Component) {
              _inheritsLoose(UIComponent, _Component);

              function UIComponent() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Component.call.apply(_Component, [this].concat(args)) || this;
                _this._lastParent = null;
                _this.stencilStage = Stage.DISABLED;
                return _this;
              }

              var _proto = UIComponent.prototype;

              _proto.__preload = function __preload() {
                this.node._uiProps.uiComp = this;
              };

              _proto.onEnable = function onEnable() {};

              _proto.onDisable = function onDisable() {};

              _proto.onDestroy = function onDestroy() {
                if (this.node._uiProps.uiComp === this) {
                  this.node._uiProps.uiComp = null;
                }
              };

              _proto.updateAssembler = function updateAssembler(render) {};

              _proto.postUpdateAssembler = function postUpdateAssembler(render) {};

              _proto.markForUpdateRenderData = function markForUpdateRenderData(enable) {
              };

              return UIComponent;
            }(Component), _temp$Y)) || _class$11) || _class$11) || _class$11) || _class$11) || _class$11));

            removeProperty(UIComponent.prototype, 'UIComponent', [{
              name: '_visibility'
            }, {
              name: 'setVisibility'
            }]);
            replaceProperty(Canvas.prototype, 'Canvas.prototype', [{
              name: 'camera',
              newName: 'cameraComponent.camera',
              customGetter: function customGetter() {
                return this._cameraComponent.camera;
              }
            }, {
              name: 'clearFlag',
              newName: 'cameraComponent.clearFlags',
              customGetter: function customGetter() {
                return this._cameraComponent ? this._cameraComponent.clearFlags : 0;
              },
              customSetter: function customSetter(val) {
                if (this._cameraComponent) this._cameraComponent.clearFlags = val;
              }
            }, {
              name: 'color',
              newName: 'cameraComponent.clearColor',
              customGetter: function customGetter() {
                return this._cameraComponent ? this._cameraComponent.clearColor : Color.BLACK;
              },
              customSetter: function customSetter(val) {
                if (this._cameraComponent) this._cameraComponent.clearColor = val;
              }
            }, {
              name: 'priority',
              newName: 'cameraComponent.priority',
              customGetter: function customGetter() {
                return this._cameraComponent ? this._cameraComponent.priority : 0;
              },
              customSetter: function customSetter(val) {
                if (this._cameraComponent) this._cameraComponent.priority = val;
              }
            }, {
              name: 'targetTexture',
              newName: 'cameraComponent.targetTexture',
              customGetter: function customGetter() {
                return this._cameraComponent ? this._cameraComponent.targetTexture : null;
              },
              customSetter: function customSetter(value) {
                if (this._cameraComponent) this._cameraComponent.targetTexture = value;
              }
            }, {
              name: 'visibility',
              newName: 'cameraComponent.visibility',
              customGetter: function customGetter() {
                return this._cameraComponent ? this._cameraComponent.visibility : 0;
              }
            }]);
            markAsWarning(Renderable2D.prototype, 'Renderable2D.prototype', [{
              name: 'srcBlendFactor',
              suggest: 'Please use a custom material to specify blending options instead.'
            }, {
              name: 'dstBlendFactor',
              suggest: 'Please use a custom material to specify blending options instead.'
            }]);
            markAsWarning(UITransform.prototype, 'UITransform.prototype', [{
              name: 'priority',
              suggest: "Please use setSiblingIndex to change index of the current node in its parent's children array."
            }]);
            legacyCC.UITransformComponent = UITransform;
            js.setClassAlias(UITransform, 'cc.UITransformComponent');
            js.setClassAlias(Renderable2D, 'cc.RenderComponent');
            legacyCC.CanvasComponent = Canvas;
            js.setClassAlias(Canvas, 'cc.CanvasComponent');

            var _dec$11, _dec2$D, _dec3$v, _dec4$p, _dec5$k, _dec6$f, _dec7$d, _dec8$c, _dec9$a, _dec10$9, _dec11$8, _dec12$8, _dec13$7, _dec14$7, _dec15$7, _dec16$7, _dec17$6, _dec18$6, _dec19$6, _class$12, _class2$X, _descriptor$N, _descriptor2$z, _descriptor3$n, _descriptor4$k, _descriptor5$g, _descriptor6$a, _descriptor7$8, _descriptor8$8, _descriptor9$7, _descriptor10$7, _descriptor11$6, _descriptor12$5, _class3$o, _temp$Z;

            var _htmlTextParser = new HtmlTextParser();

            var RichTextChildName = 'RICHTEXT_CHILD';
            var RichTextChildImageName = 'RICHTEXT_Image_CHILD';
            var labelPool = new Pool(function (seg) {

              if (!legacyCC.isValid(seg.node)) {
                return false;
              } else {
                var outline = seg.node.getComponent(LabelOutline);

                if (outline) {
                  outline.width = 0;
                }
              }

              return true;
            }, 20);
            var imagePool = new Pool(function (seg) {

              return legacyCC.isValid(seg.node);
            }, 10);

            function createSegment(type) {
              return {
                node: new Node$1(type),
                comp: null,
                lineCount: 0,
                styleIndex: 0,
                imageOffset: '',
                clickParam: '',
                clickHandler: '',
                type: type
              };
            }

            function getSegmentByPool(type, content) {
              var seg;

              if (type === RichTextChildName) {
                seg = labelPool._get();
              } else if (type === RichTextChildImageName) {
                seg = imagePool._get();
              }

              seg = seg || createSegment(type);
              var node = seg.node;

              if (!node) {
                node = new Node$1(type);
              }

              node.hideFlags |= CCObject.Flags.DontSave | CCObject.Flags.HideInHierarchy;

              if (type === RichTextChildImageName) {
                seg.comp = node.getComponent(Sprite) || node.addComponent(Sprite);
                seg.comp.spriteFrame = content;
                seg.comp.type = Sprite.Type.SLICED;
                seg.comp.sizeMode = Sprite.SizeMode.CUSTOM;
              } else {
                seg.comp = node.getComponent(Label) || node.addComponent(Label);
                seg.comp.string = content;
                seg.comp.horizontalAlign = HorizontalTextAlignment.LEFT;
                seg.comp.verticalAlign = VerticalTextAlignment.TOP;
              }

              node.setPosition(0, 0, 0);
              var trans = node._uiProps.uiTransformComp;
              trans.setAnchorPoint(0.5, 0.5);
              seg.node = node;
              seg.lineCount = 0;
              seg.styleIndex = 0;
              seg.imageOffset = '';
              seg.clickParam = '';
              seg.clickHandler = '';
              return seg;
            }

            var RichText = function (v) { return exports({ RichText: v, RichTextComponent: v }), v; }((_dec$11 = ccclass('cc.RichText'), _dec2$D = help(), _dec3$v = executionOrder(110), _dec4$p = menu(), _dec5$k = tooltip(), _dec6$f = type(HorizontalTextAlignment), _dec7$d = tooltip(), _dec8$c = tooltip(), _dec9$a = tooltip(), _dec10$9 = type(Font), _dec11$8 = tooltip(), _dec12$8 = tooltip(), _dec13$7 = type(CacheMode), _dec14$7 = tooltip(), _dec15$7 = tooltip(), _dec16$7 = tooltip(), _dec17$6 = type(SpriteAtlas), _dec18$6 = tooltip(), _dec19$6 = tooltip(), _dec$11(_class$12 = _dec2$D(_class$12 = _dec3$v(_class$12 = _dec4$p(_class$12 = executeInEditMode(_class$12 = (_class2$X = (_temp$Z = _class3$o = function (_UIComponent) {
              _inheritsLoose(RichText, _UIComponent);

              function RichText() {
                var _this;

                _this = _UIComponent.call(this) || this;

                _initializerDefineProperty(_this, "_lineHeight", _descriptor$N, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_string", _descriptor2$z, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_horizontalAlign", _descriptor3$n, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_fontSize", _descriptor4$k, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_maxWidth", _descriptor5$g, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_fontFamily", _descriptor6$a, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_font", _descriptor7$8, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_isSystemFontUsed", _descriptor8$8, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_userDefinedFont", _descriptor9$7, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_cacheMode", _descriptor10$7, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_imageAtlas", _descriptor11$6, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_handleTouchEvent", _descriptor12$5, _assertThisInitialized(_this));

                _this._textArray = [];
                _this._segments = [];
                _this._labelSegmentsCache = [];
                _this._linesWidth = [];
                _this._lineCount = 1;
                _this._labelWidth = 0;
                _this._labelHeight = 0;
                _this._layoutDirty = true;
                _this._lineOffsetX = 0;
                _this._updateRichTextStatus = void 0;

                _this._updateRichTextStatus = _this._updateRichText;
                return _this;
              }

              var _proto = RichText.prototype;

              _proto.onLoad = function onLoad() {
                this.node.on(SystemEventType.LAYER_CHANGED, this._applyLayer, this);
              };

              _proto.onEnable = function onEnable() {
                if (this.handleTouchEvent) {
                  this._addEventListeners();
                }

                this._updateRichText();

                this._activateChildren(true);
              };

              _proto.onDisable = function onDisable() {
                if (this.handleTouchEvent) {
                  this._removeEventListeners();
                }

                this._activateChildren(false);
              };

              _proto.start = function start() {
                this._onTTFLoaded();

                this.node.on(Node$1.EventType.ANCHOR_CHANGED, this._updateRichTextPosition, this);
              };

              _proto.onRestore = function onRestore() {
                {
                  return;
                }
              };

              _proto.onDestroy = function onDestroy() {
                for (var _iterator = _createForOfIteratorHelperLoose(this._segments), _step; !(_step = _iterator()).done;) {
                  var seg = _step.value;
                  seg.node.removeFromParent();

                  if (seg.type === RichTextChildName) {
                    labelPool.put(seg);
                  } else if (seg.type === RichTextChildImageName) {
                    imagePool.put(seg);
                  }
                }

                this.node.off(Node$1.EventType.ANCHOR_CHANGED, this._updateRichTextPosition, this);
                this.node.off(SystemEventType.LAYER_CHANGED, this._applyLayer, this);
              };

              _proto._addEventListeners = function _addEventListeners() {
                this.node.on(Node$1.EventType.TOUCH_END, this._onTouchEnded, this);
              };

              _proto._removeEventListeners = function _removeEventListeners() {
                this.node.off(Node$1.EventType.TOUCH_END, this._onTouchEnded, this);
              };

              _proto._updateLabelSegmentTextAttributes = function _updateLabelSegmentTextAttributes() {
                var _this2 = this;

                this._segments.forEach(function (item) {
                  _this2._applyTextAttribute(item);
                });
              };

              _proto._createFontLabel = function _createFontLabel(str) {
                return getSegmentByPool(RichTextChildName, str);
              };

              _proto._createImage = function _createImage(spriteFrame) {
                return getSegmentByPool(RichTextChildImageName, spriteFrame);
              };

              _proto._onTTFLoaded = function _onTTFLoaded() {
                var _this3 = this;

                if (this._font instanceof TTFFont) {
                  if (this._font._nativeAsset) {
                    this._layoutDirty = true;

                    this._updateRichText();
                  } else {
                    assetManager.postLoadNative(this._font, function (err) {
                      if (!_this3.isValid) {
                        return;
                      }

                      _this3._layoutDirty = true;

                      _this3._updateRichText();
                    });
                  }
                } else {
                  this._layoutDirty = true;

                  this._updateRichText();
                }
              };

              _proto._measureText = function _measureText(styleIndex, string) {
                var _this4 = this;

                var func = function func(s) {
                  var label;

                  if (_this4._labelSegmentsCache.length === 0) {
                    label = _this4._createFontLabel(s);

                    _this4._labelSegmentsCache.push(label);
                  } else {
                    label = _this4._labelSegmentsCache[0];
                    label.node.getComponent(Label).string = s;
                  }

                  label.styleIndex = styleIndex;

                  _this4._applyTextAttribute(label);

                  var labelSize = label.node._uiProps.uiTransformComp.contentSize;
                  return labelSize.width;
                };

                if (string) {
                  return func(string);
                } else {
                  return func;
                }
              };

              _proto._onTouchEnded = function _onTouchEnded(event) {
                var _this5 = this;

                var components = this.node.getComponents(Component);

                var _loop = function _loop() {
                  var seg = _step2.value;
                  var clickHandler = seg.clickHandler;
                  var clickParam = seg.clickParam;

                  if (clickHandler && _this5._containsTouchLocation(seg, event.touch.getUILocation())) {
                    components.forEach(function (component) {
                      var func = component[clickHandler];

                      if (component.enabledInHierarchy && func) {
                        func.call(component, event, clickParam);
                      }
                    });
                    event.propagationStopped = true;
                  }
                };

                for (var _iterator2 = _createForOfIteratorHelperLoose(this._segments), _step2; !(_step2 = _iterator2()).done;) {
                  _loop();
                }
              };

              _proto._containsTouchLocation = function _containsTouchLocation(label, point) {
                var comp = label.node.getComponent(UITransform);

                if (!comp) {
                  return false;
                }

                var myRect = comp.getBoundingBoxToWorld();
                return myRect.contains(point);
              };

              _proto._resetState = function _resetState() {
                var children = this.node.children;

                for (var i = children.length - 1; i >= 0; i--) {
                  var child = children[i];

                  if (child.name === RichTextChildName || child.name === RichTextChildImageName) {
                    if (child.parent === this.node) {
                      child.parent = null;
                    } else {
                      children.splice(i, 1);
                    }

                    var segment = createSegment(child.name);
                    segment.node = child;

                    if (child.name === RichTextChildName) {
                      segment.comp = child.getComponent(Label);
                      labelPool.put(segment);
                    } else {
                      segment.comp = child.getComponent(Sprite);
                      imagePool.put(segment);
                    }
                  }
                }

                children.length = 0;
                this._segments.length = 0;
                this._labelSegmentsCache.length = 0;
                this._linesWidth.length = 0;
                this._lineOffsetX = 0;
                this._lineCount = 1;
                this._labelWidth = 0;
                this._labelHeight = 0;
                this._layoutDirty = true;
              };

              _proto._activateChildren = function _activateChildren(active) {
                for (var i = this.node.children.length - 1; i >= 0; i--) {
                  var child = this.node.children[i];

                  if (child.name === RichTextChildName || child.name === RichTextChildImageName) {
                    child.active = active;
                  }
                }
              };

              _proto._addLabelSegment = function _addLabelSegment(stringToken, styleIndex) {
                var labelSegment;

                if (this._labelSegmentsCache.length === 0) {
                  labelSegment = this._createFontLabel(stringToken);
                } else {
                  labelSegment = this._labelSegmentsCache.pop();
                  var label = labelSegment.node.getComponent(Label);

                  if (label) {
                    label.string = stringToken;
                  }
                }

                labelSegment.styleIndex = styleIndex;
                labelSegment.lineCount = this._lineCount;

                labelSegment.node._uiProps.uiTransformComp.setAnchorPoint(0, 0);

                labelSegment.node.layer = this.node.layer;

                this._applyTextAttribute(labelSegment);

                this.node.addChild(labelSegment.node);

                this._segments.push(labelSegment);

                return labelSegment;
              };

              _proto._updateRichTextWithMaxWidth = function _updateRichTextWithMaxWidth(labelString, labelWidth, styleIndex) {
                var fragmentWidth = labelWidth;
                var labelSegment;

                if (this._lineOffsetX > 0 && fragmentWidth + this._lineOffsetX > this._maxWidth) {
                  var checkStartIndex = 0;

                  while (this._lineOffsetX <= this._maxWidth) {
                    var checkEndIndex = this._getFirstWordLen(labelString, checkStartIndex, labelString.length);

                    var checkString = labelString.substr(checkStartIndex, checkEndIndex);

                    var checkStringWidth = this._measureText(styleIndex, checkString);

                    if (this._lineOffsetX + checkStringWidth <= this._maxWidth) {
                      this._lineOffsetX += checkStringWidth;
                      checkStartIndex += checkEndIndex;
                    } else {
                      if (checkStartIndex > 0) {
                        var remainingString = labelString.substr(0, checkStartIndex);

                        this._addLabelSegment(remainingString, styleIndex);

                        labelString = labelString.substr(checkStartIndex, labelString.length);
                        fragmentWidth = this._measureText(styleIndex, labelString);
                      }

                      this._updateLineInfo();

                      break;
                    }
                  }
                }

                if (fragmentWidth > this._maxWidth) {
                  var fragments = fragmentText(labelString, fragmentWidth, this._maxWidth, this._measureText(styleIndex));

                  for (var k = 0; k < fragments.length; ++k) {
                    var splitString = fragments[k];
                    labelSegment = this._addLabelSegment(splitString, styleIndex);
                    var labelSize = labelSegment.node._uiProps.uiTransformComp.contentSize;
                    this._lineOffsetX += labelSize.width;

                    if (fragments.length > 1 && k < fragments.length - 1) {
                      this._updateLineInfo();
                    }
                  }
                } else {
                  this._lineOffsetX += fragmentWidth;

                  this._addLabelSegment(labelString, styleIndex);
                }
              };

              _proto._isLastComponentCR = function _isLastComponentCR(stringToken) {
                return stringToken.length - 1 === stringToken.lastIndexOf('\n');
              };

              _proto._updateLineInfo = function _updateLineInfo() {
                this._linesWidth.push(this._lineOffsetX);

                this._lineOffsetX = 0;
                this._lineCount++;
              };

              _proto._needsUpdateTextLayout = function _needsUpdateTextLayout(newTextArray) {
                if (this._layoutDirty || !this._textArray || !newTextArray) {
                  return true;
                }

                if (this._textArray.length !== newTextArray.length) {
                  return true;
                }

                for (var i = 0; i < this._textArray.length; i++) {
                  var oldItem = this._textArray[i];
                  var newItem = newTextArray[i];

                  if (oldItem.text !== newItem.text) {
                    return true;
                  } else {
                    var oldStyle = oldItem.style;
                    var newStyle = newItem.style;

                    if (oldStyle) {
                      if (newStyle) {
                        if (!!newStyle.outline !== !!oldStyle.outline) {
                          return true;
                        }

                        if (oldStyle.size !== newStyle.size || oldStyle.italic !== newStyle.italic || oldStyle.isImage !== newStyle.isImage) {
                          return true;
                        }

                        if (oldStyle.src !== newStyle.src || oldStyle.imageAlign !== newStyle.imageAlign || oldStyle.imageHeight !== newStyle.imageHeight || oldStyle.imageWidth !== newStyle.imageWidth || oldStyle.imageOffset !== newStyle.imageOffset) {
                          return true;
                        }
                      } else if (oldStyle.size || oldStyle.italic || oldStyle.isImage || oldStyle.outline) {
                        return true;
                      }
                    } else if (newStyle) {
                      if (newStyle.size || newStyle.italic || newStyle.isImage || newStyle.outline) {
                        return true;
                      }
                    }
                  }
                }

                return false;
              };

              _proto._addRichTextImageElement = function _addRichTextImageElement(richTextElement) {
                if (!richTextElement.style) {
                  return;
                }

                var style = richTextElement.style;
                var spriteFrameName = style.src;

                var spriteFrame = this._imageAtlas && spriteFrameName && this._imageAtlas.getSpriteFrame(spriteFrameName);

                if (!spriteFrame) {
                  warnID(4400);
                } else {
                  var segment = this._createImage(spriteFrame);

                  var sprite = 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;
                  }

                  segment.node.layer = this.node.layer;
                  this.node.addChild(segment.node);

                  this._segments.push(segment);

                  var spriteRect = spriteFrame.rect.clone();
                  var scaleFactor = 1;
                  var spriteWidth = spriteRect.width;
                  var spriteHeight = spriteRect.height;
                  var expectWidth = style.imageWidth || 0;
                  var expectHeight = style.imageHeight || 0;

                  if (expectHeight > 0) {
                    scaleFactor = expectHeight / spriteHeight;
                    spriteWidth *= scaleFactor;
                    spriteHeight *= scaleFactor;
                  } else {
                    scaleFactor = this._lineHeight / spriteHeight;
                    spriteWidth *= scaleFactor;
                    spriteHeight *= scaleFactor;
                  }

                  if (expectWidth > 0) {
                    spriteWidth = expectWidth;
                  }

                  if (this._maxWidth > 0) {
                    if (this._lineOffsetX + spriteWidth > this._maxWidth) {
                      this._updateLineInfo();
                    }

                    this._lineOffsetX += spriteWidth;
                  } else {
                    this._lineOffsetX += spriteWidth;

                    if (this._lineOffsetX > this._labelWidth) {
                      this._labelWidth = this._lineOffsetX;
                    }
                  }

                  segment.node._uiProps.uiTransformComp.setContentSize(spriteWidth, spriteHeight);

                  segment.lineCount = this._lineCount;
                  segment.clickHandler = '';
                  segment.clickParam = '';
                  var event = style.event;

                  if (event) {
                    segment.clickHandler = event.click;
                    segment.clickParam = event.param;
                  }
                }
              };

              _proto._updateRichText = function _updateRichText() {
                if (!this.enabledInHierarchy) {
                  return;
                }

                var newTextArray = _htmlTextParser.parse(this._string);

                if (!this._needsUpdateTextLayout(newTextArray)) {
                  this._textArray = newTextArray.slice();

                  this._updateLabelSegmentTextAttributes();

                  return;
                }

                this._textArray = newTextArray.slice();

                this._resetState();

                var lastEmptyLine = false;
                var label;

                for (var i = 0; i < this._textArray.length; ++i) {
                  var richTextElement = this._textArray[i];
                  var text = richTextElement.text;

                  if (text === undefined) {
                    continue;
                  }

                  if (text === '') {
                    if (richTextElement.style && richTextElement.style.isNewLine) {
                      this._updateLineInfo();

                      continue;
                    }

                    if (richTextElement.style && richTextElement.style.isImage && this._imageAtlas) {
                      this._addRichTextImageElement(richTextElement);

                      continue;
                    }
                  }

                  var multilineTexts = text.split('\n');

                  for (var j = 0; j < multilineTexts.length; ++j) {
                    var labelString = multilineTexts[j];

                    if (labelString === '') {
                      if (this._isLastComponentCR(text) && j === multilineTexts.length - 1) {
                        continue;
                      }

                      this._updateLineInfo();

                      lastEmptyLine = true;
                      continue;
                    }

                    lastEmptyLine = false;

                    if (this._maxWidth > 0) {
                      var labelWidth = this._measureText(i, labelString);

                      this._updateRichTextWithMaxWidth(labelString, labelWidth, i);

                      if (multilineTexts.length > 1 && j < multilineTexts.length - 1) {
                        this._updateLineInfo();
                      }
                    } else {
                      label = this._addLabelSegment(labelString, i);
                      this._lineOffsetX += label.node._uiProps.uiTransformComp.width;

                      if (this._lineOffsetX > this._labelWidth) {
                        this._labelWidth = this._lineOffsetX;
                      }

                      if (multilineTexts.length > 1 && j < multilineTexts.length - 1) {
                        this._updateLineInfo();
                      }
                    }
                  }
                }

                if (!lastEmptyLine) {
                  this._linesWidth.push(this._lineOffsetX);
                }

                if (this._maxWidth > 0) {
                  this._labelWidth = this._maxWidth;
                }

                this._labelHeight = (this._lineCount + BASELINE_RATIO) * this._lineHeight;

                this.node._uiProps.uiTransformComp.setContentSize(this._labelWidth, this._labelHeight);

                this._updateRichTextPosition();

                this._layoutDirty = false;
              };

              _proto._getFirstWordLen = function _getFirstWordLen(text, startIndex, textLen) {
                var character = text.charAt(startIndex);

                if (isUnicodeCJK(character) || isUnicodeSpace(character)) {
                  return 1;
                }

                var len = 1;

                for (var index = startIndex + 1; index < textLen; ++index) {
                  character = text.charAt(index);

                  if (isUnicodeSpace(character) || isUnicodeCJK(character)) {
                    break;
                  }

                  len++;
                }

                return len;
              };

              _proto._updateRichTextPosition = function _updateRichTextPosition() {
                var nextTokenX = 0;
                var nextLineIndex = 1;
                var totalLineCount = this._lineCount;
                var trans = this.node._uiProps.uiTransformComp;
                var anchorX = trans.anchorX;
                var anchorY = trans.anchorY;

                for (var i = 0; i < this._segments.length; ++i) {
                  var segment = this._segments[i];
                  var lineCount = segment.lineCount;

                  if (lineCount > nextLineIndex) {
                    nextTokenX = 0;
                    nextLineIndex = lineCount;
                  }

                  var lineOffsetX = this._labelWidth * (this._horizontalAlign * 0.5 - anchorX);

                  switch (this._horizontalAlign) {
                    case HorizontalTextAlignment.LEFT:
                      break;

                    case HorizontalTextAlignment.CENTER:
                      lineOffsetX -= this._linesWidth[lineCount - 1] / 2;
                      break;

                    case HorizontalTextAlignment.RIGHT:
                      lineOffsetX -= this._linesWidth[lineCount - 1];
                      break;
                  }

                  var pos = segment.node.position;
                  segment.node.setPosition(nextTokenX + lineOffsetX, this._lineHeight * (totalLineCount - lineCount) - this._labelHeight * anchorY, pos.z);

                  if (lineCount === nextLineIndex) {
                    nextTokenX += segment.node._uiProps.uiTransformComp.width;
                  }

                  var sprite = segment.node.getComponent(Sprite);

                  if (sprite) {
                    var position = segment.node.position.clone();
                    var lineHeightSet = this._lineHeight;
                    var lineHeightReal = this._lineHeight * (1 + BASELINE_RATIO);

                    switch (segment.node._uiProps.uiTransformComp.anchorY) {
                      case 1:
                        position.y += lineHeightSet + (lineHeightReal - lineHeightSet) / 2;
                        break;

                      case 0.5:
                        position.y += lineHeightReal / 2;
                        break;

                      default:
                        position.y += (lineHeightReal - lineHeightSet) / 2;
                        break;
                    }

                    if (segment.imageOffset) {
                      var offsets = segment.imageOffset.split(',');

                      if (offsets.length === 1 && offsets[0]) {
                        var offsetY = parseFloat(offsets[0]);
                        if (Number.isInteger(offsetY)) position.y += offsetY;
                      } else if (offsets.length === 2) {
                        var offsetX = parseFloat(offsets[0]);

                        var _offsetY = parseFloat(offsets[1]);

                        if (Number.isInteger(offsetX)) position.x += offsetX;
                        if (Number.isInteger(_offsetY)) position.y += _offsetY;
                      }
                    }

                    segment.node.position = position;
                  }

                  var outline = segment.node.getComponent(LabelOutline);

                  if (outline) {
                    var _position = segment.node.position.clone();

                    _position.y -= outline.width;
                    segment.node.position = _position;
                  }
                }
              };

              _proto._convertLiteralColorValue = function _convertLiteralColorValue(color) {
                var colorValue = color.toUpperCase();

                if (Color[colorValue]) {
                  var colorUse = Color[colorValue];
                  return colorUse;
                } else {
                  var out = new Color();
                  return out.fromHEX(color);
                }
              };

              _proto._applyTextAttribute = function _applyTextAttribute(labelSeg) {
                var label = labelSeg.node.getComponent(Label);

                if (!label) {
                  return;
                }

                var index = labelSeg.styleIndex;
                var textStyle;

                if (this._textArray[index]) {
                  textStyle = this._textArray[index].style;
                }

                if (textStyle) {
                  label.color = this._convertLiteralColorValue(textStyle.color || 'white');
                  label.isBold = !!textStyle.bold;
                  label.isItalic = !!textStyle.italic;
                  label.isUnderline = !!textStyle.underline;

                  if (textStyle.outline) {
                    var labelOutline = labelSeg.node.getComponent(LabelOutline);

                    if (!labelOutline) {
                      labelOutline = labelSeg.node.addComponent(LabelOutline);
                    }

                    labelOutline.color = this._convertLiteralColorValue(textStyle.outline.color);
                    labelOutline.width = textStyle.outline.width;
                  }

                  label.fontSize = textStyle.size || this._fontSize;
                  labelSeg.clickHandler = '';
                  labelSeg.clickParam = '';
                  var event = textStyle.event;

                  if (event) {
                    labelSeg.clickHandler = event.click || '';
                    labelSeg.clickParam = event.param || '';
                  }
                } else {
                  label.fontSize = this._fontSize;
                }

                label.cacheMode = this._cacheMode;
                var isAsset = this._font instanceof Font;

                if (isAsset && !this._isSystemFontUsed) {
                  label.font = this._font;
                } else {
                  label.fontFamily = this._fontFamily;
                }

                label.useSystemFont = this._isSystemFontUsed;
                label.lineHeight = this._lineHeight;
                label.updateRenderData(true);
                var assembler = label._assembler;

                if (assembler) {
                  assembler.updateRenderData(label);
                }
              };

              _proto._applyLayer = function _applyLayer() {
                for (var _iterator3 = _createForOfIteratorHelperLoose(this._segments), _step3; !(_step3 = _iterator3()).done;) {
                  var seg = _step3.value;
                  seg.node.layer = this.node.layer;
                }
              };

              _createClass(RichText, [{
                key: "string",
                get: function get() {
                  return this._string;
                },
                set: function set(value) {
                  if (this._string === value) {
                    return;
                  }

                  this._string = value;

                  this._updateRichTextStatus();
                }
              }, {
                key: "horizontalAlign",
                get: function get() {
                  return this._horizontalAlign;
                },
                set: function set(value) {
                  if (this.horizontalAlign === value) {
                    return;
                  }

                  this._horizontalAlign = value;
                  this._layoutDirty = true;

                  this._updateRichTextStatus();
                }
              }, {
                key: "fontSize",
                get: function get() {
                  return this._fontSize;
                },
                set: function set(value) {
                  if (this._fontSize === value) {
                    return;
                  }

                  this._fontSize = value;
                  this._layoutDirty = true;

                  this._updateRichTextStatus();
                }
              }, {
                key: "fontFamily",
                get: function get() {
                  return this._fontFamily;
                },
                set: function set(value) {
                  if (this._fontFamily === value) return;
                  this._fontFamily = value;
                  this._layoutDirty = true;

                  this._updateRichTextStatus();
                }
              }, {
                key: "font",
                get: function get() {
                  return this._font;
                },
                set: function set(value) {
                  if (this._font === value) {
                    return;
                  }

                  this._font = value;
                  this._layoutDirty = true;

                  if (this._font) {

                    this.useSystemFont = false;

                    this._onTTFLoaded();
                  } else {
                    this.useSystemFont = true;
                  }

                  this._updateRichTextStatus();
                }
              }, {
                key: "useSystemFont",
                get: function get() {
                  return this._isSystemFontUsed;
                },
                set: function set(value) {
                  if (this._isSystemFontUsed === value) {
                    return;
                  }

                  this._isSystemFontUsed = value;

                  this._layoutDirty = true;

                  this._updateRichTextStatus();
                }
              }, {
                key: "cacheMode",
                get: function get() {
                  return this._cacheMode;
                },
                set: function set(value) {
                  if (this._cacheMode === value) {
                    return;
                  }

                  this._cacheMode = value;

                  this._updateRichTextStatus();
                }
              }, {
                key: "maxWidth",
                get: function get() {
                  return this._maxWidth;
                },
                set: function set(value) {
                  if (this._maxWidth === value) {
                    return;
                  }

                  this._maxWidth = value;
                  this._layoutDirty = true;

                  this._updateRichTextStatus();
                }
              }, {
                key: "lineHeight",
                get: function get() {
                  return this._lineHeight;
                },
                set: function set(value) {
                  if (this._lineHeight === value) {
                    return;
                  }

                  this._lineHeight = value;
                  this._layoutDirty = true;

                  this._updateRichTextStatus();
                }
              }, {
                key: "imageAtlas",
                get: function get() {
                  return this._imageAtlas;
                },
                set: function set(value) {
                  if (this._imageAtlas === value) {
                    return;
                  }

                  this._imageAtlas = value;
                  this._layoutDirty = true;

                  this._updateRichTextStatus();
                }
              }, {
                key: "handleTouchEvent",
                get: function get() {
                  return this._handleTouchEvent;
                },
                set: function set(value) {
                  if (this._handleTouchEvent === value) {
                    return;
                  }

                  this._handleTouchEvent = value;

                  if (this.enabledInHierarchy) {
                    if (this.handleTouchEvent) {
                      this._addEventListeners();
                    } else {
                      this._removeEventListeners();
                    }
                  }
                }
              }]);

              return RichText;
            }(UIComponent), _class3$o.HorizontalAlign = HorizontalTextAlignment, _class3$o.VerticalAlign = VerticalTextAlignment, _temp$Z), (_applyDecoratedDescriptor(_class2$X.prototype, "string", [multiline, _dec5$k], Object.getOwnPropertyDescriptor(_class2$X.prototype, "string"), _class2$X.prototype), _applyDecoratedDescriptor(_class2$X.prototype, "horizontalAlign", [_dec6$f, _dec7$d], Object.getOwnPropertyDescriptor(_class2$X.prototype, "horizontalAlign"), _class2$X.prototype), _applyDecoratedDescriptor(_class2$X.prototype, "fontSize", [_dec8$c], Object.getOwnPropertyDescriptor(_class2$X.prototype, "fontSize"), _class2$X.prototype), _applyDecoratedDescriptor(_class2$X.prototype, "fontFamily", [_dec9$a], Object.getOwnPropertyDescriptor(_class2$X.prototype, "fontFamily"), _class2$X.prototype), _applyDecoratedDescriptor(_class2$X.prototype, "font", [_dec10$9, _dec11$8], Object.getOwnPropertyDescriptor(_class2$X.prototype, "font"), _class2$X.prototype), _applyDecoratedDescriptor(_class2$X.prototype, "useSystemFont", [_dec12$8], Object.getOwnPropertyDescriptor(_class2$X.prototype, "useSystemFont"), _class2$X.prototype), _applyDecoratedDescriptor(_class2$X.prototype, "cacheMode", [_dec13$7, _dec14$7], Object.getOwnPropertyDescriptor(_class2$X.prototype, "cacheMode"), _class2$X.prototype), _applyDecoratedDescriptor(_class2$X.prototype, "maxWidth", [_dec15$7], Object.getOwnPropertyDescriptor(_class2$X.prototype, "maxWidth"), _class2$X.prototype), _applyDecoratedDescriptor(_class2$X.prototype, "lineHeight", [_dec16$7], Object.getOwnPropertyDescriptor(_class2$X.prototype, "lineHeight"), _class2$X.prototype), _applyDecoratedDescriptor(_class2$X.prototype, "imageAtlas", [_dec17$6, _dec18$6], Object.getOwnPropertyDescriptor(_class2$X.prototype, "imageAtlas"), _class2$X.prototype), _applyDecoratedDescriptor(_class2$X.prototype, "handleTouchEvent", [_dec19$6], Object.getOwnPropertyDescriptor(_class2$X.prototype, "handleTouchEvent"), _class2$X.prototype), _descriptor$N = _applyDecoratedDescriptor(_class2$X.prototype, "_lineHeight", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 40;
              }
            }), _descriptor2$z = _applyDecoratedDescriptor(_class2$X.prototype, "_string", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return '<color=#00ff00>Rich</color><color=#0fffff>Text</color>';
              }
            }), _descriptor3$n = _applyDecoratedDescriptor(_class2$X.prototype, "_horizontalAlign", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return HorizontalTextAlignment.LEFT;
              }
            }), _descriptor4$k = _applyDecoratedDescriptor(_class2$X.prototype, "_fontSize", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 40;
              }
            }), _descriptor5$g = _applyDecoratedDescriptor(_class2$X.prototype, "_maxWidth", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor6$a = _applyDecoratedDescriptor(_class2$X.prototype, "_fontFamily", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 'Arial';
              }
            }), _descriptor7$8 = _applyDecoratedDescriptor(_class2$X.prototype, "_font", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor8$8 = _applyDecoratedDescriptor(_class2$X.prototype, "_isSystemFontUsed", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _descriptor9$7 = _applyDecoratedDescriptor(_class2$X.prototype, "_userDefinedFont", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor10$7 = _applyDecoratedDescriptor(_class2$X.prototype, "_cacheMode", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return CacheMode.NONE;
              }
            }), _descriptor11$6 = _applyDecoratedDescriptor(_class2$X.prototype, "_imageAtlas", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor12$5 = _applyDecoratedDescriptor(_class2$X.prototype, "_handleTouchEvent", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            })), _class2$X)) || _class$12) || _class$12) || _class$12) || _class$12) || _class$12));

            var _dec$12, _dec2$E, _dec3$w, _dec4$q, _class$13, _temp$_;
            var UIMeshRenderer = function (v) { return exports({ UIMeshRenderer: v, UIModelComponent: v }), v; }((_dec$12 = ccclass('cc.UIMeshRenderer'), _dec2$E = help(), _dec3$w = executionOrder(110), _dec4$q = menu(), _dec$12(_class$13 = _dec2$E(_class$13 = _dec3$w(_class$13 = _dec4$q(_class$13 = (_temp$_ = function (_UIComponent) {
              _inheritsLoose(UIMeshRenderer, _UIComponent);

              function UIMeshRenderer() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _UIComponent.call.apply(_UIComponent, [this].concat(args)) || this;
                _this._models = null;
                _this._modelComponent = null;
                return _this;
              }

              var _proto = UIMeshRenderer.prototype;

              _proto.onLoad = function onLoad() {
                if (!this.node._uiProps.uiTransformComp) {
                  this.node.addComponent('cc.UITransform');
                }

                this._modelComponent = this.getComponent('cc.RenderableComponent');

                if (!this._modelComponent) {
                  console.warn("node '" + (this.node && this.node.name) + "' doesn't have any renderable component");
                  return;
                }

                this._models = this._modelComponent._collectModels();
              };

              _proto.onEnable = function onEnable() {
                _UIComponent.prototype.onEnable.call(this);
              };

              _proto.onDisable = function onDisable() {
                _UIComponent.prototype.onDisable.call(this);
              };

              _proto.onDestroy = function onDestroy() {
                _UIComponent.prototype.onDestroy.call(this);

                this._modelComponent = this.getComponent('cc.RenderableComponent');

                if (!this._modelComponent) {
                  return;
                }

                this._modelComponent._sceneGetter = null;
                this._models = null;
              };

              _proto.updateAssembler = function updateAssembler(render) {
                if (this._models) {
                  this._modelComponent._detachFromScene();

                  for (var _iterator = _createForOfIteratorHelperLoose(this._models), _step; !(_step = _iterator()).done;) {
                    var m = _step.value;
                    render.commitModel.call(render, this, m, this._modelComponent.material);
                  }

                  return true;
                }

                return false;
              };

              _proto.update = function update() {
                this._fitUIRenderQueue();
              };

              _proto._fitUIRenderQueue = function _fitUIRenderQueue() {
                if (!this._modelComponent) {
                  return;
                }

                var matNum = this._modelComponent.sharedMaterials.length;

                for (var i = 0; i < matNum; i++) {
                  var material = this._modelComponent.getMaterialInstance(i);

                  if (material == null) {
                    continue;
                  }

                  var passes = material.passes;
                  var passNum = passes.length;

                  for (var j = 0; j < passNum; j++) {
                    var pass = passes[j];
                    pass._priority = RenderPriority.MAX - 11;

                    if (!pass.blendState.targets[0].blend) {
                      material.overridePipelineStates({
                        blendState: {
                          targets: [{
                            blend: true
                          }]
                        }
                      }, j);
                    }
                  }
                }
              };

              _createClass(UIMeshRenderer, [{
                key: "modelComponent",
                get: function get() {
                  return this._modelComponent;
                }
              }]);

              return UIMeshRenderer;
            }(UIComponent), _temp$_)) || _class$13) || _class$13) || _class$13) || _class$13));

            var MeshBuffer = exports('MeshBuffer', function () {
              function MeshBuffer(batcher) {
                this.vData = null;
                this.iData = null;
                this.byteStart = 0;
                this.byteOffset = 0;
                this.indicesStart = 0;
                this.indicesOffset = 0;
                this.vertexStart = 0;
                this.vertexOffset = 0;
                this.lastByteOffset = 1;
                this._attributes = null;
                this._vertexBuffers = [];
                this._indexBuffer = null;
                this._iaInfo = null;
                this._batcher = void 0;
                this._dirty = false;
                this._vertexFormatBytes = 0;
                this._initVDataCount = 0;
                this._initIDataCount = 256 * 6;
                this._outOfCallback = null;
                this._hInputAssemblers = [];
                this._nextFreeIAHandle = 0;
                this._batcher = batcher;
              }

              var _proto = MeshBuffer.prototype;

              _proto.initialize = function initialize(attrs, outOfCallback) {
                this._outOfCallback = outOfCallback;
                var formatBytes = getComponentPerVertex(attrs);
                this._vertexFormatBytes = formatBytes * Float32Array.BYTES_PER_ELEMENT;
                this._initVDataCount = 256 * this._vertexFormatBytes;
                var vbStride = Float32Array.BYTES_PER_ELEMENT * formatBytes;

                if (!this.vertexBuffers.length) {
                  this.vertexBuffers.push(this._batcher.device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, vbStride, vbStride)));
                }

                var ibStride = Uint16Array.BYTES_PER_ELEMENT;

                if (!this.indexBuffer) {
                  this._indexBuffer = this._batcher.device.createBuffer(new BufferInfo(BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, ibStride, ibStride));
                }

                this._attributes = attrs;
                this._iaInfo = new InputAssemblerInfo(this.attributes, this.vertexBuffers, this.indexBuffer);

                this._reallocBuffer();
              };

              _proto.request = function request(vertexCount, indicesCount) {
                if (vertexCount === void 0) {
                  vertexCount = 4;
                }

                if (indicesCount === void 0) {
                  indicesCount = 6;
                }

                this.lastByteOffset = this.byteOffset;
                var byteOffset = this.byteOffset + vertexCount * this._vertexFormatBytes;
                var indicesOffset = this.indicesOffset + indicesCount;

                if (vertexCount + this.vertexOffset > 65535) {
                  if (this._outOfCallback) {
                    this._outOfCallback.call(this._batcher, vertexCount, indicesCount);
                  }

                  return false;
                }

                var byteLength = this.vData.byteLength;
                var indicesLength = this.iData.length;

                if (byteOffset > byteLength || indicesOffset > indicesLength) {
                  while (byteLength < byteOffset || indicesLength < indicesOffset) {
                    this._initVDataCount *= 2;
                    this._initIDataCount *= 2;
                    byteLength = this._initVDataCount * 4;
                    indicesLength = this._initIDataCount;
                  }

                  this._reallocBuffer();
                }

                this.vertexOffset += vertexCount;
                this.indicesOffset += indicesCount;
                this.byteOffset = byteOffset;
                this._dirty = true;
                return true;
              };

              _proto.reset = function reset() {
                this.byteStart = 0;
                this.byteOffset = 0;
                this.indicesStart = 0;
                this.indicesOffset = 0;
                this.vertexStart = 0;
                this.vertexOffset = 0;
                this.lastByteOffset = 0;
                this._nextFreeIAHandle = 0;
                this._dirty = false;
              };

              _proto.destroy = function destroy() {
                this._attributes = null;
                this.vertexBuffers[0].destroy();
                this.vertexBuffers.length = 0;
                this.indexBuffer.destroy();
                this._indexBuffer = null;

                for (var i = 0; i < this._hInputAssemblers.length; i++) {
                  IAPool.free(this._hInputAssemblers[i]);
                }

                this._hInputAssemblers.length = 0;
              };

              _proto.recordBatch = function recordBatch() {
                var vCount = this.indicesOffset - this.indicesStart;

                if (!vCount) {
                  return NULL_HANDLE;
                }

                if (this._hInputAssemblers.length <= this._nextFreeIAHandle) {
                  this._hInputAssemblers.push(IAPool.alloc(this._batcher.device, this._iaInfo));
                }

                var hIA = this._hInputAssemblers[this._nextFreeIAHandle++];
                var ia = IAPool.get(hIA);
                ia.firstIndex = this.indicesStart;
                ia.indexCount = vCount;
                return hIA;
              };

              _proto.uploadBuffers = function uploadBuffers() {
                if (this.byteOffset === 0 || !this._dirty) {
                  return;
                }

                var verticesData = new Float32Array(this.vData.buffer, 0, this.byteOffset >> 2);
                var indicesData = new Uint16Array(this.iData.buffer, 0, this.indicesOffset);

                if (this.byteOffset > this.vertexBuffers[0].size) {
                  this.vertexBuffers[0].resize(this.byteOffset);
                }

                this.vertexBuffers[0].update(verticesData);

                if (this.indicesOffset * 2 > this.indexBuffer.size) {
                  this.indexBuffer.resize(this.indicesOffset * 2);
                }

                this.indexBuffer.update(indicesData);
                this._dirty = false;
              };

              _proto._reallocBuffer = function _reallocBuffer() {
                this._reallocVData(true);

                this._reallocIData(true);
              };

              _proto._reallocVData = function _reallocVData(copyOldData) {
                var oldVData;

                if (this.vData) {
                  oldVData = new Uint8Array(this.vData.buffer);
                }

                this.vData = new Float32Array(this._initVDataCount);

                if (oldVData && copyOldData) {
                  var newData = new Uint8Array(this.vData.buffer);

                  for (var i = 0, l = oldVData.length; i < l; i++) {
                    newData[i] = oldVData[i];
                  }
                }
              };

              _proto._reallocIData = function _reallocIData(copyOldData) {
                var oldIData = this.iData;
                this.iData = new Uint16Array(this._initIDataCount);

                if (oldIData && copyOldData) {
                  var iData = this.iData;

                  for (var i = 0, l = oldIData.length; i < l; i++) {
                    iData[i] = oldIData[i];
                  }
                }
              };

              _createClass(MeshBuffer, [{
                key: "attributes",
                get: function get() {
                  return this._attributes;
                }
              }, {
                key: "vertexBuffers",
                get: function get() {
                  return this._vertexBuffers;
                }
              }, {
                key: "indexBuffer",
                get: function get() {
                  return this._indexBuffer;
                }
              }, {
                key: "vertexFormatBytes",
                get: function get() {
                  return this._vertexFormatBytes;
                }
              }]);

              return MeshBuffer;
            }());
            MeshBuffer.OPACITY_OFFSET = 8;

            var UI_VIS_FLAG = Layers.Enum.NONE | Layers.Enum.UI_3D;
            var DrawBatch2D = exports('UIDrawBatch', function () {
              function DrawBatch2D() {
                this.bufferBatch = null;
                this.camera = null;
                this.renderScene = null;
                this.model = null;
                this.texture = null;
                this.sampler = null;
                this.useLocalData = null;
                this.isStatic = false;
                this.textureHash = 0;
                this.samplerHash = 0;
                this._handle = NULL_HANDLE;
                this._passes = [];
                this._handle = BatchPool2D.alloc();
                BatchPool2D.set(this._handle, BatchView2D.VIS_FLAGS, UI_VIS_FLAG);
                BatchPool2D.set(this._handle, BatchView2D.INPUT_ASSEMBLER, NULL_HANDLE);
                BatchPool2D.set(this._handle, BatchView2D.DESCRIPTOR_SET, NULL_HANDLE);
              }

              var _proto = DrawBatch2D.prototype;

              _proto.destroy = function destroy(ui) {
                if (this._handle) {
                  var length = this.passes.length;

                  for (var i = 0; i < length; i++) {
                    this.passes[i]._destroyHandle();
                  }

                  this._passes = [];
                  BatchPool2D.free(this._handle);
                  this._handle = NULL_HANDLE;
                }
              };

              _proto.clear = function clear() {
                this.bufferBatch = null;
                this.hInputAssembler = NULL_HANDLE;
                this.hDescriptorSet = NULL_HANDLE;
                this.camera = null;
                this.texture = null;
                this.sampler = null;
                this.model = null;
                this.isStatic = false;
                this.useLocalData = null;
                this.visFlags = UI_VIS_FLAG;
              };

              _proto.fillPasses = function fillPasses(mat, dss, dssHash, bs, bsHash, patches) {
                if (mat) {
                  var passes = mat.passes;

                  if (!passes) {
                    return;
                  }

                  BatchPool2D.set(this._handle, BatchView2D.PASS_COUNT, passes.length);
                  var passOffset = BatchView2D.PASS_0;
                  var shaderOffset = BatchView2D.SHADER_0;
                  var hashFactor = 0;

                  for (var i = 0; i < passes.length; i++, passOffset++, shaderOffset++) {
                    if (!this._passes[i]) {
                      this._passes[i] = new Pass(legacyCC.director.root);
                      this._passes[i]._handle = PassPool.alloc();
                    }

                    var mtlPass = passes[i];
                    var passInUse = this._passes[i];

                    if (!dss) {
                      dss = mtlPass.depthStencilState;
                      dssHash = 0;
                    }

                    if (!bs) {
                      bs = mtlPass.blendState;
                      bsHash = 0;
                    }

                    if (bsHash === -1) {
                      bsHash = 0;
                    }

                    hashFactor = dssHash << 16 | bsHash;
                    mtlPass.update();

                    passInUse._initPassFromTarget(mtlPass, dss, bs, hashFactor);

                    BatchPool2D.set(this._handle, passOffset, passInUse.handle);
                    BatchPool2D.set(this._handle, shaderOffset, passInUse.getShaderVariant(patches));
                  }
                }
              };

              _createClass(DrawBatch2D, [{
                key: "handle",
                get: function get() {
                  return this._handle;
                }
              }, {
                key: "hInputAssembler",
                get: function get() {
                  return BatchPool2D.get(this._handle, BatchView2D.INPUT_ASSEMBLER);
                },
                set: function set(handle) {
                  BatchPool2D.set(this._handle, BatchView2D.INPUT_ASSEMBLER, handle);
                }
              }, {
                key: "hDescriptorSet",
                get: function get() {
                  return BatchPool2D.get(this._handle, BatchView2D.DESCRIPTOR_SET);
                },
                set: function set(handle) {
                  BatchPool2D.set(this._handle, BatchView2D.DESCRIPTOR_SET, handle);
                }
              }, {
                key: "visFlags",
                get: function get() {
                  return BatchPool2D.get(this._handle, BatchView2D.VIS_FLAGS);
                },
                set: function set(vis) {
                  BatchPool2D.set(this._handle, BatchView2D.VIS_FLAGS, vis);
                }
              }, {
                key: "passes",
                get: function get() {
                  return this._passes;
                }
              }]);

              return DrawBatch2D;
            }());

            var _dec$13, _dec2$F, _dec3$x, _dec4$r, _dec5$l, _class$14, _class2$Y, _temp$$;
            var UIStaticBatch = function (v) { return exports({ UIStaticBatch: v, UIStaticBatchComponent: v }), v; }((_dec$13 = ccclass('cc.UIStaticBatch'), _dec2$F = help(), _dec3$x = menu(), _dec4$r = executionOrder(110), _dec5$l = visible(), _dec$13(_class$14 = _dec2$F(_class$14 = _dec3$x(_class$14 = _dec4$r(_class$14 = (_class2$Y = (_temp$$ = function (_Renderable2D) {
              _inheritsLoose(UIStaticBatch, _Renderable2D);

              function UIStaticBatch() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Renderable2D.call.apply(_Renderable2D, [this].concat(args)) || this;
                _this._init = false;
                _this._meshBuffer = null;
                _this._dirty = true;
                _this._lastMeshBuffer = null;
                _this._uiDrawBatchList = [];
                return _this;
              }

              var _proto = UIStaticBatch.prototype;

              _proto.onLoad = function onLoad() {
                var ui = this._getBatcher();

                if (!ui) {
                  return;
                }

                var attr = vfmtPosUvColor;
                var buffer = new MeshBuffer(ui);
                buffer.initialize(attr, this._arrivalMaxBuffer.bind(this));
                this._meshBuffer = buffer;
              };

              _proto.onDestroy = function onDestroy() {
                _Renderable2D.prototype.onDestroy.call(this);

                this._clearData();

                if (this._meshBuffer) {
                  this._meshBuffer.destroy();

                  this._meshBuffer = null;
                }
              };

              _proto.updateAssembler = function updateAssembler(render) {
                render.currIsStatic = true;

                if (this._dirty) {
                  render.finishMergeBatches();
                  this._lastMeshBuffer = render.currBufferBatch;
                  render.currBufferBatch = this._meshBuffer;
                  render.currStaticRoot = this;
                }

                if (this._init) {
                  render.finishMergeBatches();
                  render.commitStaticBatch(this);
                }
              };

              _proto.postUpdateAssembler = function postUpdateAssembler(render) {
                if (this._dirty) {
                  render.finishMergeBatches();
                  render.currBufferBatch = this._lastMeshBuffer;
                  render.currStaticRoot = null;
                  this._dirty = false;
                  this._init = true;
                  this.node._static = true;

                  this._meshBuffer.uploadBuffers();
                }

                render.currIsStatic = false;
              };

              _proto.markAsDirty = function markAsDirty() {
                if (!this._getBatcher()) {
                  return;
                }

                this.node._static = false;
                this._dirty = true;
                this._init = false;

                this._clearData();
              };

              _proto._requireDrawBatch = function _requireDrawBatch() {
                var batch = new DrawBatch2D();
                batch.isStatic = true;

                this._uiDrawBatchList.push(batch);

                return batch;
              };

              _proto._clearData = function _clearData() {
                if (this._meshBuffer) {
                  this._meshBuffer.reset();

                  var ui = this._getBatcher();

                  for (var i = 0; i < this._uiDrawBatchList.length; i++) {
                    var element = this._uiDrawBatchList[i];
                    element.destroy(ui);
                  }
                }

                this._uiDrawBatchList.length = 0;
                this._init = false;
              };

              _proto._getBatcher = function _getBatcher() {
                if (director.root && director.root.batcher2D) {
                  return director.root.batcher2D;
                }

                warnID(9301);
                return null;
              };

              _proto._arrivalMaxBuffer = function _arrivalMaxBuffer() {
                var ui = this._getBatcher();

                if (ui) {
                  ui.autoMergeBatches();
                }

                warnID(9300);
              };

              _createClass(UIStaticBatch, [{
                key: "color",
                get: function get() {
                  return this._color;
                },
                set: function set(value) {
                  if (this._color === value) {
                    return;
                  }

                  this._color.set(value);
                }
              }, {
                key: "drawBatchList",
                get: function get() {
                  return this._uiDrawBatchList;
                }
              }]);

              return UIStaticBatch;
            }(Renderable2D), _temp$$), (_applyDecoratedDescriptor(_class2$Y.prototype, "color", [override, _dec5$l], Object.getOwnPropertyDescriptor(_class2$Y.prototype, "color"), _class2$Y.prototype)), _class2$Y)) || _class$14) || _class$14) || _class$14) || _class$14));

            var _dec$14, _dec2$G, _dec3$y, _dec4$s, _dec5$m, _dec6$g, _dec7$e, _dec8$d, _class$15, _class2$Z, _descriptor$O, _descriptor2$A, _descriptor3$o, _temp$10;
            var LabelShadow = exports('LabelShadow', (_dec$14 = ccclass('cc.LabelShadow'), _dec2$G = help(), _dec3$y = executionOrder(110), _dec4$s = menu(), _dec5$m = requireComponent(Label), _dec6$g = tooltip(), _dec7$e = tooltip(), _dec8$d = tooltip(), _dec$14(_class$15 = _dec2$G(_class$15 = _dec3$y(_class$15 = _dec4$s(_class$15 = _dec5$m(_class$15 = executeInEditMode(_class$15 = (_class2$Z = (_temp$10 = function (_Component) {
              _inheritsLoose(LabelShadow, _Component);

              function LabelShadow() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Component.call.apply(_Component, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "_color", _descriptor$O, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_offset", _descriptor2$A, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_blur", _descriptor3$o, _assertThisInitialized(_this));

                return _this;
              }

              var _proto = LabelShadow.prototype;

              _proto.onEnable = function onEnable() {
                this._updateRenderData();
              };

              _proto.onDisable = function onDisable() {
                this._updateRenderData();
              };

              _proto._updateRenderData = function _updateRenderData() {
                var label = this.node.getComponent(Label);

                if (label) {
                  label.updateRenderData(true);
                }
              };

              _createClass(LabelShadow, [{
                key: "color",
                get: function get() {
                  return this._color;
                },
                set: function set(value) {
                  if (this._color === value) {
                    return;
                  }

                  this._color.set(value);

                  this._updateRenderData();
                }
              }, {
                key: "offset",
                get: function get() {
                  return this._offset;
                },
                set: function set(value) {
                  this._offset = value;

                  this._updateRenderData();
                }
              }, {
                key: "blur",
                get: function get() {
                  return this._blur;
                },
                set: function set(value) {
                  this._blur = value;

                  this._updateRenderData();
                }
              }]);

              return LabelShadow;
            }(Component), _temp$10), (_descriptor$O = _applyDecoratedDescriptor(_class2$Z.prototype, "_color", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new Color(0, 0, 0, 255);
              }
            }), _descriptor2$A = _applyDecoratedDescriptor(_class2$Z.prototype, "_offset", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new Vec2(2, 2);
              }
            }), _descriptor3$o = _applyDecoratedDescriptor(_class2$Z.prototype, "_blur", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 2;
              }
            }), _applyDecoratedDescriptor(_class2$Z.prototype, "color", [_dec6$g], Object.getOwnPropertyDescriptor(_class2$Z.prototype, "color"), _class2$Z.prototype), _applyDecoratedDescriptor(_class2$Z.prototype, "offset", [_dec7$e], Object.getOwnPropertyDescriptor(_class2$Z.prototype, "offset"), _class2$Z.prototype), _applyDecoratedDescriptor(_class2$Z.prototype, "blur", [_dec8$d], Object.getOwnPropertyDescriptor(_class2$Z.prototype, "blur"), _class2$Z.prototype)), _class2$Z)) || _class$15) || _class$15) || _class$15) || _class$15) || _class$15) || _class$15));

            var _dec$15, _dec2$H, _dec3$z, _dec4$t, _class$16, _class2$_, _descriptor$P, _temp$11;
            var UIOpacity = function (v) { return exports({ UIOpacity: v, UIOpacityComponent: v }), v; }((_dec$15 = ccclass('cc.UIOpacity'), _dec2$H = help(), _dec3$z = executionOrder(110), _dec4$t = menu(), _dec$15(_class$16 = _dec2$H(_class$16 = _dec3$z(_class$16 = _dec4$t(_class$16 = executeInEditMode(_class$16 = (_class2$_ = (_temp$11 = function (_Component) {
              _inheritsLoose(UIOpacity, _Component);

              function UIOpacity() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Component.call.apply(_Component, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "_opacity", _descriptor$P, _assertThisInitialized(_this));

                return _this;
              }

              var _proto = UIOpacity.prototype;

              _proto.onEnable = function onEnable() {
                this.node._uiProps.localOpacity = this._opacity / 255;
              };

              _proto.onDisable = function onDisable() {
                this.node._uiProps.localOpacity = 1;
              };

              _createClass(UIOpacity, [{
                key: "opacity",
                get: function get() {
                  return this._opacity;
                },
                set: function set(value) {
                  if (this._opacity === value) {
                    return;
                  }

                  value = clampf(value, 0, 255);
                  this._opacity = value;
                  this.node._uiProps.localOpacity = value / 255;
                }
              }]);

              return UIOpacity;
            }(Component), _temp$11), (_applyDecoratedDescriptor(_class2$_.prototype, "opacity", [editable], Object.getOwnPropertyDescriptor(_class2$_.prototype, "opacity"), _class2$_.prototype), _descriptor$P = _applyDecoratedDescriptor(_class2$_.prototype, "_opacity", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 255;
              }
            })), _class2$_)) || _class$16) || _class$16) || _class$16) || _class$16) || _class$16));

            legacyCC.MaskComponent = Mask;
            js.setClassAlias(Mask, 'cc.MaskComponent');
            legacyCC.LabelComponent = Label;
            js.setClassAlias(Label, 'cc.LabelComponent');
            legacyCC.LabelOutlineComponent = LabelOutline;
            js.setClassAlias(LabelOutline, 'cc.LabelOutlineComponent');
            legacyCC.RichTextComponent = RichText;
            js.setClassAlias(RichText, 'cc.RichTextComponent');
            legacyCC.SpriteComponent = Sprite;
            js.setClassAlias(Sprite, 'cc.SpriteComponent');
            legacyCC.UIModelComponent = UIMeshRenderer;
            js.setClassAlias(UIMeshRenderer, 'cc.UIModelComponent');
            legacyCC.GraphicsComponent = Graphics;
            js.setClassAlias(Graphics, 'cc.GraphicsComponent');
            js.setClassAlias(UIStaticBatch, 'cc.UIStaticBatchComponent');
            js.setClassAlias(UIOpacity, 'cc.UIOpacityComponent');

            var Aim = function Aim(i, x, y) {
              this.i = void 0;
              this.x = void 0;
              this.y = void 0;
              this.prev = null;
              this.next = null;
              this.z = 0;
              this.prevZ = null;
              this.nextZ = null;
              this.steiner = false;
              this.i = i;
              this.x = x;
              this.y = y;
            };

            function linkedList(datas, start, end, dim, clockwise) {
              var i = 0;
              var last = null;

              if (clockwise === signedArea(datas, start, end, dim) > 0) {
                for (i = start; i < end; i += dim) {
                  last = insertNode(i, datas[i], datas[i + 1], last);
                }
              } else {
                for (i = end - dim; i >= start; i -= dim) {
                  last = insertNode(i, datas[i], datas[i + 1], last);
                }
              }

              if (last && equals$1(last, last.next)) {
                removeNode(last);
                last = last.next;
              }

              return last;
            }

            function filterPoints(start, end) {
              if (end === void 0) {
                end = null;
              }

              if (!start) {
                return start;
              }

              if (!end) {
                end = start;
              }

              var p = start;
              var again = false;

              do {
                again = false;

                if (!p.steiner && (equals$1(p, p.next) || area(p.prev, p, p.next) === 0)) {
                  removeNode(p);
                  p = end = p.prev;

                  if (p === p.next) {
                    return null;
                  }

                  again = true;
                } else {
                  p = p.next;
                }
              } while (again || p !== end);

              return end;
            }

            function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
              if (pass === void 0) {
                pass = 0;
              }

              if (!ear) {
                return;
              }

              if (!pass && size) {
                indexCurve(ear, minX, minY, size);
              }

              var stop = ear;
              var prev = null;
              var next = null;

              while (ear.prev !== ear.next) {
                prev = ear.prev;
                next = ear.next;

                if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
                  triangles.push(prev.i / dim);
                  triangles.push(ear.i / dim);
                  triangles.push(next.i / dim);
                  removeNode(ear);
                  ear = next.next;
                  stop = next.next;
                  continue;
                }

                ear = next;

                if (ear === stop) {
                  if (!pass) {
                    earcutLinked(filterPoints(ear), triangles, dim, minX, minY, size, 1);
                  } else if (pass === 1) {
                    ear = cureLocalIntersections(ear, triangles, dim);
                    earcutLinked(ear, triangles, dim, minX, minY, size, 2);
                  } else if (pass === 2) {
                    splitEarcut(ear, triangles, dim, minX, minY, size);
                  }

                  break;
                }
              }
            }

            function isEar(ear) {
              var a = ear.prev;
              var b = ear;
              var c = ear.next;

              if (area(a, b, c) >= 0) {
                return false;
              }

              var p = ear.next.next;

              while (p !== ear.prev) {
                if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) {
                  return false;
                }

                p = p.next;
              }

              return true;
            }

            function isEarHashed(ear, minX, minY, size) {
              var a = ear.prev;
              var b = ear;
              var c = ear.next;

              if (area(a, b, c) >= 0) {
                return false;
              }

              var minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x;
              var minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y;
              var maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x;
              var maxTY = a.y > b.y ? a.y > c.y ? a.y : c.y : b.y > c.y ? b.y : c.y;
              var minZ = zOrder(minTX, minTY, minX, minY, size);
              var maxZ = zOrder(maxTX, maxTY, minX, minY, size);
              var p = ear.nextZ;

              while (p && p.z <= maxZ) {
                if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) {
                  return false;
                }

                p = p.nextZ;
              }

              p = ear.prevZ;

              while (p && p.z >= minZ) {
                if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) {
                  return false;
                }

                p = p.prevZ;
              }

              return true;
            }

            function cureLocalIntersections(start, triangles, dim) {
              var p = start;

              do {
                var a = p.prev;
                var b = p.next.next;

                if (!equals$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) {
              var a = start;

              do {
                var b = a.next.next;

                while (b !== a.prev) {
                  if (a.i !== b.i && isValidDiagonal(a, b)) {
                    var c = splitPolygon(a, b);
                    a = filterPoints(a, a.next);
                    c = filterPoints(c, c.next);
                    earcutLinked(a, triangles, dim, minX, minY, size);
                    earcutLinked(c, triangles, dim, minX, minY, size);
                    return;
                  }

                  b = b.next;
                }

                a = a.next;
              } while (a !== start);
            }

            function eliminateHoles(datas, holeIndices, outerNode, dim) {
              var queue = [];
              var i = 0;
              var len = 0;
              var start = 0;
              var end = 0;
              var list = null;

              for (i = 0, len = holeIndices.length; i < len; i++) {
                start = holeIndices[i] * dim;
                end = i < len - 1 ? holeIndices[i + 1] * dim : datas.length;
                list = linkedList(datas, start, end, dim, false);

                if (!list) {
                  continue;
                }

                if (list === list.next) {
                  list.steiner = true;
                }

                queue.push(getLeftmost(list));
              }

              queue.sort(compareX);

              if (!outerNode) {
                return outerNode;
              }

              for (i = 0; i < queue.length; i++) {
                eliminateHole(queue[i], outerNode);
                outerNode = filterPoints(outerNode, outerNode.next);
              }

              return outerNode;
            }

            function compareX(a, b) {
              return a.x - b.x;
            }

            function eliminateHole(hole, outerNode) {
              outerNode = findHoleBridge(hole, outerNode);

              if (outerNode) {
                var b = splitPolygon(outerNode, hole);
                filterPoints(b, b.next);
              }
            }

            function findHoleBridge(hole, outerNode) {
              var p = outerNode;
              var hx = hole.x;
              var hy = hole.y;
              var qx = -Infinity;
              var m = null;

              do {
                if (hy <= p.y && hy >= p.next.y) {
                  var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);

                  if (x <= hx && x > qx) {
                    qx = x;

                    if (x === hx) {
                      if (hy === p.y) {
                        return p;
                      }

                      if (hy === p.next.y) {
                        return p.next;
                      }
                    }

                    m = p.x < p.next.x ? p : p.next;
                  }
                }

                p = p.next;
              } while (p !== outerNode);

              if (!m) {
                return null;
              }

              if (hx === qx) {
                return m.prev;
              }

              var stop = m;
              var mx = m.x;
              var my = m.y;
              var tanMin = Infinity;
              var tan;
              p = m.next;

              while (p !== stop) {
                if (hx >= p.x && p.x >= mx && pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
                  tan = Math.abs(hy - p.y) / (hx - p.x);

                  if ((tan < tanMin || tan === tanMin && p.x > m.x) && locallyInside(p, hole)) {
                    m = p;
                    tanMin = tan;
                  }
                }

                p = p.next;
              }

              return m;
            }

            function indexCurve(start, minX, minY, size) {
              var p = start;

              do {
                if (p.z === null) {
                  p.z = zOrder(p.x, p.y, minX, minY, size);
                }

                p.prevZ = p.prev;
                p.nextZ = p.next;
                p = p.next;
              } while (p !== start);

              p.prevZ.nextZ = null;
              p.prevZ = null;
              sortLinked(p);
            }

            function sortLinked(list) {
              var i = 0;
              var p = null;
              var q = null;
              var e = null;
              var tail = null;
              var numMerges = 0;
              var pSize = 0;
              var qSize = 0;
              var inSize = 1;

              do {
                p = list;
                list = null;
                tail = null;
                numMerges = 0;

                while (p) {
                  numMerges++;
                  q = p;
                  pSize = 0;

                  for (i = 0; i < inSize; i++) {
                    pSize++;
                    q = q.nextZ;

                    if (!q) {
                      break;
                    }
                  }

                  qSize = inSize;

                  while (pSize > 0 || qSize > 0 && q) {
                    if (pSize === 0) {
                      e = q;
                      q = q.nextZ;
                      qSize--;
                    } else if (qSize === 0 || !q) {
                      e = p;
                      p = p.nextZ;
                      pSize--;
                    } else if (p.z <= q.z) {
                      e = p;
                      p = p.nextZ;
                      pSize--;
                    } else {
                      e = q;
                      q = q.nextZ;
                      qSize--;
                    }

                    if (tail) {
                      tail.nextZ = e;
                    } else {
                      list = e;
                    }

                    e.prevZ = tail;
                    tail = e;
                  }

                  p = q;
                }

                tail.nextZ = null;
                inSize *= 2;
              } while (numMerges > 1);

              return list;
            }

            function zOrder(x, y, minX, minY, size) {
              x = 32767 * (x - minX) / size;
              y = 32767 * (y - minY) / size;
              x = (x | x << 8) & 0x00FF00FF;
              x = (x | x << 4) & 0x0F0F0F0F;
              x = (x | x << 2) & 0x33333333;
              x = (x | x << 1) & 0x55555555;
              y = (y | y << 8) & 0x00FF00FF;
              y = (y | y << 4) & 0x0F0F0F0F;
              y = (y | y << 2) & 0x33333333;
              y = (y | y << 1) & 0x55555555;
              return x | y << 1;
            }

            function getLeftmost(start) {
              var p = start;
              var leftmost = start;

              do {
                if (p.x < leftmost.x) {
                  leftmost = p;
                }

                p = p.next;
              } while (p !== start);

              return leftmost;
            }

            function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
              return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
            }

            function isValidDiagonal(a, b) {
              return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
            }

            function area(p, q, r) {
              return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
            }

            function equals$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(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
            }

            function intersectsPolygon(a, b) {
              var p = a;

              do {
                if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && intersects(p, p.next, a, b)) {
                  return true;
                }

                p = p.next;
              } while (p !== a);

              return false;
            }

            function locallyInside(a, b) {
              return area(a.prev, a, a.next) < 0 ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
            }

            function middleInside(a, b) {
              var p = a;
              var inside = false;
              var px = (a.x + b.x) / 2;
              var py = (a.y + b.y) / 2;

              do {
                if (p.y > py !== p.next.y > py && px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x) {
                  inside = !inside;
                }

                p = p.next;
              } while (p !== a);

              return inside;
            }

            function splitPolygon(a, b) {
              var a2 = new Aim(a.i, a.x, a.y);
              var b2 = new Aim(b.i, b.x, b.y);
              var an = a.next;
              var bp = b.prev;
              a.next = b;
              b.prev = a;
              a2.next = an;
              an.prev = a2;
              b2.next = a2;
              a2.prev = b2;
              bp.next = b2;
              b2.prev = bp;
              return b2;
            }

            function insertNode(i, x, y, last) {
              var p = new Aim(i, x, y);

              if (!last) {
                p.prev = p;
                p.next = p;
              } else {
                p.next = last.next;
                p.prev = last;
                last.next.prev = p;
                last.next = p;
              }

              return p;
            }

            function removeNode(p) {
              p.next.prev = p.prev;
              p.prev.next = p.next;

              if (p.prevZ) {
                p.prevZ.nextZ = p.nextZ;
              }

              if (p.nextZ) {
                p.nextZ.prevZ = p.prevZ;
              }
            }

            function signedArea(datas, start, end, dim) {
              var sum = 0;

              for (var i = start, j = end - dim; i < end; i += dim) {
                sum += (datas[j] - datas[i]) * (datas[i + 1] + datas[j + 1]);
                j = i;
              }

              return sum;
            }

            function earcut(datas, holeIndices, dim) {
              dim = dim || 3;
              var hasHoles = holeIndices ? holeIndices.length : 0;
              var outerLen = hasHoles ? holeIndices[0] * dim : datas.length;
              var outerNode = linkedList(datas, 0, outerLen, dim, true);
              var triangles = [];

              if (!outerNode) {
                return triangles;
              }

              var minX = 0;
              var minY = 0;
              var maxX = 0;
              var maxY = 0;
              var x = 0;
              var y = 0;
              var size = 0;

              if (hasHoles) {
                outerNode = eliminateHoles(datas, holeIndices, outerNode, dim);
              }

              if (datas.length > 80 * dim) {
                minX = maxX = datas[0];
                minY = maxY = datas[1];

                for (var i = dim; i < outerLen; i += dim) {
                  x = datas[i];
                  y = datas[i + 1];

                  if (x < minX) {
                    minX = x;
                  }

                  if (y < minY) {
                    minY = y;
                  }

                  if (x > maxX) {
                    maxX = x;
                  }

                  if (y > maxY) {
                    maxY = y;
                  }
                }

                size = Math.max(maxX - minX, maxY - minY);
              }

              earcutLinked(outerNode, triangles, dim, minX, minY, size);
              return triangles;
            }

            var MAX_VERTEX = 65535;
            var MAX_INDICES = MAX_VERTEX * 2;
            var PI$1 = Math.PI;
            var min$3 = Math.min;
            var max$4 = Math.max;
            var ceil = Math.ceil;
            var acos$1 = Math.acos;
            var cos$2 = Math.cos;
            var sin$1 = Math.sin;
            var atan2 = Math.atan2;
            var attrBytes = 8;
            var _renderData = null;
            var _impl = null;

            var _curColor = new Color();

            var vec3_temps = [];

            for (var i$1 = 0; i$1 < 4; i$1++) {
              vec3_temps.push(new Vec3());
            }

            function curveDivs(r, arc, tol) {
              var da = acos$1(r / (r + tol)) * 2.0;
              return max$4(2, ceil(arc / da));
            }

            function clamp$1(v, minNum, maxNum) {
              if (v < minNum) {
                return minNum;
              } else if (v > maxNum) {
                return maxNum;
              }

              return v;
            }

            var graphicsAssembler = {
              useModel: true,
              updateRenderData: function updateRenderData(graphics) {},
              fillBuffers: function fillBuffers(graphics, renderer) {},
              renderIA: function renderIA(graphics, renderer) {},
              getRenderData: function getRenderData(graphics, vertexCount) {
                if (!_impl) {
                  return null;
                }

                var renderDataList = _impl.getRenderDataList();

                var renderData = renderDataList[_impl.dataOffset];

                if (!renderData) {
                  return null;
                }

                var meshBuffer = renderData;
                var maxVertexCount = meshBuffer ? meshBuffer.vertexStart + vertexCount : 0;

                if (maxVertexCount > MAX_VERTEX || maxVertexCount * 3 > MAX_INDICES) {
                  ++_impl.dataOffset;

                  if (_impl.dataOffset < renderDataList.length) {
                    renderData = renderDataList[_impl.dataOffset];
                  } else {
                    renderData = _impl.requestRenderData();
                    renderDataList[_impl.dataOffset] = renderData;
                  }

                  meshBuffer = renderData;
                }

                if (meshBuffer && meshBuffer.vertexCount < maxVertexCount) {
                  meshBuffer.request(vertexCount, vertexCount * 3);
                }

                return renderData;
              },
              stroke: function stroke(graphics) {
                Color.copy(_curColor, graphics.strokeColor);

                if (!graphics.impl) {
                  return;
                }

                this._flattenPaths(graphics.impl);

                this._expandStroke(graphics);

                graphics.impl.updatePathOffset = true;
                this.end(graphics);
              },
              fill: function fill(graphics) {
                Color.copy(_curColor, graphics.fillColor);

                this._expandFill(graphics);

                if (graphics.impl) {
                  graphics.impl.updatePathOffset = true;
                }

                this.end(graphics);
              },
              end: function end(graphics) {
                graphics.markForUpdateRenderData();
              },
              _expandStroke: function _expandStroke(graphics) {
                var w = graphics.lineWidth * 0.5;
                var lineCap = graphics.lineCap;
                var lineJoin = graphics.lineJoin;
                var miterLimit = graphics.miterLimit;
                _impl = graphics.impl;

                if (!_impl) {
                  return;
                }

                var nCap = curveDivs(w, PI$1, _impl.tessTol);

                this._calculateJoins(_impl, w, lineJoin, miterLimit);

                var paths = _impl.paths;
                var vertexCount = 0;

                for (var _i = _impl.pathOffset, l = _impl.pathLength; _i < l; _i++) {
                  var path = paths[_i];
                  var pointsLength = path.points.length;

                  if (lineJoin === LineJoin.ROUND) {
                    vertexCount += (pointsLength + path.bevel * (nCap + 2) + 1) * 2;
                  } else {
                    vertexCount += (pointsLength + path.bevel * 5 + 1) * 2;
                  }

                  if (!path.closed) {
                    if (lineCap === LineCap.ROUND) {
                      vertexCount += (nCap * 2 + 2) * 2;
                    } else {
                      vertexCount += (3 + 3) * 2;
                    }
                  }
                }

                var meshBuffer = _renderData = this.getRenderData(graphics, vertexCount);

                if (!meshBuffer) {
                  return;
                }

                var vData = meshBuffer.vData;
                var iData = meshBuffer.iData;

                for (var _i2 = _impl.pathOffset, _l = _impl.pathLength; _i2 < _l; _i2++) {
                  var _path = paths[_i2];
                  var pts = _path.points;
                  var _pointsLength = pts.length;
                  var offset = meshBuffer.vertexStart;
                  var p0 = void 0;
                  var p1 = void 0;
                  var start = 0;
                  var end = 0;
                  var loop = _path.closed;

                  if (loop) {
                    p0 = pts[_pointsLength - 1];
                    p1 = pts[0];
                    start = 0;
                    end = _pointsLength;
                  } else {
                    p0 = pts[0];
                    p1 = pts[1];
                    start = 1;
                    end = _pointsLength - 1;
                  }

                  p1 = p1 || p0;

                  if (!loop) {
                    var dPos = new Point(p1.x, p1.y);
                    dPos.subtract(p0);
                    dPos.normalize();
                    var dx = dPos.x;
                    var dy = dPos.y;

                    if (lineCap === LineCap.BUTT) {
                      this._buttCapStart(p0, dx, dy, w, 0);
                    } else if (lineCap === LineCap.SQUARE) {
                      this._buttCapStart(p0, dx, dy, w, w);
                    } else if (lineCap === LineCap.ROUND) {
                      this._roundCapStart(p0, dx, dy, w, nCap);
                    }
                  }

                  for (var j = start; j < end; ++j) {
                    if (lineJoin === LineJoin.ROUND) {
                      this._roundJoin(p0, p1, w, w, nCap);
                    } else if ((p1.flags & (PointFlags.PT_BEVEL | PointFlags.PT_INNERBEVEL)) !== 0) {
                      this._bevelJoin(p0, p1, w, w);
                    } else {
                      this._vSet(p1.x + p1.dmx * w, p1.y + p1.dmy * w, 1);

                      this._vSet(p1.x - p1.dmx * w, p1.y - p1.dmy * w, -1);
                    }

                    p0 = p1;
                    p1 = pts[j + 1];
                  }

                  if (loop) {
                    var vDataOffset = offset * attrBytes;

                    this._vSet(vData[vDataOffset], vData[vDataOffset + 1], 1);

                    this._vSet(vData[vDataOffset + attrBytes], vData[vDataOffset + attrBytes + 1], -1);
                  } else {
                    var _dPos = new Point(p1.x, p1.y);

                    _dPos.subtract(p0);

                    _dPos.normalize();

                    var _dx = _dPos.x;
                    var _dy = _dPos.y;

                    if (lineCap === LineCap.BUTT) {
                      this._buttCapEnd(p1, _dx, _dy, w, 0);
                    } else if (lineCap === LineCap.SQUARE) {
                      this._buttCapEnd(p1, _dx, _dy, w, w);
                    } else if (lineCap === LineCap.ROUND) {
                      this._roundCapEnd(p1, _dx, _dy, w, nCap);
                    }
                  }

                  var indicesOffset = meshBuffer.indicesStart;

                  for (var begin = offset + 2, over = meshBuffer.vertexStart; begin < over; begin++) {
                    iData[indicesOffset++] = begin - 2;
                    iData[indicesOffset++] = begin - 1;
                    iData[indicesOffset++] = begin;
                  }

                  meshBuffer.indicesStart = indicesOffset;
                }

                _renderData = null;
                _impl = null;
              },
              _expandFill: function _expandFill(graphics) {
                _impl = graphics.impl;

                if (!_impl) {
                  return;
                }

                var paths = _impl.paths;
                var vertexCount = 0;

                for (var _i3 = _impl.pathOffset, l = _impl.pathLength; _i3 < l; _i3++) {
                  var path = paths[_i3];
                  var pointsLength = path.points.length;
                  vertexCount += pointsLength;
                }

                var renderData = _renderData = this.getRenderData(graphics, vertexCount);

                if (!renderData) {
                  return;
                }

                var meshBuffer = renderData;
                var vData = meshBuffer.vData;
                var iData = meshBuffer.iData;

                for (var _i4 = _impl.pathOffset, _l2 = _impl.pathLength; _i4 < _l2; _i4++) {
                  var _path2 = paths[_i4];
                  var pts = _path2.points;
                  var _pointsLength2 = pts.length;

                  if (_pointsLength2 === 0) {
                    continue;
                  }

                  var vertexOffset = renderData.vertexStart;

                  for (var j = 0; j < _pointsLength2; ++j) {
                    this._vSet(pts[j].x, pts[j].y);
                  }

                  var indicesOffset = renderData.indicesStart;

                  if (_path2.complex) {
                    var earcutData = [];

                    for (var _j = vertexOffset, end = renderData.vertexStart; _j < end; _j++) {
                      var vDataOffset = _j * attrBytes;
                      earcutData.push(vData[vDataOffset++]);
                      earcutData.push(vData[vDataOffset++]);
                      earcutData.push(vData[vDataOffset++]);
                    }

                    var newIndices = earcut(earcutData, null, 3);

                    if (!newIndices || newIndices.length === 0) {
                      continue;
                    }

                    for (var _j2 = 0, nIndices = newIndices.length; _j2 < nIndices; _j2++) {
                      iData[indicesOffset++] = newIndices[_j2] + vertexOffset;
                    }
                  } else {
                    var first = vertexOffset;

                    for (var start = vertexOffset + 2, _end = meshBuffer.vertexStart; start < _end; start++) {
                      iData[indicesOffset++] = first;
                      iData[indicesOffset++] = start - 1;
                      iData[indicesOffset++] = start;
                    }
                  }

                  meshBuffer.indicesStart = indicesOffset;
                }

                _renderData = null;
                _impl = null;
              },
              _calculateJoins: function _calculateJoins(impl, w, lineJoin, miterLimit) {
                var iw = 0.0;

                if (w > 0.0) {
                  iw = 1 / w;
                }

                var paths = impl.paths;

                for (var _i5 = impl.pathOffset, l = impl.pathLength; _i5 < l; _i5++) {
                  var path = paths[_i5];
                  var pts = path.points;
                  var ptsLength = pts.length;
                  var p0 = pts[ptsLength - 1];
                  var p1 = pts[0];
                  path.bevel = 0;

                  for (var j = 0; j < ptsLength; j++) {
                    var dmr2 = 0;
                    var cross = 0;
                    var limit = 0;
                    var dlx0 = p0.dy;
                    var dly0 = -p0.dx;
                    var dlx1 = p1.dy;
                    var dly1 = -p1.dx;
                    p1.dmx = (dlx0 + dlx1) * 0.5;
                    p1.dmy = (dly0 + dly1) * 0.5;
                    dmr2 = p1.dmx * p1.dmx + p1.dmy * p1.dmy;

                    if (dmr2 > 0.000001) {
                      var scale = 1 / dmr2;

                      if (scale > 600) {
                        scale = 600;
                      }

                      p1.dmx *= scale;
                      p1.dmy *= scale;
                    }

                    cross = p1.dx * p0.dy - p0.dx * p1.dy;

                    if (cross > 0) {
                      p1.flags |= PointFlags.PT_LEFT;
                    }

                    limit = max$4(11, min$3(p0.len, p1.len) * iw);

                    if (dmr2 * limit * limit < 1) {
                      p1.flags |= PointFlags.PT_INNERBEVEL;
                    }

                    if (p1.flags & PointFlags.PT_CORNER) {
                      if (dmr2 * miterLimit * miterLimit < 1 || lineJoin === LineJoin.BEVEL || lineJoin === LineJoin.ROUND) {
                        p1.flags |= PointFlags.PT_BEVEL;
                      }
                    }

                    if ((p1.flags & (PointFlags.PT_BEVEL | PointFlags.PT_INNERBEVEL)) !== 0) {
                      path.bevel++;
                    }

                    p0 = p1;
                    p1 = pts[j + 1];
                  }
                }
              },
              _flattenPaths: function _flattenPaths(impl) {
                var paths = impl.paths;

                for (var _i6 = impl.pathOffset, l = impl.pathLength; _i6 < l; _i6++) {
                  var path = paths[_i6];
                  var pts = path.points;
                  var p0 = pts[pts.length - 1];
                  var p1 = pts[0];

                  if (pts.length > 2 && p0.equals(p1)) {
                    path.closed = true;
                    pts.pop();
                    p0 = pts[pts.length - 1];
                  }

                  for (var j = 0, size = pts.length; j < size; j++) {
                    var dPos = new Point(p1.x, p1.y);
                    dPos.subtract(p0);
                    p0.len = dPos.length();

                    if (dPos.x || dPos.y) {
                      dPos.normalize();
                    }

                    p0.dx = dPos.x;
                    p0.dy = dPos.y;
                    p0 = p1;
                    p1 = pts[j + 1];
                  }
                }
              },
              _chooseBevel: function _chooseBevel(bevel, p0, p1, w) {
                var x = p1.x;
                var y = p1.y;
                var x0 = 0;
                var y0 = 0;
                var x1 = 0;
                var y1 = 0;

                if (bevel !== 0) {
                  x0 = x + p0.dy * w;
                  y0 = y - p0.dx * w;
                  x1 = x + p1.dy * w;
                  y1 = y - p1.dx * w;
                } else {
                  x0 = x1 = x + p1.dmx * w;
                  y0 = y1 = y + p1.dmy * w;
                }

                return [x0, y0, x1, y1];
              },
              _buttCapStart: function _buttCapStart(p, dx, dy, w, d) {
                var px = p.x - dx * d;
                var py = p.y - dy * d;
                var dlx = dy;
                var dly = -dx;

                this._vSet(px + dlx * w, py + dly * w, 1);

                this._vSet(px - dlx * w, py - dly * w, -1);
              },
              _buttCapEnd: function _buttCapEnd(p, dx, dy, w, d) {
                var px = p.x + dx * d;
                var py = p.y + dy * d;
                var dlx = dy;
                var dly = -dx;

                this._vSet(px + dlx * w, py + dly * w, 1);

                this._vSet(px - dlx * w, py - dly * w, -1);
              },
              _roundCapStart: function _roundCapStart(p, dx, dy, w, nCap) {
                var px = p.x;
                var py = p.y;
                var dlx = dy;
                var dly = -dx;

                for (var _i7 = 0; _i7 < nCap; _i7++) {
                  var a = _i7 / (nCap - 1) * PI$1;
                  var ax = cos$2(a) * w;
                  var ay = sin$1(a) * w;

                  this._vSet(px - dlx * ax - dx * ay, py - dly * ax - dy * ay, 1);

                  this._vSet(px, py, 0);
                }

                this._vSet(px + dlx * w, py + dly * w, 1);

                this._vSet(px - dlx * w, py - dly * w, -1);
              },
              _roundCapEnd: function _roundCapEnd(p, dx, dy, w, nCap) {
                var px = p.x;
                var py = p.y;
                var dlx = dy;
                var dly = -dx;

                this._vSet(px + dlx * w, py + dly * w, 1);

                this._vSet(px - dlx * w, py - dly * w, -1);

                for (var _i8 = 0; _i8 < nCap; _i8++) {
                  var a = _i8 / (nCap - 1) * PI$1;
                  var ax = cos$2(a) * w;
                  var ay = sin$1(a) * w;

                  this._vSet(px, py, 0);

                  this._vSet(px - dlx * ax + dx * ay, py - dly * ax + dy * ay, 1);
                }
              },
              _roundJoin: function _roundJoin(p0, p1, lw, rw, nCap) {
                var dlx0 = p0.dy;
                var dly0 = -p0.dx;
                var dlx1 = p1.dy;
                var dly1 = -p1.dx;
                var p1x = p1.x;
                var p1y = p1.y;

                if ((p1.flags & PointFlags.PT_LEFT) !== 0) {
                  var out = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, lw);

                  var lx0 = out[0];
                  var ly0 = out[1];
                  var lx1 = out[2];
                  var ly1 = out[3];
                  var a0 = atan2(-dly0, -dlx0);
                  var a1 = atan2(-dly1, -dlx1);

                  if (a1 > a0) {
                    a1 -= PI$1 * 2;
                  }

                  this._vSet(lx0, ly0, 1);

                  this._vSet(p1x - dlx0 * rw, p1.y - dly0 * rw, -1);

                  var n = clamp$1(ceil((a0 - a1) / PI$1) * nCap, 2, nCap);

                  for (var _i9 = 0; _i9 < n; _i9++) {
                    var u = _i9 / (n - 1);
                    var a = a0 + u * (a1 - a0);
                    var rx = p1x + cos$2(a) * rw;
                    var ry = p1y + sin$1(a) * rw;

                    this._vSet(p1x, p1y, 0);

                    this._vSet(rx, ry, -1);
                  }

                  this._vSet(lx1, ly1, 1);

                  this._vSet(p1x - dlx1 * rw, p1y - dly1 * rw, -1);
                } else {
                  var _out = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, -rw);

                  var rx0 = _out[0];
                  var ry0 = _out[1];
                  var rx1 = _out[2];
                  var ry1 = _out[3];

                  var _a = atan2(dly0, dlx0);

                  var _a2 = atan2(dly1, dlx1);

                  if (_a2 < _a) {
                    _a2 += PI$1 * 2;
                  }

                  this._vSet(p1x + dlx0 * rw, p1y + dly0 * rw, 1);

                  this._vSet(rx0, ry0, -1);

                  var _n = clamp$1(ceil((_a2 - _a) / PI$1) * nCap, 2, nCap);

                  for (var _i10 = 0; _i10 < _n; _i10++) {
                    var _u = _i10 / (_n - 1);

                    var _a3 = _a + _u * (_a2 - _a);

                    var lx = p1x + cos$2(_a3) * lw;
                    var ly = p1y + sin$1(_a3) * lw;

                    this._vSet(lx, ly, 1);

                    this._vSet(p1x, p1y, 0);
                  }

                  this._vSet(p1x + dlx1 * rw, p1y + dly1 * rw, 1);

                  this._vSet(rx1, ry1, -1);
                }
              },
              _bevelJoin: function _bevelJoin(p0, p1, lw, rw) {
                var rx0 = 0;
                var ry0 = 0;
                var rx1 = 0;
                var ry1 = 0;
                var lx0 = 0;
                var ly0 = 0;
                var lx1 = 0;
                var ly1 = 0;
                var dlx0 = p0.dy;
                var dly0 = -p0.dx;
                var dlx1 = p1.dy;
                var dly1 = -p1.dx;

                if (p1.flags & PointFlags.PT_LEFT) {
                  var out = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, lw);

                  lx0 = out[0];
                  ly0 = out[1];
                  lx1 = out[2];
                  ly1 = out[3];

                  this._vSet(lx0, ly0, 1);

                  this._vSet(p1.x - dlx0 * rw, p1.y - dly0 * rw, -1);

                  this._vSet(lx1, ly1, 1);

                  this._vSet(p1.x - dlx1 * rw, p1.y - dly1 * rw, -1);
                } else {
                  var _out2 = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, -rw);

                  rx0 = _out2[0];
                  ry0 = _out2[1];
                  rx1 = _out2[2];
                  ry1 = _out2[3];

                  this._vSet(p1.x + dlx0 * lw, p1.y + dly0 * lw, 1);

                  this._vSet(rx0, ry0, -1);

                  this._vSet(p1.x + dlx1 * lw, p1.y + dly1 * lw, 1);

                  this._vSet(rx1, ry1, -1);
                }
              },
              _vSet: function _vSet(x, y, distance) {
                if (distance === void 0) {
                  distance = 0;
                }

                if (!_renderData) {
                  return;
                }

                var meshBuffer = _renderData;
                var dataOffset = meshBuffer.vertexStart * attrBytes;
                var vData = meshBuffer.vData;
                vData[dataOffset++] = x;
                vData[dataOffset++] = y;
                vData[dataOffset++] = 0;
                Color.toArray(vData, _curColor, dataOffset);
                dataOffset += 4;
                vData[dataOffset++] = distance;
                meshBuffer.vertexStart++;
              }
            };

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

            var LetterInfo = function LetterInfo() {
              this["char"] = '';
              this.valid = true;
              this.x = 0;
              this.y = 0;
              this.line = 0;
              this.hash = '';
            };

            var _tmpRect = new Rect();

            var _comp = null;
            var _uiTrans = null;
            var _horizontalKerning = [];
            var _lettersInfo = [];
            var _linesWidth = [];
            var _linesOffsetX = [];

            var _labelDimensions = new Size();

            var _contentSize = new Size();

            var letterPosition = new Vec2();
            var _lineSpacing = 0;
            var _fntConfig = null;
            var _numberOfLines = 0;
            var _textDesiredHeight = 0;
            var _letterOffsetY = 0;
            var _tailoredTopY = 0;
            var _tailoredBottomY = 0;
            var _bmfontScale = 1.0;
            var _spriteFrame = null;
            var _string = '';
            var _fontSize = 0;
            var _originFontSize = 0;
            var _hAlign = 0;
            var _vAlign = 0;
            var _spacingX = 0;
            var _lineHeight = 0;
            var _overflow = 0;
            var _isWrapText = false;
            var _labelWidth = 0;
            var _labelHeight = 0;
            var _maxLineWidth = 0;
            var bmfontUtils = {
              updateRenderData: function updateRenderData(comp) {
                if (!comp.renderData || !comp.renderData.vertDirty) {
                  return;
                }

                if (_comp === comp) {
                  return;
                }

                _comp = comp;
                _uiTrans = _comp.node._uiProps.uiTransformComp;

                this._updateFontFamily(comp);

                this._updateProperties(comp);

                this._updateLabelInfo(comp);

                this._updateContent();

                _comp.actualFontSize = _fontSize;

                _uiTrans.setContentSize(_contentSize);

                _comp.renderData.vertDirty = _comp.renderData.uvDirty = false;

                _comp.markForUpdateRenderData(false);

                _comp = null;

                this._resetProperties();
              },
              _updateFontScale: function _updateFontScale() {
                _bmfontScale = _fontSize / _originFontSize;
              },
              _updateFontFamily: function _updateFontFamily(comp) {
                var fontAsset = comp.font;
                _spriteFrame = fontAsset.spriteFrame;
                _fntConfig = fontAsset.fntConfig;
                shareLabelInfo.fontAtlas = fontAsset.fontDefDictionary;
                dynamicAtlasManager.packToDynamicAtlas(comp, _spriteFrame);
              },
              _updateLabelInfo: function _updateLabelInfo(comp) {
                shareLabelInfo.hash = '';
                shareLabelInfo.margin = 0;
              },
              _updateProperties: function _updateProperties(comp) {
                _string = comp.string.toString();
                _fontSize = comp.fontSize;
                _originFontSize = _fntConfig ? _fntConfig.fontSize : comp.fontSize;
                _hAlign = comp.horizontalAlign;
                _vAlign = comp.verticalAlign;
                _spacingX = comp.spacingX;
                _overflow = comp.overflow;
                _lineHeight = comp._lineHeight;
                var contentSize = _uiTrans.contentSize;
                _contentSize.width = contentSize.width;
                _contentSize.height = contentSize.height;

                if (_overflow === Overflow.NONE) {
                  _isWrapText = false;
                  _contentSize.width += shareLabelInfo.margin * 2;
                  _contentSize.height += shareLabelInfo.margin * 2;
                } else if (_overflow === Overflow.RESIZE_HEIGHT) {
                  _isWrapText = true;
                  _contentSize.height += shareLabelInfo.margin * 2;
                } else {
                  _isWrapText = comp.enableWrapText;
                }

                shareLabelInfo.lineHeight = _lineHeight;
                shareLabelInfo.fontSize = _fontSize;

                this._setupBMFontOverflowMetrics();
              },
              _resetProperties: function _resetProperties() {
                _fntConfig = null;
                _spriteFrame = null;
                shareLabelInfo.hash = '';
                shareLabelInfo.margin = 0;
              },
              _updateContent: function _updateContent() {
                this._updateFontScale();

                this._computeHorizontalKerningForText();

                this._alignText();
              },
              _computeHorizontalKerningForText: function _computeHorizontalKerningForText() {
                var string = _string;
                var stringLen = string.length;
                var kerningDict = _fntConfig.kerningDict;
                var horizontalKerning = _horizontalKerning;
                var prev = -1;

                for (var i = 0; i < stringLen; ++i) {
                  var key = string.charCodeAt(i);
                  var kerningAmount = kerningDict[prev << 16 | key & 0xffff] || 0;

                  if (i < stringLen - 1) {
                    horizontalKerning[i] = kerningAmount;
                  } else {
                    horizontalKerning[i] = 0;
                  }

                  prev = key;
                }
              },
              _multilineTextWrap: function _multilineTextWrap(nextTokenFunc) {
                var textLen = _string.length;
                var lineIndex = 0;
                var nextTokenX = 0;
                var nextTokenY = 0;
                var longestLine = 0;
                var letterRight = 0;
                var highestY = 0;
                var lowestY = 0;
                var letterDef = null;

                for (var index = 0; index < textLen;) {
                  var character = _string.charAt(index);

                  if (character === '\n') {
                    _linesWidth.push(letterRight);

                    letterRight = 0;
                    lineIndex++;
                    nextTokenX = 0;
                    nextTokenY -= _lineHeight * this._getFontScale() + _lineSpacing;

                    this._recordPlaceholderInfo(index, character);

                    index++;
                    continue;
                  }

                  var tokenLen = nextTokenFunc(_string, index, textLen);
                  var tokenHighestY = highestY;
                  var tokenLowestY = lowestY;
                  var tokenRight = letterRight;
                  var nextLetterX = nextTokenX;
                  var newLine = false;

                  for (var tmp = 0; tmp < tokenLen; ++tmp) {
                    var letterIndex = index + tmp;
                    character = _string.charAt(letterIndex);

                    if (character === '\r') {
                      this._recordPlaceholderInfo(letterIndex, character);

                      continue;
                    }

                    letterDef = shareLabelInfo.fontAtlas.getLetterDefinitionForChar(character, shareLabelInfo);

                    if (!letterDef) {
                      this._recordPlaceholderInfo(letterIndex, character);

                      console.log("Can't find letter definition in texture atlas " + _fntConfig.atlasName + " for letter:" + character);
                      continue;
                    }

                    var letterX = nextLetterX + letterDef.offsetX * _bmfontScale - shareLabelInfo.margin;

                    if (_isWrapText && _maxLineWidth > 0 && nextTokenX > 0 && letterX + letterDef.w * _bmfontScale > _maxLineWidth && !isUnicodeSpace(character)) {
                      _linesWidth.push(letterRight);

                      letterRight = 0;
                      lineIndex++;
                      nextTokenX = 0;
                      nextTokenY -= _lineHeight * this._getFontScale() + _lineSpacing;
                      newLine = true;
                      break;
                    } else {
                      letterPosition.x = letterX;
                    }

                    letterPosition.y = nextTokenY - letterDef.offsetY * _bmfontScale;

                    this._recordLetterInfo(letterPosition, character, letterIndex, lineIndex);

                    if (letterIndex + 1 < _horizontalKerning.length && letterIndex < textLen - 1) {
                      nextLetterX += _horizontalKerning[letterIndex + 1];
                    }

                    nextLetterX += letterDef.xAdvance * _bmfontScale + _spacingX;
                    tokenRight = letterPosition.x + letterDef.w * _bmfontScale;

                    if (tokenHighestY < letterPosition.y) {
                      tokenHighestY = letterPosition.y;
                    }

                    if (tokenLowestY > letterPosition.y - letterDef.h * _bmfontScale) {
                      tokenLowestY = letterPosition.y - letterDef.h * _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;
                }

                _linesWidth.push(letterRight);

                _numberOfLines = lineIndex + 1;
                _textDesiredHeight = _numberOfLines * _lineHeight * this._getFontScale();

                if (_numberOfLines > 1) {
                  _textDesiredHeight += (_numberOfLines - 1) * _lineSpacing;
                }

                _contentSize.width = _labelWidth;
                _contentSize.height = _labelHeight;

                if (_labelWidth <= 0) {
                  _contentSize.width = parseFloat(longestLine.toFixed(2)) + shareLabelInfo.margin * 2;
                }

                if (_labelHeight <= 0) {
                  _contentSize.height = parseFloat(_textDesiredHeight.toFixed(2)) + shareLabelInfo.margin * 2;
                }

                _tailoredTopY = _contentSize.height;
                _tailoredBottomY = 0;

                if (highestY > 0) {
                  _tailoredTopY = _contentSize.height + highestY;
                }

                if (lowestY < -_textDesiredHeight) {
                  _tailoredBottomY = _textDesiredHeight + lowestY;
                }

                return true;
              },
              _getFirstCharLen: function _getFirstCharLen() {
                return 1;
              },
              _getFontScale: function _getFontScale() {
                return _overflow === Overflow.SHRINK ? _bmfontScale : 1;
              },
              _getFirstWordLen: function _getFirstWordLen(text, startIndex, textLen) {
                var character = text.charAt(startIndex);

                if (isUnicodeCJK(character) || character === '\n' || isUnicodeSpace(character)) {
                  return 1;
                }

                var len = 1;
                var letterDef = shareLabelInfo.fontAtlas.getLetterDefinitionForChar(character, shareLabelInfo);

                if (!letterDef) {
                  return len;
                }

                var nextLetterX = letterDef.xAdvance * _bmfontScale + _spacingX;
                var letterX = 0;

                for (var index = startIndex + 1; index < textLen; ++index) {
                  character = text.charAt(index);
                  letterDef = shareLabelInfo.fontAtlas.getLetterDefinitionForChar(character, shareLabelInfo);

                  if (!letterDef) {
                    break;
                  }

                  letterX = nextLetterX + letterDef.offsetX * _bmfontScale;

                  if (letterX + letterDef.w * _bmfontScale > _maxLineWidth && !isUnicodeSpace(character) && _maxLineWidth > 0) {
                    return len;
                  }

                  nextLetterX += letterDef.xAdvance * _bmfontScale + _spacingX;

                  if (character === '\n' || isUnicodeSpace(character) || isUnicodeCJK(character)) {
                    break;
                  }

                  len++;
                }

                return len;
              },
              _multilineTextWrapByWord: function _multilineTextWrapByWord() {
                return this._multilineTextWrap(this._getFirstWordLen);
              },
              _multilineTextWrapByChar: function _multilineTextWrapByChar() {
                return this._multilineTextWrap(this._getFirstCharLen);
              },
              _recordPlaceholderInfo: function _recordPlaceholderInfo(letterIndex, _char) {
                if (letterIndex >= _lettersInfo.length) {
                  var tmpInfo = new LetterInfo();

                  _lettersInfo.push(tmpInfo);
                }

                _lettersInfo[letterIndex]["char"] = _char;
                _lettersInfo[letterIndex].hash = _char.charCodeAt(0) + shareLabelInfo.hash;
                _lettersInfo[letterIndex].valid = false;
              },
              _recordLetterInfo: function _recordLetterInfo(letterPosition, character, letterIndex, lineIndex) {
                if (letterIndex >= _lettersInfo.length) {
                  var tmpInfo = new LetterInfo();

                  _lettersInfo.push(tmpInfo);
                }

                var _char2 = character.charCodeAt(0);

                var key = _char2 + shareLabelInfo.hash;
                _lettersInfo[letterIndex].line = lineIndex;
                _lettersInfo[letterIndex]["char"] = character;
                _lettersInfo[letterIndex].hash = key;
                _lettersInfo[letterIndex].valid = shareLabelInfo.fontAtlas.getLetter(key).valid;
                _lettersInfo[letterIndex].x = letterPosition.x;
                _lettersInfo[letterIndex].y = letterPosition.y;
              },
              _alignText: function _alignText() {
                _textDesiredHeight = 0;
                _linesWidth.length = 0;

                {
                  this._multilineTextWrapByWord();
                }

                this._computeAlignmentOffset();

                if (_overflow === Overflow.SHRINK) {
                  if (_fontSize > 0 && this._isVerticalClamp()) {
                    this._shrinkLabelToContentSize(this._isVerticalClamp);
                  }
                }

                if (!this._updateQuads()) {
                  if (_overflow === Overflow.SHRINK) {
                    this._shrinkLabelToContentSize(this._isHorizontalClamp);
                  }
                }
              },
              _scaleFontSizeDown: function _scaleFontSizeDown(fontSize) {
                var shouldUpdateContent = true;

                if (!fontSize) {
                  fontSize = 0.1;
                  shouldUpdateContent = false;
                }

                _fontSize = fontSize;

                if (shouldUpdateContent) {
                  this._updateContent();
                }
              },
              _shrinkLabelToContentSize: function _shrinkLabelToContentSize(lambda) {
                var fontSize = _fontSize;
                var left = 0;
                var right = fontSize | 0;
                var mid = 0;

                while (left < right) {
                  mid = left + right + 1 >> 1;
                  var newFontSize = mid;

                  if (newFontSize <= 0) {
                    break;
                  }

                  _bmfontScale = newFontSize / _originFontSize;

                  {
                    this._multilineTextWrapByWord();
                  }

                  this._computeAlignmentOffset();

                  if (lambda()) {
                    right = mid - 1;
                  } else {
                    left = mid;
                  }
                }

                if (left >= 0) {
                  this._scaleFontSizeDown(left);
                }
              },
              _isVerticalClamp: function _isVerticalClamp() {
                if (_textDesiredHeight > _contentSize.height) {
                  return true;
                } else {
                  return false;
                }
              },
              _isHorizontalClamp: function _isHorizontalClamp() {
                var letterClamp = false;

                for (var ctr = 0, l = _string.length; ctr < l; ++ctr) {
                  var letterInfo = _lettersInfo[ctr];

                  if (letterInfo.valid) {
                    var letterDef = shareLabelInfo.fontAtlas.getLetterDefinitionForChar(letterInfo["char"], shareLabelInfo);

                    if (!letterDef) {
                      continue;
                    }

                    var px = letterInfo.x + letterDef.w / 2 * _bmfontScale;
                    var lineIndex = letterInfo.line;

                    if (_labelWidth > 0) {
                      if (!_isWrapText) {
                        if (px > _contentSize.width) {
                          letterClamp = true;
                          break;
                        }
                      } else {
                        var wordWidth = _linesWidth[lineIndex];

                        if (wordWidth > _contentSize.width && (px > _contentSize.width || px < 0)) {
                          letterClamp = true;
                          break;
                        }
                      }
                    }
                  }
                }

                return letterClamp;
              },
              _isHorizontalClamped: function _isHorizontalClamped(px, lineIndex) {
                var wordWidth = _linesWidth[lineIndex];
                var letterOverClamp = px > _contentSize.width || px < 0;

                if (!_isWrapText) {
                  return letterOverClamp;
                } else {
                  return wordWidth > _contentSize.width && letterOverClamp;
                }
              },
              _updateQuads: function _updateQuads() {
                if (!_comp) {
                  return false;
                }

                var texture = _spriteFrame ? _spriteFrame.texture : shareLabelInfo.fontAtlas.getTexture();
                var renderData = _comp.renderData;
                renderData.dataLength = renderData.vertexCount = renderData.indicesCount = 0;
                var anchorPoint = _uiTrans.anchorPoint;
                var contentSize = _contentSize;
                var appX = anchorPoint.x * contentSize.width;
                var appY = anchorPoint.y * contentSize.height;
                var ret = true;

                for (var ctr = 0, l = _string.length; ctr < l; ++ctr) {
                  var letterInfo = _lettersInfo[ctr];

                  if (!letterInfo.valid) {
                    continue;
                  }

                  var letterDef = shareLabelInfo.fontAtlas.getLetter(letterInfo.hash);

                  if (!letterDef) {
                    console.warn('Can\'t find letter in this bitmap-font');
                    continue;
                  }

                  _tmpRect.height = letterDef.h;
                  _tmpRect.width = letterDef.w;
                  _tmpRect.x = letterDef.u;
                  _tmpRect.y = letterDef.v;
                  var py = letterInfo.y + _letterOffsetY;

                  if (_labelHeight > 0) {
                    if (py > _tailoredTopY) {
                      var clipTop = py - _tailoredTopY;
                      _tmpRect.y += clipTop;
                      _tmpRect.height -= clipTop;
                      py -= clipTop;
                    }

                    if (py - letterDef.h * _bmfontScale < _tailoredBottomY && _overflow === Overflow.CLAMP) {
                      _tmpRect.height = py < _tailoredBottomY ? 0 : (py - _tailoredBottomY) / _bmfontScale;
                    }
                  }

                  var lineIndex = letterInfo.line;
                  var px = letterInfo.x + letterDef.w / 2 * _bmfontScale + _linesOffsetX[lineIndex];

                  if (_labelWidth > 0) {
                    if (this._isHorizontalClamped(px, lineIndex)) {
                      if (_overflow === Overflow.CLAMP) {
                        _tmpRect.width = 0;
                      } else if (_overflow === Overflow.SHRINK) {
                        if (_contentSize.width > letterDef.w) {
                          ret = false;
                          break;
                        } else {
                          _tmpRect.width = 0;
                        }
                      }
                    }
                  }

                  if (_tmpRect.height > 0 && _tmpRect.width > 0) {
                    var isRotated = this._determineRect();

                    var letterPositionX = letterInfo.x + _linesOffsetX[letterInfo.line];
                    this.appendQuad(_comp, texture, _tmpRect, isRotated, letterPositionX - appX, py - appY, _bmfontScale);
                  }
                }

                return ret;
              },
              appendQuad: function appendQuad(comp, texture, rect, rotated, x, y, scale) {},
              _determineRect: function _determineRect() {
                var isRotated = _spriteFrame.isRotated();

                var originalSize = _spriteFrame.getOriginalSize();

                var rect = _spriteFrame.getRect();

                var offset = _spriteFrame.getOffset();

                var trimmedLeft = offset.x + (originalSize.width - rect.width) / 2;
                var trimmedTop = offset.y - (originalSize.height - rect.height) / 2;

                if (!isRotated) {
                  _tmpRect.x += rect.x - trimmedLeft;
                  _tmpRect.y += rect.y + trimmedTop;
                } else {
                  var originalX = _tmpRect.x;
                  _tmpRect.x = rect.x + rect.height - _tmpRect.y - _tmpRect.height - trimmedTop;
                  _tmpRect.y = originalX + rect.y - trimmedLeft;

                  if (_tmpRect.y < 0) {
                    _tmpRect.height += trimmedTop;
                  }
                }

                return isRotated;
              },
              _computeAlignmentOffset: function _computeAlignmentOffset() {
                _linesOffsetX.length = 0;

                switch (_hAlign) {
                  case HorizontalTextAlignment.LEFT:
                    for (var i = 0; i < _numberOfLines; ++i) {
                      _linesOffsetX.push(0);
                    }

                    break;

                  case HorizontalTextAlignment.CENTER:
                    for (var _i = 0, l = _linesWidth.length; _i < l; _i++) {
                      _linesOffsetX.push((_contentSize.width - _linesWidth[_i]) / 2);
                    }

                    break;

                  case HorizontalTextAlignment.RIGHT:
                    for (var _i2 = 0, _l = _linesWidth.length; _i2 < _l; _i2++) {
                      _linesOffsetX.push(_contentSize.width - _linesWidth[_i2]);
                    }

                    break;
                }

                _letterOffsetY = _contentSize.height;

                if (_vAlign !== VerticalTextAlignment.TOP) {
                  var blank = _contentSize.height - _textDesiredHeight + _lineHeight * this._getFontScale() - _originFontSize * _bmfontScale;

                  if (_vAlign === VerticalTextAlignment.BOTTOM) {
                    _letterOffsetY -= blank;
                  } else {
                    _letterOffsetY -= blank / 2;
                  }
                }
              },
              _setupBMFontOverflowMetrics: function _setupBMFontOverflowMetrics() {
                var newWidth = _contentSize.width;
                var newHeight = _contentSize.height;

                if (_overflow === Overflow.RESIZE_HEIGHT) {
                  newHeight = 0;
                }

                if (_overflow === Overflow.NONE) {
                  newWidth = 0;
                  newHeight = 0;
                }

                _labelWidth = newWidth;
                _labelHeight = newHeight;
                _labelDimensions.width = newWidth;
                _labelDimensions.height = newHeight;
                _maxLineWidth = newWidth;
              }
            };

            var tempColor = new Color(255, 255, 255, 255);
            var bmfont = {
              createData: function createData(comp) {
                return comp.requestRenderData();
              },
              fillBuffers: function fillBuffers(comp, renderer) {
                var node = comp.node;

                comp._setCacheAlpha(node._uiProps.opacity);

                tempColor.set(comp.color);
                tempColor.a = node._uiProps.opacity * 255;
                fillMeshVertices3D(node, renderer, comp.renderData, tempColor);
              },
              appendQuad: function appendQuad(comp, spriteFrame, rect, rotated, x, y, scale) {
                var renderData = comp.renderData;

                if (!renderData) {
                  return;
                }

                var dataOffset = renderData.dataLength;
                renderData.dataLength += 4;
                renderData.vertexCount = renderData.dataLength;
                renderData.indicesCount = renderData.dataLength / 2 * 3;
                var dataList = renderData.data;
                var texW = spriteFrame.width;
                var texH = spriteFrame.height;
                var rectWidth = rect.width;
                var rectHeight = rect.height;
                var l = 0;
                var b = 0;
                var t = 0;
                var r = 0;

                if (!rotated) {
                  l = rect.x / texW;
                  r = (rect.x + rectWidth) / texW;
                  b = (rect.y + rectHeight) / texH;
                  t = rect.y / texH;
                  dataList[dataOffset].u = l;
                  dataList[dataOffset].v = b;
                  dataList[dataOffset + 1].u = r;
                  dataList[dataOffset + 1].v = b;
                  dataList[dataOffset + 2].u = l;
                  dataList[dataOffset + 2].v = t;
                  dataList[dataOffset + 3].u = r;
                  dataList[dataOffset + 3].v = t;
                } else {
                  l = rect.x / texW;
                  r = (rect.x + rectHeight) / texW;
                  b = (rect.y + rectWidth) / texH;
                  t = rect.y / texH;
                  dataList[dataOffset].u = l;
                  dataList[dataOffset].v = t;
                  dataList[dataOffset + 1].u = l;
                  dataList[dataOffset + 1].v = b;
                  dataList[dataOffset + 2].u = r;
                  dataList[dataOffset + 2].v = t;
                  dataList[dataOffset + 3].u = r;
                  dataList[dataOffset + 3].v = b;
                }

                dataList[dataOffset].x = x;
                dataList[dataOffset].y = y - rectHeight * scale;
                dataList[dataOffset + 1].x = x + rectWidth * scale;
                dataList[dataOffset + 1].y = y - rectHeight * scale;
                dataList[dataOffset + 2].x = x;
                dataList[dataOffset + 2].y = y;
                dataList[dataOffset + 3].x = x + rectWidth * scale;
                dataList[dataOffset + 3].y = y;
              }
            };
            addon(bmfont, bmfontUtils);

            var _atlasWidth = 1024;
            var _atlasHeight = 1024;
            var _shareAtlas = null;
            var letterFont = mixin(bmfontUtils, {
              getAssemblerData: function getAssemblerData() {
                if (!_shareAtlas) {
                  _shareAtlas = new LetterAtlas(_atlasWidth, _atlasHeight);
                }

                return _shareAtlas.getTexture();
              },
              _updateFontFamily: function _updateFontFamily(comp) {
                shareLabelInfo.fontAtlas = _shareAtlas;
                shareLabelInfo.fontFamily = this._getFontFamily(comp);
                var outline = comp.getComponent(LabelOutline);

                if (outline && outline.enabled) {
                  shareLabelInfo.isOutlined = true;
                  shareLabelInfo.margin = outline.width;
                  shareLabelInfo.out = outline.color.clone();
                  shareLabelInfo.out.a = outline.color.a * comp.color.a / 255.0;
                } else {
                  shareLabelInfo.isOutlined = false;
                  shareLabelInfo.margin = 0;
                }
              },
              _getFontFamily: function _getFontFamily(comp) {
                var fontFamily = 'Arial';

                if (!comp.useSystemFont) {
                  if (comp.font) {
                    if (comp.font._nativeAsset) {
                      fontFamily = comp.font._nativeAsset;
                    } else {
                      assetManager.postLoadNative(comp.font, function (err) {
                        if (!comp.isValid) {
                          return;
                        }

                        fontFamily = comp.font._nativeAsset || 'Arial';
                        comp.updateRenderData(true);
                      });
                    }
                  }
                } else {
                  fontFamily = comp.fontFamily || 'Arial';
                }

                return fontFamily;
              },
              _updateLabelInfo: function _updateLabelInfo(comp) {
                shareLabelInfo.fontDesc = this._getFontDesc();
                shareLabelInfo.color = comp.color;
                shareLabelInfo.hash = computeHash(shareLabelInfo);
              },
              _getFontDesc: function _getFontDesc() {
                var fontDesc = shareLabelInfo.fontSize.toString() + "px ";
                fontDesc += shareLabelInfo.fontFamily;

                return fontDesc;
              },
              _computeHorizontalKerningForText: function _computeHorizontalKerningForText() {},
              _determineRect: function _determineRect(tempRect) {
                return false;
              }
            });

            var WHITE$1 = new Color(255, 255, 255, 255);
            var letter = {
              createData: function createData(comp) {
                return comp.requestRenderData();
              },
              fillBuffers: function fillBuffers(comp, renderer) {
                if (!comp.renderData) {
                  return;
                }

                var node = comp.node;

                comp._setCacheAlpha(node._uiProps.opacity);

                WHITE$1.a = node._uiProps.opacity * 255;
                fillMeshVertices3D(node, renderer, comp.renderData, WHITE$1);
              },
              appendQuad: bmfont.appendQuad
            };
            addon(letter, letterFont);

            var Overflow$1 = Label.Overflow;
            var MAX_SIZE$1 = 2048;

            var _BASELINE_OFFSET$1 = getBaselineOffset();

            var _invisibleAlpha = (1 / 255).toFixed(3);

            var _context = null;
            var _canvas = null;
            var _texture = null;
            var _fontDesc = '';
            var _string$1 = '';
            var _fontSize$1 = 0;
            var _drawFontsize = 0;
            var _splitStrings = [];

            var _canvasSize = new Size();

            var _lineHeight$1 = 0;
            var _hAlign$1 = 0;
            var _vAlign$1 = 0;

            var _color = new Color();

            var _alpha = 1;
            var _fontFamily = '';
            var _overflow$1 = Overflow$1.NONE;
            var _isWrapText$1 = false;
            var _outlineComp = null;

            var _outlineColor = Color.BLACK.clone();

            var _shadowComp = null;

            var _shadowColor = Color.BLACK.clone();

            var _canvasPadding = new Rect();

            var _contentSizeExtend = Size.ZERO.clone();

            var _nodeContentSize = Size.ZERO.clone();

            var _startPosition = Vec2.ZERO.clone();

            var _drawUnderlinePos = Vec2.ZERO.clone();

            var _drawUnderlineWidth = 0;
            var _underlineThickness = 0;
            var _isBold = false;
            var _isItalic = false;
            var _isUnderline = false;
            var Alignment = ['left', 'center', 'right'];
            var ttfUtils = {
              getAssemblerData: function getAssemblerData() {
                var sharedLabelData = Label._canvasPool.get();

                return sharedLabelData;
              },
              resetAssemblerData: function resetAssemblerData(assemblerData) {
                if (assemblerData) {
                  Label._canvasPool.put(assemblerData);
                }
              },
              updateRenderData: function updateRenderData(comp) {
                if (!comp.renderData || !comp.renderData.vertDirty) {
                  return;
                }

                var trans = comp.node._uiProps.uiTransformComp;

                this._updateFontFamily(comp);

                this._updateProperties(comp, trans);

                this._calculateLabelFont();

                this._updateLabelDimensions();

                this._resetDynamicAtlas(comp);

                this._updateTexture(comp);

                this.updateOpacity(comp);

                comp._setCacheAlpha(_alpha);

                this._calDynamicAtlas(comp);

                comp.actualFontSize = _fontSize$1;
                trans.setContentSize(_canvasSize);
                this.updateVertexData(comp);
                this.updateUvs(comp);
                comp.markForUpdateRenderData(false);
                _context = null;
                _canvas = null;
                _texture = null;
              },
              updateVertexData: function updateVertexData(comp) {},
              updateUvs: function updateUvs(comp) {},
              updateOpacity: function updateOpacity(comp) {
                var vData = comp.renderData.vData;
                var colorOffset = 5;
                var colorA = comp.node._uiProps.opacity;

                for (var i = 0; i < 4; i++) {
                  vData[colorOffset + 3] = colorA;
                  colorOffset += 9;
                }
              },
              _updateFontFamily: function _updateFontFamily(comp) {
                if (!comp.useSystemFont) {
                  if (comp.font) {
                    if (comp.font._nativeAsset) {
                      _fontFamily = comp.font._nativeAsset;
                    } else {
                      assetManager.postLoadNative(comp.font, function (err) {
                        if (!comp.isValid) {
                          return;
                        }

                        _fontFamily = comp.font._nativeAsset || 'Arial';
                        comp.updateRenderData(true);
                      });
                      _fontFamily = 'Arial';
                    }
                  } else {
                    _fontFamily = 'Arial';
                  }
                } else {
                  _fontFamily = comp.fontFamily || 'Arial';
                }
              },
              _updateProperties: function _updateProperties(comp, trans) {
                var assemblerData = comp.assemblerData;

                if (!assemblerData) {
                  return;
                }

                _context = assemblerData.context;
                _canvas = assemblerData.canvas;
                _texture = comp.spriteFrame;
                _string$1 = comp.string.toString();
                _fontSize$1 = comp.fontSize;
                _drawFontsize = _fontSize$1;
                _overflow$1 = comp.overflow;
                _nodeContentSize.width = _canvasSize.width = trans.width;
                _nodeContentSize.height = _canvasSize.height = trans.height;
                _underlineThickness = comp.underlineHeight;
                _lineHeight$1 = comp.lineHeight;
                _hAlign$1 = comp.horizontalAlign;
                _vAlign$1 = comp.verticalAlign;
                _color = comp.color;
                _alpha = comp.node._uiProps.opacity;
                _isBold = comp.isBold;
                _isItalic = comp.isItalic;
                _isUnderline = comp.isUnderline;

                if (_overflow$1 === Overflow$1.NONE) {
                  _isWrapText$1 = false;
                } else if (_overflow$1 === Overflow$1.RESIZE_HEIGHT) {
                  _isWrapText$1 = true;
                } else {
                  _isWrapText$1 = comp.enableWrapText;
                }

                _outlineComp = LabelOutline && comp.getComponent(LabelOutline);
                _outlineComp = _outlineComp && _outlineComp.enabled && _outlineComp.width > 0 ? _outlineComp : null;

                if (_outlineComp) {
                  _outlineColor.set(_outlineComp.color);
                }

                _shadowComp = LabelShadow && comp.getComponent(LabelShadow);
                _shadowComp = _shadowComp && _shadowComp.enabled ? _shadowComp : null;

                if (_shadowComp) {
                  _shadowColor.set(_shadowComp.color);
                }

                this._updatePaddingRect();
              },
              _updatePaddingRect: function _updatePaddingRect() {
                var top = 0;
                var bottom = 0;
                var left = 0;
                var right = 0;
                var outlineWidth = 0;
                _contentSizeExtend.width = _contentSizeExtend.height = 0;

                if (_outlineComp) {
                  outlineWidth = _outlineComp.width;
                  top = bottom = left = right = outlineWidth;
                  _contentSizeExtend.width = _contentSizeExtend.height = outlineWidth * 2;
                }

                if (_shadowComp) {
                  var shadowWidth = _shadowComp.blur + outlineWidth;
                  var offsetX = _shadowComp.offset.x;
                  var offsetY = _shadowComp.offset.y;
                  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 (_isItalic) {
                  var offset = _drawFontsize * Math.tan(12 * 0.0174532925);

                  right += offset;
                  _contentSizeExtend.width += offset;
                }

                _canvasPadding.x = left;
                _canvasPadding.y = top;
                _canvasPadding.width = left + right;
                _canvasPadding.height = top + bottom;
              },
              _calculateFillTextStartPosition: function _calculateFillTextStartPosition() {
                var labelX = 0;

                if (_hAlign$1 === HorizontalTextAlignment.RIGHT) {
                  labelX = _canvasSize.width - _canvasPadding.width;
                } else if (_hAlign$1 === HorizontalTextAlignment.CENTER) {
                  labelX = (_canvasSize.width - _canvasPadding.width) / 2;
                }

                var lineHeight = this._getLineHeight();

                var drawStartY = lineHeight * (_splitStrings.length - 1);
                var firstLinelabelY = _fontSize$1 * (1 - BASELINE_RATIO / 2);

                if (_vAlign$1 !== VerticalTextAlignment.TOP) {
                  var blank = drawStartY + _canvasPadding.height + _fontSize$1 - _canvasSize.height;

                  if (_vAlign$1 === VerticalTextAlignment.BOTTOM) {
                    blank += BASELINE_RATIO / 2 * _fontSize$1;
                    firstLinelabelY -= blank;
                  } else {
                    firstLinelabelY -= blank / 2;
                  }
                }

                firstLinelabelY += _BASELINE_OFFSET$1 * _fontSize$1;

                _startPosition.set(labelX + _canvasPadding.x, firstLinelabelY + _canvasPadding.y);
              },
              _updateTexture: function _updateTexture(comp) {
                if (!_context || !_canvas) {
                  return;
                }

                _context.clearRect(0, 0, _canvas.width, _canvas.height);

                _context.font = _fontDesc;

                this._calculateFillTextStartPosition();

                var lineHeight = this._getLineHeight();

                _context.lineJoin = 'round';

                if (comp._srcBlendFactor === BlendFactor.SRC_ALPHA) {
                  _context.fillStyle = "rgba(" + _color.r + ", " + _color.g + ", " + _color.b + ", " + _invisibleAlpha + ")";

                  _context.fillRect(0, 0, _canvas.width, _canvas.height);
                }

                _context.fillStyle = "rgb(" + _color.r + ", " + _color.g + ", " + _color.b + ")";
                var drawTextPosX = _startPosition.x;
                var drawTextPosY = 0;

                this._drawTextEffect(_startPosition, lineHeight);

                for (var i = 0; i < _splitStrings.length; ++i) {
                  drawTextPosY = _startPosition.y + i * lineHeight;

                  if (_outlineComp) {
                    _context.strokeText(_splitStrings[i], drawTextPosX, drawTextPosY);
                  }

                  _context.fillText(_splitStrings[i], drawTextPosX, drawTextPosY);
                }

                if (_shadowComp) {
                  _context.shadowColor = 'transparent';
                }

                if (_texture) {
                  var tex;

                  if (_texture instanceof SpriteFrame) {
                    tex = _texture.texture;
                  } else {
                    tex = _texture;
                  }

                  var uploadAgain = _canvas.width !== 0 && _canvas.height !== 0;

                  if (uploadAgain) {
                    tex.reset({
                      width: _canvas.width,
                      height: _canvas.height,
                      mipmapLevel: 1
                    });
                    tex.uploadData(_canvas);

                    if (_texture instanceof SpriteFrame) {
                      _texture.rect = new Rect(0, 0, _canvas.width, _canvas.height);

                      _texture._calculateUV();
                    }

                    if (legacyCC.director.root && legacyCC.director.root.batcher2D) {
                      legacyCC.director.root.batcher2D._releaseDescriptorSetCache(tex.getHash());
                    }
                  }
                }
              },
              _resetDynamicAtlas: function _resetDynamicAtlas(comp) {
                if (comp.cacheMode !== Label.CacheMode.BITMAP) return;
                var frame = comp.ttfSpriteFrame;
                dynamicAtlasManager.deleteAtlasSpriteFrame(frame);

                frame._resetDynamicAtlasFrame();
              },
              _calDynamicAtlas: function _calDynamicAtlas(comp) {
                if (comp.cacheMode !== Label.CacheMode.BITMAP) return;
                var frame = comp.ttfSpriteFrame;
                dynamicAtlasManager.packToDynamicAtlas(comp, frame);
                comp.renderData.uvDirty = true;
              },
              _setupOutline: function _setupOutline() {
                _context.strokeStyle = "rgba(" + _outlineColor.r + ", " + _outlineColor.g + ", " + _outlineColor.b + ", " + _outlineColor.a / 255 + ")";
                _context.lineWidth = _outlineComp.width * 2;
              },
              _setupShadow: function _setupShadow() {
                _context.shadowColor = "rgba(" + _shadowColor.r + ", " + _shadowColor.g + ", " + _shadowColor.b + ", " + _shadowColor.a / 255 + ")";
                _context.shadowBlur = _shadowComp.blur;
                _context.shadowOffsetX = _shadowComp.offset.x;
                _context.shadowOffsetY = -_shadowComp.offset.y;
              },
              _drawTextEffect: function _drawTextEffect(startPosition, lineHeight) {
                if (!_shadowComp && !_outlineComp && !_isUnderline) return;
                var isMultiple = _splitStrings.length > 1 && _shadowComp;

                var measureText = this._measureText(_context, _fontDesc);

                var drawTextPosX = 0;
                var drawTextPosY = 0;

                if (_shadowComp) {
                  this._setupShadow();
                }

                if (_outlineComp) {
                  this._setupOutline();
                }

                for (var i = 0; i < _splitStrings.length; ++i) {
                  drawTextPosX = startPosition.x;
                  drawTextPosY = startPosition.y + i * lineHeight;

                  if (isMultiple) {
                    if (_outlineComp) {
                      _context.strokeText(_splitStrings[i], drawTextPosX, drawTextPosY);
                    }

                    _context.fillText(_splitStrings[i], drawTextPosX, drawTextPosY);
                  }

                  if (_isUnderline) {
                    _drawUnderlineWidth = measureText(_splitStrings[i]);

                    if (_hAlign$1 === HorizontalTextAlignment.RIGHT) {
                      _drawUnderlinePos.x = startPosition.x - _drawUnderlineWidth;
                    } else if (_hAlign$1 === HorizontalTextAlignment.CENTER) {
                      _drawUnderlinePos.x = startPosition.x - _drawUnderlineWidth / 2;
                    } else {
                      _drawUnderlinePos.x = startPosition.x;
                    }

                    _drawUnderlinePos.y = drawTextPosY + _drawFontsize / 8;

                    _context.fillRect(_drawUnderlinePos.x, _drawUnderlinePos.y, _drawUnderlineWidth, _underlineThickness);
                  }
                }

                if (isMultiple) {
                  _context.shadowColor = 'transparent';
                }
              },
              _updateLabelDimensions: function _updateLabelDimensions() {
                _canvasSize.width = Math.min(_canvasSize.width, MAX_SIZE$1);
                _canvasSize.height = Math.min(_canvasSize.height, MAX_SIZE$1);
                var recreate = false;

                if (_canvas.width !== _canvasSize.width) {
                  _canvas.width = _canvasSize.width;
                  recreate = true;
                }

                if (_canvas.height !== _canvasSize.height) {
                  _canvas.height = _canvasSize.height;
                  recreate = true;
                }

                if (recreate) _context.font = _fontDesc;
                _context.textAlign = Alignment[_hAlign$1];
                _context.textBaseline = 'alphabetic';
              },
              _getFontDesc: function _getFontDesc() {
                var fontDesc = _fontSize$1.toString() + "px ";
                fontDesc += _fontFamily;

                if (_isBold) {
                  fontDesc = "bold " + fontDesc;
                }

                if (_isItalic) {
                  fontDesc = "italic " + fontDesc;
                }

                return fontDesc;
              },
              _getLineHeight: function _getLineHeight() {
                var nodeSpacingY = _lineHeight$1;

                if (nodeSpacingY === 0) {
                  nodeSpacingY = _fontSize$1;
                } else {
                  nodeSpacingY = nodeSpacingY * _fontSize$1 / _drawFontsize;
                }

                return nodeSpacingY | 0;
              },
              _calculateParagraphLength: function _calculateParagraphLength(paragraphedStrings, ctx) {
                var paragraphLength = [];

                for (var _iterator = _createForOfIteratorHelperLoose(paragraphedStrings), _step; !(_step = _iterator()).done;) {
                  var para = _step.value;
                  var width = safeMeasureText(ctx, para, _fontDesc);
                  paragraphLength.push(width);
                }

                return paragraphLength;
              },
              _measureText: function _measureText(ctx, fontDesc) {
                return function (string) {
                  return safeMeasureText(ctx, string, fontDesc);
                };
              },
              _calculateShrinkFont: function _calculateShrinkFont(paragraphedStrings) {
                if (!_context) return;

                var paragraphLength = this._calculateParagraphLength(paragraphedStrings, _context);

                var i = 0;
                var totalHeight = 0;
                var maxLength = 0;

                if (_isWrapText$1) {
                  var canvasWidthNoMargin = _nodeContentSize.width;
                  var canvasHeightNoMargin = _nodeContentSize.height;

                  if (canvasWidthNoMargin < 0 || canvasHeightNoMargin < 0) {
                    return;
                  }

                  totalHeight = canvasHeightNoMargin + 1;
                  var actualFontSize = _fontSize$1 + 1;
                  var textFragment = [];
                  var left = 0;
                  var right = actualFontSize | 0;
                  var mid = 0;

                  while (left < right) {
                    mid = left + right + 1 >> 1;

                    if (mid <= 0) {
                      logID(4003);
                      break;
                    }

                    _fontSize$1 = mid;
                    _fontDesc = this._getFontDesc();
                    _context.font = _fontDesc;

                    var lineHeight = this._getLineHeight();

                    totalHeight = 0;

                    for (i = 0; i < paragraphedStrings.length; ++i) {
                      var allWidth = safeMeasureText(_context, paragraphedStrings[i], _fontDesc);
                      textFragment = fragmentText(paragraphedStrings[i], allWidth, canvasWidthNoMargin, this._measureText(_context, _fontDesc));
                      totalHeight += textFragment.length * lineHeight;
                    }

                    if (totalHeight > canvasHeightNoMargin) {
                      right = mid - 1;
                    } else {
                      left = mid;
                    }
                  }

                  if (left === 0) {
                    logID(4003);
                  } else {
                    _fontSize$1 = left;
                    _fontDesc = this._getFontDesc();
                    _context.font = _fontDesc;
                  }
                } else {
                  totalHeight = paragraphedStrings.length * this._getLineHeight();

                  for (i = 0; i < paragraphedStrings.length; ++i) {
                    if (maxLength < paragraphLength[i]) {
                      maxLength = paragraphLength[i];
                    }
                  }

                  var scaleX = (_canvasSize.width - _canvasPadding.width) / maxLength;
                  var scaleY = _canvasSize.height / totalHeight;
                  _fontSize$1 = _drawFontsize * Math.min(1, scaleX, scaleY) | 0;
                  _fontDesc = this._getFontDesc();
                  _context.font = _fontDesc;
                }
              },
              _calculateWrapText: function _calculateWrapText(paragraphedStrings) {
                if (!_isWrapText$1 || !_context) return;
                _splitStrings = [];
                var canvasWidthNoMargin = _nodeContentSize.width;

                for (var i = 0; i < paragraphedStrings.length; ++i) {
                  var allWidth = safeMeasureText(_context, paragraphedStrings[i], _fontDesc);
                  var textFragment = fragmentText(paragraphedStrings[i], allWidth, canvasWidthNoMargin, this._measureText(_context, _fontDesc));
                  _splitStrings = _splitStrings.concat(textFragment);
                }
              },
              _calculateLabelFont: function _calculateLabelFont() {
                if (!_context) {
                  return;
                }

                var paragraphedStrings = _string$1.split('\n');

                _splitStrings = paragraphedStrings;
                _fontDesc = this._getFontDesc();
                _context.font = _fontDesc;

                switch (_overflow$1) {
                  case Overflow$1.NONE:
                    {
                      var canvasSizeX = 0;
                      var canvasSizeY = 0;

                      for (var i = 0; i < paragraphedStrings.length; ++i) {
                        var paraLength = safeMeasureText(_context, paragraphedStrings[i], _fontDesc);
                        canvasSizeX = canvasSizeX > paraLength ? canvasSizeX : paraLength;
                      }

                      canvasSizeY = (_splitStrings.length + BASELINE_RATIO) * this._getLineHeight();
                      var rawWidth = parseFloat(canvasSizeX.toFixed(2));
                      var rawHeight = parseFloat(canvasSizeY.toFixed(2));
                      _canvasSize.width = rawWidth + _canvasPadding.width;
                      _canvasSize.height = rawHeight + _canvasPadding.height;
                      _nodeContentSize.width = rawWidth + _contentSizeExtend.width;
                      _nodeContentSize.height = rawHeight + _contentSizeExtend.height;
                      break;
                    }

                  case Overflow$1.SHRINK:
                    {
                      this._calculateShrinkFont(paragraphedStrings);

                      this._calculateWrapText(paragraphedStrings);

                      break;
                    }

                  case Overflow$1.CLAMP:
                    {
                      this._calculateWrapText(paragraphedStrings);

                      break;
                    }

                  case Overflow$1.RESIZE_HEIGHT:
                    {
                      this._calculateWrapText(paragraphedStrings);

                      var _rawHeight = (_splitStrings.length + BASELINE_RATIO) * this._getLineHeight();

                      _canvasSize.height = _rawHeight + _canvasPadding.height;
                      _nodeContentSize.height = _rawHeight + _contentSizeExtend.height;
                      break;
                    }
                }
              }
            };

            var WHITE$2 = Color.WHITE.clone();
            var ttf = {
              createData: function createData(comp) {
                var renderData = comp.requestRenderData();
                renderData.dataLength = 4;
                renderData.vertexCount = 4;
                renderData.indicesCount = 6;
                var vData = renderData.vData = new Float32Array(4 * 9);
                vData[3] = vData[21] = vData[22] = vData[31] = 0;
                vData[4] = vData[12] = vData[13] = vData[30] = 1;
                var offset = 5;

                for (var i = 0; i < 4; i++) {
                  Color.toArray(vData, WHITE$2, offset);
                  offset += 9;
                }

                return renderData;
              },
              fillBuffers: function fillBuffers(comp, renderer) {
                var renderData = comp.renderData;
                var dataList = renderData.data;
                var node = comp.node;
                var buffer = renderer.acquireBufferBatch();
                var vertexOffset = buffer.byteOffset >> 2;
                var indicesOffset = buffer.indicesOffset;
                var vertexId = buffer.vertexOffset;
                var isRecreate = buffer.request();

                if (!isRecreate) {
                  buffer = renderer.currBufferBatch;
                  indicesOffset = 0;
                  vertexId = 0;
                  vertexOffset = 0;
                }

                var vBuf = buffer.vData;
                var iBuf = buffer.iData;
                var vData = renderData.vData;
                var data0 = dataList[0];
                var data3 = dataList[3];
                node.updateWorldTransform();
                var pos = node._pos;
                var rot = node._rot;
                var scale = node._scale;
                var ax = data0.x * scale.x;
                var bx = data3.x * scale.x;
                var ay = data0.y * scale.y;
                var by = data3.y * scale.y;
                var qx = rot.x;
                var qy = rot.y;
                var qz = rot.z;
                var qw = rot.w;
                var qxy = qx * qy;
                var qzw = qz * qw;
                var qxy2 = qx * qx - qy * qy;
                var qzw2 = qw * qw - qz * qz;
                var cx1 = qzw2 + qxy2;
                var cx2 = (qxy - qzw) * 2;
                var cy1 = qzw2 - qxy2;
                var cy2 = (qxy + qzw) * 2;
                var x = pos.x;
                var y = pos.y;
                vData[0] = cx1 * ax + cx2 * ay + x;
                vData[1] = cy1 * ay + cy2 * ax + y;
                vData[9] = cx1 * bx + cx2 * ay + x;
                vData[10] = cy1 * ay + cy2 * bx + y;
                vData[18] = cx1 * ax + cx2 * by + x;
                vData[19] = cy1 * by + cy2 * ax + y;
                vData[27] = cx1 * bx + cx2 * by + x;
                vData[28] = cy1 * by + cy2 * bx + y;
                vBuf.set(vData, vertexOffset);
                iBuf[indicesOffset++] = vertexId;
                iBuf[indicesOffset++] = vertexId + 1;
                iBuf[indicesOffset++] = vertexId + 2;
                iBuf[indicesOffset++] = vertexId + 2;
                iBuf[indicesOffset++] = vertexId + 1;
                iBuf[indicesOffset++] = vertexId + 3;
              },
              updateVertexData: function updateVertexData(comp) {
                var renderData = comp.renderData;

                if (!renderData) {
                  return;
                }

                var uiTrans = comp.node._uiProps.uiTransformComp;
                var width = uiTrans.width;
                var height = uiTrans.height;
                var appX = uiTrans.anchorX * width;
                var appY = uiTrans.anchorY * height;
                var data = renderData.data;
                data[0].x = -appX;
                data[0].y = -appY;
                data[3].x = width - appX;
                data[3].y = height - appY;
              },
              updateUvs: function updateUvs(comp) {
                var renderData = comp.renderData;

                if (!renderData) {
                  return;
                }

                var vData = renderData.vData;

                if (!vData || !renderData.uvDirty) {
                  return;
                }

                var uv = comp.ttfSpriteFrame.uv;
                vData[3] = uv[0];
                vData[4] = uv[1];
                vData[12] = uv[2];
                vData[13] = uv[3];
                vData[21] = uv[4];
                vData[22] = uv[5];
                vData[30] = uv[6];
                vData[31] = uv[7];
                renderData.uvDirty = false;
              }
            };
            addon(ttf, ttfUtils);

            var labelAssembler = exports('labelAssembler', {
              getAssembler: function getAssembler(comp) {
                var assembler = ttf;

                if (comp.font instanceof BitmapFont) {
                  assembler = bmfont;
                } else if (comp.cacheMode === Label.CacheMode.CHAR) {
                  assembler = letter;
                }

                return assembler;
              }
            });
            Label.Assembler = labelAssembler;

            var FillType$1 = Sprite.FillType;
            var matrix = new Mat4();
            var tempColor$1 = new Color(255, 255, 255, 255);
            var barFilled = {
              useModel: false,
              updateRenderData: function updateRenderData(sprite) {
                var frame = sprite.spriteFrame;
                dynamicAtlasManager.packToDynamicAtlas(sprite, frame);
                var renderData = sprite.renderData;

                if (renderData && frame) {
                  var uvDirty = renderData.uvDirty;
                  var vertDirty = renderData.vertDirty;

                  if (!uvDirty && !vertDirty) {
                    return;
                  }

                  var fillStart = sprite.fillStart;
                  var fillRange = sprite.fillRange;

                  if (fillRange < 0) {
                    fillStart += fillRange;
                    fillRange = -fillRange;
                  }

                  fillRange = fillStart + fillRange;
                  fillStart = fillStart > 1.0 ? 1.0 : fillStart;
                  fillStart = fillStart < 0.0 ? 0.0 : fillStart;
                  fillRange = fillRange > 1.0 ? 1.0 : fillRange;
                  fillRange = fillRange < 0.0 ? 0.0 : fillRange;
                  fillRange -= fillStart;
                  fillRange = fillRange < 0 ? 0 : fillRange;
                  var fillEnd = fillStart + fillRange;
                  fillEnd = fillEnd > 1 ? 1 : fillEnd;

                  if (uvDirty) {
                    this.updateUVs(sprite, fillStart, fillEnd);
                  }

                  if (vertDirty) {
                    if (this.updateVertexData) {
                      this.updateVertexData(sprite, fillStart, fillEnd);
                    }

                    this.updateWorldVertexData(sprite);
                  }
                }
              },
              updateUVs: function updateUVs(sprite, fillStart, fillEnd) {
                var spriteFrame = sprite.spriteFrame;
                var renderData = sprite.renderData;
                var dataList = renderData.data;
                var atlasWidth = spriteFrame.width;
                var atlasHeight = spriteFrame.height;
                var textureRect = spriteFrame.getRect();
                var ul = 0;
                var vb = 0;
                var ur = 0;
                var vt = 0;
                var quadUV0 = 0;
                var quadUV1 = 0;
                var quadUV2 = 0;
                var quadUV3 = 0;
                var quadUV4 = 0;
                var quadUV5 = 0;
                var quadUV6 = 0;
                var quadUV7 = 0;

                if (spriteFrame.isRotated()) {
                  ul = textureRect.x / atlasWidth;
                  vb = (textureRect.y + textureRect.width) / atlasHeight;
                  ur = (textureRect.x + textureRect.height) / atlasWidth;
                  vt = textureRect.y / atlasHeight;
                  quadUV0 = quadUV2 = ul;
                  quadUV4 = quadUV6 = ur;
                  quadUV3 = quadUV7 = vb;
                  quadUV1 = quadUV5 = vt;
                } else {
                  ul = textureRect.x / atlasWidth;
                  vb = (textureRect.y + textureRect.height) / atlasHeight;
                  ur = (textureRect.x + textureRect.width) / atlasWidth;
                  vt = textureRect.y / atlasHeight;
                  quadUV0 = quadUV4 = ul;
                  quadUV2 = quadUV6 = ur;
                  quadUV1 = quadUV3 = vb;
                  quadUV5 = quadUV7 = vt;
                }

                switch (sprite.fillType) {
                  case FillType$1.HORIZONTAL:
                    dataList[0].u = quadUV0 + (quadUV2 - quadUV0) * fillStart;
                    dataList[0].v = quadUV1 + (quadUV3 - quadUV1) * fillStart;
                    dataList[1].u = quadUV0 + (quadUV2 - quadUV0) * fillEnd;
                    dataList[1].v = quadUV1 + (quadUV3 - quadUV1) * fillEnd;
                    dataList[2].u = quadUV4 + (quadUV6 - quadUV4) * fillStart;
                    dataList[2].v = quadUV5 + (quadUV7 - quadUV5) * fillStart;
                    dataList[3].u = quadUV4 + (quadUV6 - quadUV4) * fillEnd;
                    dataList[3].v = quadUV5 + (quadUV7 - quadUV5) * fillEnd;
                    break;

                  case FillType$1.VERTICAL:
                    dataList[0].u = quadUV0 + (quadUV4 - quadUV0) * fillStart;
                    dataList[0].v = quadUV1 + (quadUV5 - quadUV1) * fillStart;
                    dataList[1].u = quadUV2 + (quadUV6 - quadUV2) * fillStart;
                    dataList[1].v = quadUV3 + (quadUV7 - quadUV3) * fillStart;
                    dataList[2].u = quadUV0 + (quadUV4 - quadUV0) * fillEnd;
                    dataList[2].v = quadUV1 + (quadUV5 - quadUV1) * fillEnd;
                    dataList[3].u = quadUV2 + (quadUV6 - quadUV2) * fillEnd;
                    dataList[3].v = quadUV3 + (quadUV7 - quadUV3) * fillEnd;
                    break;

                  default:
                    errorID(2626);
                    break;
                }

                renderData.uvDirty = false;
              },
              updateVertexData: function updateVertexData(sprite, fillStart, fillEnd) {
                var renderData = sprite.renderData;
                var dataList = renderData.data;
                var uiTrans = sprite.node._uiProps.uiTransformComp;
                var width = uiTrans.width;
                var height = uiTrans.height;
                var appX = uiTrans.anchorX * width;
                var appY = uiTrans.anchorY * height;
                var l = -appX;
                var b = -appY;
                var r = width - appX;
                var t = height - appY;
                var progressStart = 0;
                var progressEnd = 0;

                switch (sprite.fillType) {
                  case FillType$1.HORIZONTAL:
                    progressStart = l + (r - l) * fillStart;
                    progressEnd = l + (r - l) * fillEnd;
                    l = progressStart;
                    r = progressEnd;
                    break;

                  case FillType$1.VERTICAL:
                    progressStart = b + (t - b) * fillStart;
                    progressEnd = b + (t - b) * fillEnd;
                    b = progressStart;
                    t = progressEnd;
                    break;

                  default:
                    errorID(2626);
                    break;
                }

                dataList[4].x = l;
                dataList[4].y = b;
                dataList[5].x = r;
                dataList[5].y = b;
                dataList[6].x = l;
                dataList[6].y = t;
                dataList[7].x = r;
                dataList[7].y = t;
                renderData.vertDirty = false;
              },
              createData: function createData(sprite) {
                var renderData = sprite.requestRenderData();
                renderData.dataLength = 8;
                renderData.vertexCount = 4;
                renderData.indicesCount = 6;
                var dataList = renderData.data;

                for (var _iterator = _createForOfIteratorHelperLoose(dataList), _step; !(_step = _iterator()).done;) {
                  var data = _step.value;
                  data.z = 0;
                }

                return renderData;
              },
              updateWorldVertexData: function updateWorldVertexData(sprite) {
                var node = sprite.node;
                var dataList = sprite.renderData.data;
                node.getWorldMatrix(matrix);

                for (var i = 0; i < 4; i++) {
                  var local = dataList[i + 4];
                  var world = dataList[i];
                  Vec3.transformMat4(world, local, matrix);
                }
              },
              fillBuffers: function fillBuffers(sprite, renderer) {
                if (sprite.node.hasChangedFlags) {
                  this.updateWorldVertexData(sprite);
                }

                var node = sprite.node;
                tempColor$1.set(sprite.color);
                tempColor$1.a = node._uiProps.opacity * 255;
                fillVerticesWithoutCalc3D(node, renderer, sprite.renderData, tempColor$1);
              },
              updateColor: function updateColor(sprite) {}
            };

            var PI_2 = Math.PI * 2;
            var EPSILON$1 = 1e-6;
            var tempColor$2 = new Color(255, 255, 255, 255);
            var _vertPos = [new Vec2(), new Vec2(), new Vec2(), new Vec2()];

            var _vertices = new Array(4);

            var _uvs = new Array(8);

            var _intersectPoint_1 = [new Vec2(), new Vec2(), new Vec2(), new Vec2()];
            var _intersectPoint_2 = [new Vec2(), new Vec2(), new Vec2(), new Vec2()];

            var _center = new Vec2();

            var _triangles = [new Vec2(), new Vec2(), new Vec2(), new Vec2()];

            function _calcIntersectedPoints(left, right, bottom, top, center, angle, intersectPoints) {
              var sinAngle = Math.sin(angle);
              sinAngle = Math.abs(sinAngle) > EPSILON$1 ? sinAngle : 0;
              var cosAngle = Math.cos(angle);
              cosAngle = Math.abs(cosAngle) > EPSILON$1 ? cosAngle : 0;
              var tanAngle = 0;
              var cotAngle = 0;

              if (cosAngle !== 0) {
                tanAngle = sinAngle / cosAngle;

                if ((left - center.x) * cosAngle > 0) {
                  var yLeft = center.y + tanAngle * (left - center.x);
                  intersectPoints[0].x = left;
                  intersectPoints[0].y = yLeft;
                }

                if ((right - center.x) * cosAngle > 0) {
                  var yRight = center.y + tanAngle * (right - center.x);
                  intersectPoints[2].x = right;
                  intersectPoints[2].y = yRight;
                }
              }

              if (sinAngle !== 0) {
                cotAngle = cosAngle / sinAngle;

                if ((top - center.y) * sinAngle > 0) {
                  var xTop = center.x + cotAngle * (top - center.y);
                  intersectPoints[3].x = xTop;
                  intersectPoints[3].y = top;
                }

                if ((bottom - center.y) * sinAngle > 0) {
                  var xBottom = center.x + cotAngle * (bottom - center.y);
                  intersectPoints[1].x = xBottom;
                  intersectPoints[1].y = bottom;
                }
              }
            }

            function _calculateVertices(sprite) {
              var uiTrans = sprite.node._uiProps.uiTransformComp;
              var width = uiTrans.width;
              var height = uiTrans.height;
              var appX = uiTrans.anchorX * width;
              var appY = uiTrans.anchorY * height;
              var l = -appX;
              var b = -appY;
              var r = width - appX;
              var t = height - appY;
              var vertices = _vertices;
              vertices[0] = l;
              vertices[1] = b;
              vertices[2] = r;
              vertices[3] = t;
              var fillCenter = sprite.fillCenter;
              var cx = _center.x = Math.min(Math.max(0, fillCenter.x), 1) * (r - l) + l;
              var cy = _center.y = Math.min(Math.max(0, fillCenter.y), 1) * (t - b) + b;
              _vertPos[0].x = _vertPos[3].x = l;
              _vertPos[1].x = _vertPos[2].x = r;
              _vertPos[0].y = _vertPos[1].y = b;
              _vertPos[2].y = _vertPos[3].y = t;

              for (var _iterator = _createForOfIteratorHelperLoose(_triangles), _step; !(_step = _iterator()).done;) {
                var num = _step.value;
                Vec2.set(num, 0, 0);
              }

              if (cx !== vertices[0]) {
                Vec2.set(_triangles[0], 3, 0);
              }

              if (cx !== vertices[2]) {
                Vec2.set(_triangles[2], 1, 2);
              }

              if (cy !== vertices[1]) {
                Vec2.set(_triangles[1], 0, 1);
              }

              if (cy !== vertices[3]) {
                Vec2.set(_triangles[3], 2, 3);
              }
            }

            function _calculateUVs(spriteFrame) {
              var atlasWidth = spriteFrame.width;
              var atlasHeight = spriteFrame.height;
              var textureRect = spriteFrame.getRect();
              var u0 = 0;
              var u1 = 0;
              var v0 = 0;
              var v1 = 0;
              var uvs = _uvs;

              if (spriteFrame.isRotated()) {
                u0 = textureRect.x / atlasWidth;
                u1 = (textureRect.x + textureRect.height) / atlasWidth;
                v0 = textureRect.y / atlasHeight;
                v1 = (textureRect.y + textureRect.width) / atlasHeight;
                uvs[0] = uvs[2] = u0;
                uvs[4] = uvs[6] = u1;
                uvs[3] = uvs[7] = v1;
                uvs[1] = uvs[5] = v0;
              } else {
                u0 = textureRect.x / atlasWidth;
                u1 = (textureRect.x + textureRect.width) / atlasWidth;
                v0 = textureRect.y / atlasHeight;
                v1 = (textureRect.y + textureRect.height) / atlasHeight;
                uvs[0] = uvs[4] = u0;
                uvs[2] = uvs[6] = u1;
                uvs[1] = uvs[3] = v1;
                uvs[5] = uvs[7] = v0;
              }
            }

            function _getVertAngle(start, end) {
              var placementX = end.x - start.x;
              var placementY = end.y - start.y;

              if (placementX === 0 && placementY === 0) {
                return 0;
              } else if (placementX === 0) {
                if (placementY > 0) {
                  return Math.PI * 0.5;
                } else {
                  return Math.PI * 1.5;
                }
              } else {
                var angle = Math.atan(placementY / placementX);

                if (placementX < 0) {
                  angle += Math.PI;
                }

                return angle;
              }
            }

            function _generateTriangle(dataList, offset, vert0, vert1, vert2) {
              var vertices = _vertices;
              var v0x = vertices[0];
              var v0y = vertices[1];
              var v1x = vertices[2];
              var v1y = vertices[3];
              dataList[offset].x = vert0.x;
              dataList[offset].y = vert0.y;
              dataList[offset + 1].x = vert1.x;
              dataList[offset + 1].y = vert1.y;
              dataList[offset + 2].x = vert2.x;
              dataList[offset + 2].y = vert2.y;
              var progressX = 0;
              var progressY = 0;
              progressX = (vert0.x - v0x) / (v1x - v0x);
              progressY = (vert0.y - v0y) / (v1y - v0y);

              _generateUV(progressX, progressY, dataList, offset);

              progressX = (vert1.x - v0x) / (v1x - v0x);
              progressY = (vert1.y - v0y) / (v1y - v0y);

              _generateUV(progressX, progressY, dataList, offset + 1);

              progressX = (vert2.x - v0x) / (v1x - v0x);
              progressY = (vert2.y - v0y) / (v1y - v0y);

              _generateUV(progressX, progressY, dataList, offset + 2);
            }

            function _generateUV(progressX, progressY, data, offset) {
              var uvs = _uvs;
              var px1 = uvs[0] + (uvs[2] - uvs[0]) * progressX;
              var px2 = uvs[4] + (uvs[6] - uvs[4]) * progressX;
              var py1 = uvs[1] + (uvs[3] - uvs[1]) * progressX;
              var py2 = uvs[5] + (uvs[7] - uvs[5]) * progressX;
              var uv = data[offset];
              uv.u = px1 + (px2 - px1) * progressY;
              uv.v = py1 + (py2 - py1) * progressY;
            }

            var radialFilled = {
              useModel: false,
              createData: function createData(sprite) {
                return sprite.requestRenderData();
              },
              updateRenderData: function updateRenderData(sprite) {
                var frame = sprite.spriteFrame;
                dynamicAtlasManager.packToDynamicAtlas(sprite, frame);
                var renderData = sprite.renderData;

                if (renderData && frame) {
                  if (renderData.vertDirty || renderData.uvDirty) {
                    var dataList = renderData.data;
                    var fillStart = sprite.fillStart;
                    var fillRange = sprite.fillRange;

                    if (fillRange < 0) {
                      fillStart += fillRange;
                      fillRange = -fillRange;
                    }

                    while (fillStart >= 1.0) {
                      fillStart -= 1.0;
                    }

                    while (fillStart < 0.0) {
                      fillStart += 1.0;
                    }

                    fillStart *= PI_2;
                    fillRange *= PI_2;
                    var fillEnd = fillStart + fillRange;

                    _calculateVertices(sprite);

                    _calculateUVs(frame);

                    _calcIntersectedPoints(_vertices[0], _vertices[2], _vertices[1], _vertices[3], _center, fillStart, _intersectPoint_1);

                    _calcIntersectedPoints(_vertices[0], _vertices[2], _vertices[1], _vertices[3], _center, fillStart + fillRange, _intersectPoint_2);

                    var offset = 0;

                    for (var triangleIndex = 0; triangleIndex < 4; ++triangleIndex) {
                      var triangle = _triangles[triangleIndex];

                      if (!triangle) {
                        continue;
                      }

                      if (fillRange >= PI_2) {
                        renderData.dataLength = offset + 3;

                        _generateTriangle(dataList, offset, _center, _vertPos[triangle.x], _vertPos[triangle.y]);

                        offset += 3;
                        continue;
                      }

                      var startAngle = _getVertAngle(_center, _vertPos[triangle.x]);

                      var endAngle = _getVertAngle(_center, _vertPos[triangle.y]);

                      if (endAngle < startAngle) {
                        endAngle += PI_2;
                      }

                      startAngle -= PI_2;
                      endAngle -= PI_2;

                      for (var testIndex = 0; testIndex < 3; ++testIndex) {
                        if (startAngle >= fillEnd) ; else if (startAngle >= fillStart) {
                          renderData.dataLength = offset + 3;

                          if (endAngle >= fillEnd) {
                            _generateTriangle(dataList, offset, _center, _vertPos[triangle.x], _intersectPoint_2[triangleIndex]);
                          } else {
                            _generateTriangle(dataList, offset, _center, _vertPos[triangle.x], _vertPos[triangle.y]);
                          }

                          offset += 3;
                        } else if (endAngle > fillStart) {
                          if (endAngle <= fillEnd) {
                            renderData.dataLength = offset + 3;

                            _generateTriangle(dataList, offset, _center, _intersectPoint_1[triangleIndex], _vertPos[triangle.y]);

                            offset += 3;
                          } else {
                            renderData.dataLength = offset + 3;

                            _generateTriangle(dataList, offset, _center, _intersectPoint_1[triangleIndex], _intersectPoint_2[triangleIndex]);

                            offset += 3;
                          }
                        }

                        startAngle += PI_2;
                        endAngle += PI_2;
                      }
                    }

                    renderData.indicesCount = renderData.vertexCount = offset;
                    renderData.vertDirty = renderData.uvDirty = false;
                  }
                }
              },
              fillBuffers: function fillBuffers(comp, renderer) {
                var node = comp.node;
                var renderData = comp.renderData;
                tempColor$2.set(comp.color);
                tempColor$2.a = node._uiProps.opacity * 255;
                fillVertices3D(node, renderer, renderData, tempColor$2);
              },
              updateColor: function updateColor(sprite) {}
            };

            var vec3_temps$1 = [];

            for (var i$2 = 0; i$2 < 4; i$2++) {
              vec3_temps$1.push(new Vec3());
            }

            var simple = {
              createData: function createData(sprite) {
                var renderData = sprite.requestRenderData();
                renderData.dataLength = 4;
                renderData.vertexCount = 4;
                renderData.indicesCount = 6;
                renderData.vData = new Float32Array(4 * 9);
                return renderData;
              },
              updateRenderData: function updateRenderData(sprite) {
                var frame = sprite.spriteFrame;
                dynamicAtlasManager.packToDynamicAtlas(sprite, frame);
                var renderData = sprite.renderData;

                if (renderData && frame) {
                  if (renderData.vertDirty) {
                    this.updateVertexData(sprite);
                  }

                  if (renderData.uvDirty) {
                    this.updateUvs(sprite);
                  }
                }
              },
              updateWorldVerts: function updateWorldVerts(sprite, vData) {
                var renderData = sprite.renderData;
                var dataList = renderData.data;
                var node = sprite.node;
                var data0 = dataList[0];
                var data3 = dataList[3];
                var matrix = node.worldMatrix;
                var a = matrix.m00;
                var b = matrix.m01;
                var c = matrix.m04;
                var d = matrix.m05;
                var justTranslate = a === 1 && b === 0 && c === 0 && d === 1;
                var tx = matrix.m12;
                var ty = matrix.m13;
                var vl = data0.x;
                var vr = data3.x;
                var vb = data0.y;
                var vt = data3.y;

                if (justTranslate) {
                  var vltx = vl + tx;
                  var vrtx = vr + tx;
                  var vbty = vb + ty;
                  var vtty = vt + ty;
                  vData[0] = vltx;
                  vData[1] = vbty;
                  vData[9] = vrtx;
                  vData[10] = vbty;
                  vData[18] = vltx;
                  vData[19] = vtty;
                  vData[27] = vrtx;
                  vData[28] = vtty;
                } else {
                  var al = a * vl;
                  var ar = a * vr;
                  var bl = b * vl;
                  var br = b * vr;
                  var cb = c * vb;
                  var ct = c * vt;
                  var db = d * vb;
                  var dt = d * vt;
                  var cbtx = cb + tx;
                  var cttx = ct + tx;
                  var dbty = db + ty;
                  var dtty = dt + ty;
                  vData[0] = al + cbtx;
                  vData[1] = bl + dbty;
                  vData[9] = ar + cbtx;
                  vData[10] = br + dbty;
                  vData[18] = al + cttx;
                  vData[19] = bl + dtty;
                  vData[27] = ar + cttx;
                  vData[28] = br + dtty;
                }

                node._uiProps.uiTransformDirty = false;
              },
              fillBuffers: function fillBuffers(sprite, renderer) {
                if (sprite === null) {
                  return;
                }

                var vData = sprite.renderData.vData;

                if (sprite.node._uiProps.uiTransformDirty) {
                  this.updateWorldVerts(sprite, vData);
                }

                var buffer = renderer.acquireBufferBatch();
                var vertexOffset = buffer.byteOffset >> 2;
                var indicesOffset = buffer.indicesOffset;
                var vertexId = buffer.vertexOffset;
                var bufferUnchanged = buffer.request();

                if (!bufferUnchanged) {
                  buffer = renderer.currBufferBatch;
                  vertexOffset = 0;
                  indicesOffset = 0;
                  vertexId = 0;
                }

                var vBuf = buffer.vData;
                var iBuf = buffer.iData;
                vBuf.set(vData, vertexOffset);
                var index0 = vertexId;
                var index1 = vertexId + 1;
                var index2 = vertexId + 2;
                var index3 = vertexId + 3;
                iBuf[indicesOffset++] = index0;
                iBuf[indicesOffset++] = index1;
                iBuf[indicesOffset++] = index2;
                iBuf[indicesOffset++] = index2;
                iBuf[indicesOffset++] = index1;
                iBuf[indicesOffset++] = index3;
              },
              updateVertexData: function updateVertexData(sprite) {
                var renderData = sprite.renderData;

                if (!renderData) {
                  return;
                }

                var uiTrans = sprite.node._uiProps.uiTransformComp;
                var dataList = renderData.data;
                var cw = uiTrans.width;
                var ch = uiTrans.height;
                var appX = uiTrans.anchorX * cw;
                var appY = uiTrans.anchorY * ch;
                var l = 0;
                var b = 0;
                var r = 0;
                var t = 0;

                if (sprite.trim) {
                  l = -appX;
                  b = -appY;
                  r = cw - appX;
                  t = ch - appY;
                } else {
                  var frame = sprite.spriteFrame;
                  var originSize = frame.getOriginalSize();
                  var rect = frame.getRect();
                  var ow = originSize.width;
                  var oh = originSize.height;
                  var rw = rect.width;
                  var rh = rect.height;
                  var offset = frame.getOffset();
                  var scaleX = cw / ow;
                  var scaleY = ch / oh;
                  var trimLeft = offset.x + (ow - rw) / 2;
                  var trimRight = offset.x - (ow - rw) / 2;
                  var trimBottom = offset.y + (oh - rh) / 2;
                  var trimTop = offset.y - (oh - rh) / 2;
                  l = trimLeft * scaleX - appX;
                  b = trimBottom * scaleY - appY;
                  r = cw + trimRight * scaleX - appX;
                  t = ch + trimTop * scaleY - appY;
                }

                dataList[0].x = l;
                dataList[0].y = b;
                dataList[3].x = r;
                dataList[3].y = t;
                renderData.vertDirty = false;
                this.updateWorldVerts(sprite, renderData.vData);
              },
              updateUvs: function updateUvs(sprite) {
                var renderData = sprite.renderData;
                var vData = renderData.vData;
                var uv = sprite.spriteFrame.uv;
                vData[3] = uv[0];
                vData[4] = uv[1];
                vData[12] = uv[2];
                vData[13] = uv[3];
                vData[21] = uv[4];
                vData[22] = uv[5];
                vData[30] = uv[6];
                vData[31] = uv[7];
                renderData.uvDirty = false;
              },
              updateColor: function updateColor(sprite) {
                var vData = sprite.renderData.vData;
                var colorOffset = 5;
                var color = sprite.color;
                var colorR = color.r / 255;
                var colorG = color.g / 255;
                var colorB = color.b / 255;
                var colorA = sprite.node._uiProps.opacity;

                for (var _i = 0; _i < 4; _i++) {
                  vData[colorOffset] = colorR;
                  vData[colorOffset + 1] = colorG;
                  vData[colorOffset + 2] = colorB;
                  vData[colorOffset + 3] = colorA;
                  colorOffset += 9;
                }
              }
            };

            var vec3_temp$1 = new Vec3();
            var matrix$1 = new Mat4();
            var sliced = {
              useModel: false,
              createData: function createData(sprite) {
                var renderData = sprite.requestRenderData();
                renderData.dataLength = 20;
                renderData.vertexCount = 16;
                renderData.indicesCount = 54;
                return renderData;
              },
              updateRenderData: function updateRenderData(sprite) {
                var frame = sprite.spriteFrame;
                dynamicAtlasManager.packToDynamicAtlas(sprite, frame);
                var renderData = sprite.renderData;

                if (renderData && frame) {
                  var vertDirty = renderData.vertDirty;

                  if (vertDirty) {
                    this.updateVertexData(sprite);
                    this.updateWorldVertexData(sprite);
                  }
                }
              },
              updateVertexData: function updateVertexData(sprite) {
                var renderData = sprite.renderData;
                var dataList = renderData.data;
                var uiTrans = sprite.node._uiProps.uiTransformComp;
                var width = uiTrans.width;
                var height = uiTrans.height;
                var appX = uiTrans.anchorX * width;
                var appY = uiTrans.anchorY * height;
                var frame = sprite.spriteFrame;
                var leftWidth = frame.insetLeft;
                var rightWidth = frame.insetRight;
                var topHeight = frame.insetTop;
                var bottomHeight = frame.insetBottom;
                var sizableWidth = width - leftWidth - rightWidth;
                var sizableHeight = height - topHeight - bottomHeight;
                var xScale = width / (leftWidth + rightWidth);
                var yScale = height / (topHeight + bottomHeight);
                xScale = Number.isNaN(xScale) || xScale > 1 ? 1 : xScale;
                yScale = Number.isNaN(yScale) || yScale > 1 ? 1 : yScale;
                sizableWidth = sizableWidth < 0 ? 0 : sizableWidth;
                sizableHeight = sizableHeight < 0 ? 0 : sizableHeight;
                dataList[0].x = -appX;
                dataList[0].y = -appY;
                dataList[1].x = leftWidth * xScale - appX;
                dataList[1].y = bottomHeight * yScale - appY;
                dataList[2].x = dataList[1].x + sizableWidth;
                dataList[2].y = dataList[1].y + sizableHeight;
                dataList[3].x = width - appX;
                dataList[3].y = height - appY;
                renderData.vertDirty = false;
              },
              fillBuffers: function fillBuffers(sprite, renderer) {
                if (sprite.node.hasChangedFlags) {
                  this.updateWorldVertexData(sprite);
                }

                var buffer = renderer.acquireBufferBatch();
                var renderData = sprite.renderData;
                var dataList = renderData.data;
                var vertexOffset = buffer.byteOffset >> 2;
                var vertexCount = renderData.vertexCount;
                var indicesOffset = buffer.indicesOffset;
                var vertexId = buffer.vertexOffset;
                var uvSliced = sprite.spriteFrame.uvSliced;
                var isRecreate = buffer.request(vertexCount, renderData.indicesCount);

                if (!isRecreate) {
                  buffer = renderer.currBufferBatch;
                  vertexOffset = 0;
                  indicesOffset = 0;
                  vertexId = 0;
                }

                var vBuf = buffer.vData;
                var iBuf = buffer.iData;

                for (var i = 4; i < 20; ++i) {
                  var vert = dataList[i];
                  var uvs = uvSliced[i - 4];
                  vBuf[vertexOffset++] = vert.x;
                  vBuf[vertexOffset++] = vert.y;
                  vBuf[vertexOffset++] = vert.z;
                  vBuf[vertexOffset++] = uvs.u;
                  vBuf[vertexOffset++] = uvs.v;
                  Color.toArray(vBuf, dataList[i].color, vertexOffset);
                  vertexOffset += 4;
                }

                for (var r = 0; r < 3; ++r) {
                  for (var c = 0; c < 3; ++c) {
                    var start = vertexId + r * 4 + c;
                    iBuf[indicesOffset++] = start;
                    iBuf[indicesOffset++] = start + 1;
                    iBuf[indicesOffset++] = start + 4;
                    iBuf[indicesOffset++] = start + 1;
                    iBuf[indicesOffset++] = start + 5;
                    iBuf[indicesOffset++] = start + 4;
                  }
                }
              },
              updateWorldVertexData: function updateWorldVertexData(sprite) {
                var node = sprite.node;
                var dataList = sprite.renderData.data;
                node.getWorldMatrix(matrix$1);

                for (var row = 0; row < 4; ++row) {
                  var rowD = dataList[row];

                  for (var col = 0; col < 4; ++col) {
                    var colD = dataList[col];
                    var world = dataList[4 + row * 4 + col];
                    Vec3.set(vec3_temp$1, colD.x, rowD.y, 0);
                    Vec3.transformMat4(world, vec3_temp$1, matrix$1);
                  }
                }
              },
              updateColor: function updateColor(sprite) {
                var datalist = sprite.renderData.data;
                var color = sprite.color;
                var colorR = color.r;
                var colorG = color.g;
                var colorB = color.b;
                var colorA = sprite.node._uiProps.opacity * 255;

                for (var i = 4; i < 20; i++) {
                  datalist[i].color.r = colorR;
                  datalist[i].color.g = colorG;
                  datalist[i].color.b = colorB;
                  datalist[i].color.a = colorA;
                }
              }
            };

            var vec3_temps$2 = [];

            for (var i$3 = 0; i$3 < 4; i$3++) {
              vec3_temps$2.push(new Vec3());
            }

            var _perVertexLength = 9;
            var tiled = {
              createData: function createData(sprite) {
                return sprite.requestRenderData();
              },
              updateRenderData: function updateRenderData(sprite) {
                var renderData = sprite.renderData;
                var frame = sprite.spriteFrame;

                if (!frame || !renderData || !(renderData.uvDirty || renderData.vertDirty)) {
                  return;
                }

                var uiTrans = sprite.node._uiProps.uiTransformComp;
                var contentWidth = Math.abs(uiTrans.width);
                var contentHeight = Math.abs(uiTrans.height);
                var rect = frame.getRect();
                var leftWidth = frame.insetLeft;
                var rightWidth = frame.insetRight;
                var centerWidth = rect.width - leftWidth - rightWidth;
                var topHeight = frame.insetTop;
                var bottomHeight = frame.insetBottom;
                var centerHeight = rect.height - topHeight - bottomHeight;
                var sizableWidth = contentWidth - leftWidth - rightWidth;
                var sizableHeight = contentHeight - topHeight - bottomHeight;
                sizableWidth = sizableWidth > 0 ? sizableWidth : 0;
                sizableHeight = sizableHeight > 0 ? sizableHeight : 0;
                var hRepeat = centerWidth === 0 ? sizableWidth : sizableWidth / centerWidth;
                var vRepeat = centerHeight === 0 ? sizableHeight : sizableHeight / centerHeight;
                var row = Math.ceil(vRepeat + 2);
                var col = Math.ceil(hRepeat + 2);
                renderData.dataLength = Math.max(8, row + 1, col + 1);
                this.updateVerts(sprite, sizableWidth, sizableHeight, row, col);
                renderData.vertexCount = row * col * 4;
                renderData.indicesCount = row * col * 6;
                renderData.uvDirty = false;
                renderData.vertDirty = false;
                this.updateColor(sprite);
              },
              fillBuffers: function fillBuffers(sprite, renderer) {
                var node = sprite.node;
                var uiTrans = sprite.node._uiProps.uiTransformComp;
                var contentWidth = Math.abs(uiTrans.width);
                var contentHeight = Math.abs(uiTrans.height);
                var renderData = sprite.renderData;
                var buffer = renderer.acquireBufferBatch();
                var indicesOffset = buffer.indicesOffset;
                var vertexOffset = buffer.byteOffset >> 2;
                var vertexId = buffer.vertexOffset;
                var vertexCount = renderData.vertexCount;
                var indicesCount = renderData.indicesCount;
                var vBuf = buffer.vData;
                var iBuf = buffer.iData;
                var isRecreate = buffer.request(vertexCount, indicesCount);

                if (!isRecreate) {
                  buffer = renderer.currBufferBatch;
                  vertexOffset = 0;
                  indicesOffset = 0;
                  vertexId = 0;
                }

                var frame = sprite.spriteFrame;
                var rotated = frame.isRotated();
                var uv = frame.uv;
                var uvSliced = sprite.spriteFrame.uvSliced;
                var rect = frame.getRect();
                var leftWidth = frame.insetLeft;
                var rightWidth = frame.insetRight;
                var centerWidth = rect.width - leftWidth - rightWidth;
                var topHeight = frame.insetTop;
                var bottomHeight = frame.insetBottom;
                var centerHeight = rect.height - topHeight - bottomHeight;
                var sizableWidth = contentWidth - leftWidth - rightWidth;
                var sizableHeight = contentHeight - topHeight - bottomHeight;
                sizableWidth = sizableWidth > 0 ? sizableWidth : 0;
                sizableHeight = sizableHeight > 0 ? sizableHeight : 0;
                var hRepeat = centerWidth === 0 ? sizableWidth : sizableWidth / centerWidth;
                var vRepeat = centerHeight === 0 ? sizableHeight : sizableHeight / centerHeight;
                var row = Math.ceil(vRepeat + 2);
                var col = Math.ceil(hRepeat + 2);
                var matrix = node.worldMatrix;
                var datalist = renderData.data;
                this.fillVertices(vBuf, vertexOffset, matrix, row, col, datalist);
                var offset = _perVertexLength;
                var offset1 = offset;
                var offset2 = offset * 2;
                var offset3 = offset * 3;
                var offset4 = offset * 4;
                var coefU = 0;
                var coefV = 0;
                var tempXVerts = [];
                var tempYVerts = [];

                for (var yIndex = 0, yLength = row; yIndex < yLength; ++yIndex) {
                  if (sizableHeight > centerHeight) {
                    if (sizableHeight >= yIndex * centerHeight) {
                      coefV = 1;
                    } else {
                      coefV = vRepeat % 1;
                    }
                  } else {
                    coefV = vRepeat;
                  }

                  for (var xIndex = 0, xLength = col; xIndex < xLength; ++xIndex) {
                    if (sizableWidth > centerWidth) {
                      if (sizableWidth >= xIndex * centerWidth) {
                        coefU = 1;
                      } else {
                        coefU = hRepeat % 1;
                      }
                    } else {
                      coefU = hRepeat;
                    }

                    var vertexOffsetU = vertexOffset + 3;
                    var vertexOffsetV = vertexOffsetU + 1;

                    if (rotated) {
                      if (yIndex === 0) {
                        tempXVerts[0] = uvSliced[0].u;
                        tempXVerts[1] = uvSliced[0].u;
                        tempXVerts[2] = uvSliced[4].u + (uvSliced[8].u - uvSliced[4].u) * coefV;
                      } else if (yIndex < row - 1) {
                        tempXVerts[0] = uvSliced[4].u;
                        tempXVerts[1] = uvSliced[4].u;
                        tempXVerts[2] = uvSliced[4].u + (uvSliced[8].u - uvSliced[4].u) * coefV;
                      } else if (yIndex === row - 1) {
                        tempXVerts[0] = uvSliced[8].u;
                        tempXVerts[1] = uvSliced[8].u;
                        tempXVerts[2] = uvSliced[12].u;
                      }

                      if (xIndex === 0) {
                        tempYVerts[0] = uvSliced[0].v;
                        tempYVerts[1] = uvSliced[1].v + (uvSliced[2].v - uvSliced[1].v) * coefU;
                        tempYVerts[2] = uvSliced[0].v;
                      } else if (xIndex < col - 1) {
                        tempYVerts[0] = uvSliced[1].v;
                        tempYVerts[1] = uvSliced[1].v + (uvSliced[2].v - uvSliced[1].v) * coefU;
                        tempYVerts[2] = uvSliced[1].v;
                      } else if (xIndex === col - 1) {
                        tempYVerts[0] = uvSliced[2].v;
                        tempYVerts[1] = uvSliced[3].v;
                        tempYVerts[2] = uvSliced[2].v;
                      }

                      tempXVerts[3] = tempXVerts[2];
                      tempYVerts[3] = tempYVerts[1];
                    } else {
                      if (xIndex === 0) {
                        tempXVerts[0] = uvSliced[0].u;
                        tempXVerts[1] = uvSliced[1].u + (uvSliced[2].u - uvSliced[1].u) * coefU;
                        tempXVerts[2] = uv[0];
                      } else if (xIndex < col - 1) {
                        tempXVerts[0] = uvSliced[1].u;
                        tempXVerts[1] = uvSliced[1].u + (uvSliced[2].u - uvSliced[1].u) * coefU;
                        tempXVerts[2] = uvSliced[1].u;
                      } else if (xIndex === col - 1) {
                        tempXVerts[0] = uvSliced[2].u;
                        tempXVerts[1] = uvSliced[3].u;
                        tempXVerts[2] = uvSliced[2].u;
                      }

                      if (yIndex === 0) {
                        tempYVerts[0] = uvSliced[0].v;
                        tempYVerts[1] = uvSliced[0].v;
                        tempYVerts[2] = uvSliced[4].v + (uvSliced[8].v - uvSliced[4].v) * coefV;
                      } else if (yIndex < row - 1) {
                        tempYVerts[0] = uvSliced[4].v;
                        tempYVerts[1] = uvSliced[4].v;
                        tempYVerts[2] = uvSliced[4].v + (uvSliced[8].v - uvSliced[4].v) * coefV;
                      } else if (yIndex === row - 1) {
                        tempYVerts[0] = uvSliced[8].v;
                        tempYVerts[1] = uvSliced[8].v;
                        tempYVerts[2] = uvSliced[12].v;
                      }

                      tempXVerts[3] = tempXVerts[1];
                      tempYVerts[3] = tempYVerts[2];
                    }

                    vBuf[vertexOffsetU] = tempXVerts[0];
                    vBuf[vertexOffsetV] = tempYVerts[0];
                    vBuf[vertexOffsetU + offset1] = tempXVerts[1];
                    vBuf[vertexOffsetV + offset1] = tempYVerts[1];
                    vBuf[vertexOffsetU + offset2] = tempXVerts[2];
                    vBuf[vertexOffsetV + offset2] = tempYVerts[2];
                    vBuf[vertexOffsetU + offset3] = tempXVerts[3];
                    vBuf[vertexOffsetV + offset3] = tempYVerts[3];
                    Color.toArray(vBuf, datalist[0].color, vertexOffsetV + 1);
                    Color.toArray(vBuf, datalist[0].color, vertexOffsetV + offset1 + 1);
                    Color.toArray(vBuf, datalist[0].color, vertexOffsetV + offset2 + 1);
                    Color.toArray(vBuf, datalist[0].color, vertexOffsetV + offset3 + 1);
                    vertexOffset += offset4;
                  }
                }

                for (var _i = 0; _i < indicesCount; _i += 6) {
                  iBuf[indicesOffset++] = vertexId;
                  iBuf[indicesOffset++] = vertexId + 1;
                  iBuf[indicesOffset++] = vertexId + 2;
                  iBuf[indicesOffset++] = vertexId + 1;
                  iBuf[indicesOffset++] = vertexId + 3;
                  iBuf[indicesOffset++] = vertexId + 2;
                  vertexId += 4;
                }
              },
              fillVertices: function fillVertices(vBuf, vertexOffset, matrix, row, col, dataList) {
                var x = 0;
                var x1 = 0;
                var y = 0;
                var y1 = 0;

                for (var yIndex = 0, yLength = row; yIndex < yLength; ++yIndex) {
                  y = dataList[yIndex].y;
                  y1 = dataList[yIndex + 1].y;

                  for (var xIndex = 0, xLength = col; xIndex < xLength; ++xIndex) {
                    x = dataList[xIndex].x;
                    x1 = dataList[xIndex + 1].x;
                    Vec3.set(vec3_temps$2[0], x, y, 0);
                    Vec3.set(vec3_temps$2[1], x1, y, 0);
                    Vec3.set(vec3_temps$2[2], x, y1, 0);
                    Vec3.set(vec3_temps$2[3], x1, y1, 0);

                    for (var _i2 = 0; _i2 < 4; _i2++) {
                      var vec3_temp = vec3_temps$2[_i2];
                      Vec3.transformMat4(vec3_temp, vec3_temp, matrix);
                      var offset = _i2 * _perVertexLength;
                      vBuf[vertexOffset + offset] = vec3_temp.x;
                      vBuf[vertexOffset + offset + 1] = vec3_temp.y;
                      vBuf[vertexOffset + offset + 2] = vec3_temp.z;
                    }

                    vertexOffset += 36;
                  }
                }
              },
              updateVerts: function updateVerts(sprite, sizableWidth, sizableHeight, row, col) {
                var uiTrans = sprite.node._uiProps.uiTransformComp;
                var renderData = sprite.renderData;
                var data = renderData.data;
                var frame = sprite.spriteFrame;
                var rect = frame.getRect();
                var contentWidth = Math.abs(uiTrans.width);
                var contentHeight = Math.abs(uiTrans.height);
                var appx = uiTrans.anchorX * contentWidth;
                var appy = uiTrans.anchorY * contentHeight;
                var leftWidth = frame.insetLeft;
                var rightWidth = frame.insetRight;
                var centerWidth = rect.width - leftWidth - rightWidth;
                var topHeight = frame.insetTop;
                var bottomHeight = frame.insetBottom;
                var centerHeight = rect.height - topHeight - bottomHeight;
                var xScale = uiTrans.width / (leftWidth + rightWidth) > 1 ? 1 : uiTrans.width / (leftWidth + rightWidth);
                var yScale = uiTrans.height / (topHeight + bottomHeight) > 1 ? 1 : uiTrans.height / (topHeight + bottomHeight);
                var offsetWidth = 0;
                var offsetHeight = 0;

                if (centerWidth > 0) {
                  offsetWidth = Math.floor(sizableWidth * 1000) / 1000 % centerWidth === 0 ? centerWidth : sizableWidth % centerWidth;
                } else {
                  offsetWidth = sizableWidth;
                }

                if (centerHeight > 0) {
                  offsetHeight = Math.floor(sizableHeight * 1000) / 1000 % centerHeight === 0 ? centerHeight : sizableHeight % centerHeight;
                } else {
                  offsetHeight = sizableHeight;
                }

                for (var _i3 = 0; _i3 <= col; _i3++) {
                  if (_i3 === 0) {
                    data[_i3].x = -appx;
                  } else if (_i3 > 0 && _i3 < col) {
                    if (_i3 === 1) {
                      data[_i3].x = leftWidth * xScale + Math.min(centerWidth, sizableWidth) - appx;
                    } else if (centerWidth > 0) {
                      if (_i3 === col - 1) {
                        data[_i3].x = leftWidth + offsetWidth + centerWidth * (_i3 - 2) - appx;
                      } else {
                        data[_i3].x = leftWidth + Math.min(centerWidth, sizableWidth) + centerWidth * (_i3 - 2) - appx;
                      }
                    } else {
                      data[_i3].x = leftWidth + sizableWidth - appx;
                    }
                  } else if (_i3 === col) {
                    data[_i3].x = Math.min(leftWidth + sizableWidth + rightWidth, contentWidth) - appx;
                  }
                }

                for (var _i4 = 0; _i4 <= row; _i4++) {
                  if (_i4 === 0) {
                    data[_i4].y = -appy;
                  } else if (_i4 > 0 && _i4 < row) {
                    if (_i4 === 1) {
                      data[_i4].y = bottomHeight * yScale + Math.min(centerHeight, sizableHeight) - appy;
                    } else if (centerHeight > 0) {
                      if (_i4 === row - 1) {
                        data[_i4].y = bottomHeight + offsetHeight + (_i4 - 2) * centerHeight - appy;
                      } else {
                        data[_i4].y = bottomHeight + Math.min(centerHeight, sizableHeight) + (_i4 - 2) * centerHeight - appy;
                      }
                    } else {
                      data[_i4].y = bottomHeight + sizableHeight - appy;
                    }
                  } else if (_i4 === row) {
                    data[_i4].y = Math.min(bottomHeight + sizableHeight + topHeight, contentHeight) - appy;
                  }
                }
              },
              updateColor: function updateColor(sprite) {
                var datalist = sprite.renderData.data;
                var length = datalist.length;
                if (length === 0) return;
                var color = sprite.color;
                var colorR = color.r;
                var colorG = color.g;
                var colorB = color.b;
                var colorA = sprite.node._uiProps.opacity * 255;

                for (var _i5 = 0; _i5 < length; _i5++) {
                  datalist[_i5].color.r = colorR;
                  datalist[_i5].color.g = colorG;
                  datalist[_i5].color.b = colorB;
                  datalist[_i5].color.a = colorA;
                }
              }
            };

            var SpriteType$1 = Sprite.Type;
            var FillType$2 = Sprite.FillType;
            var spriteAssembler = exports('spriteAssembler', {
              getAssembler: function getAssembler(spriteComp) {
                var util = simple;
                var comp = spriteComp;

                switch (comp.type) {
                  case SpriteType$1.SLICED:
                    util = sliced;
                    break;

                  case SpriteType$1.TILED:
                    util = tiled;
                    break;

                  case SpriteType$1.FILLED:
                    if (comp.fillType === FillType$2.RADIAL) {
                      util = radialFilled;
                    } else {
                      util = barFilled;
                    }

                    break;
                }

                return util;
              }
            });
            Sprite.Assembler = spriteAssembler;

            var _stencilManager = StencilManager.sharedManager;

            function applyClearMask(mask, renderer) {
              _stencilManager.clear(mask);

              renderer.commitModel(mask, mask._clearModel, mask._clearStencilMtl);
            }

            function applyAreaMask(mask, renderer) {
              _stencilManager.enterLevel(mask);

              if (mask.type === MaskType.IMAGE_STENCIL) {
                simple.fillBuffers(mask, renderer);
                var mat = mask.graphics.getMaterialInstance(0);
                renderer.forceMergeBatches(mat, mask.spriteFrame, mask.graphics);
              } else {
                mask.graphics.updateAssembler(renderer);
              }
            }

            var maskAssembler = {
              createData: function createData(mask) {
                var renderData = mask.requestRenderData();
                renderData.dataLength = 4;
                renderData.vertexCount = 4;
                renderData.indicesCount = 6;
                renderData.vData = new Float32Array(4 * 9);
                return renderData;
              },
              updateRenderData: function updateRenderData(mask) {
                if (mask.type === MaskType.IMAGE_STENCIL) {
                  simple.updateRenderData(mask);
                  simple.updateColor(mask);
                }
              },
              fillBuffers: function fillBuffers(mask, renderer) {
                if (mask.type !== MaskType.IMAGE_STENCIL || mask.spriteFrame) {
                  _stencilManager.pushMask(mask);

                  renderer.finishMergeBatches();
                  applyClearMask(mask, renderer);
                  applyAreaMask(mask, renderer);

                  _stencilManager.enableMask();
                }
              }
            };
            var maskEndAssembler = {
              fillBuffers: function fillBuffers(mask, ui) {
                _stencilManager.exitMask();
              }
            };
            var StartAssembler = {
              getAssembler: function getAssembler() {
                return maskAssembler;
              }
            };
            var PostAssembler = {
              getAssembler: function getAssembler() {
                return maskEndAssembler;
              }
            };
            Mask.Assembler = StartAssembler;
            Mask.PostAssembler = PostAssembler;

            var _dsInfo$2 = new DescriptorSetInfo(null);

            var m4_1$3 = new Mat4();
            var Batcher2D = exports('UI', function () {
              var _proto = Batcher2D.prototype;

              _proto.acquireBufferBatch = function acquireBufferBatch(attributes) {
                if (attributes === void 0) {
                  attributes = vfmtPosUvColor;
                }

                var strideBytes = attributes === vfmtPosUvColor ? 36 : getAttributeStride(attributes);

                if (!this._currMeshBuffer || this._currMeshBuffer.vertexFormatBytes !== strideBytes) {
                  this._requireBufferBatch(attributes);

                  return this._currMeshBuffer;
                }

                return this._currMeshBuffer;
              };

              _proto.registerCustomBuffer = function registerCustomBuffer(attributes, callback) {
                var batch;

                if (attributes instanceof MeshBuffer) {
                  batch = attributes;
                } else {
                  batch = this._bufferBatchPool.add();
                  batch.initialize(attributes, callback || this._recreateMeshBuffer.bind(this, attributes));
                }

                var strideBytes = batch.vertexFormatBytes;

                var buffers = this._customMeshBuffers.get(strideBytes);

                if (!buffers) {
                  buffers = [];

                  this._customMeshBuffers.set(strideBytes, buffers);
                }

                buffers.push(batch);
                return batch;
              };

              _proto.unRegisterCustomBuffer = function unRegisterCustomBuffer(buffer) {
                var buffers = this._customMeshBuffers.get(buffer.vertexFormatBytes);

                if (buffers) {
                  for (var i = 0; i < buffers.length; i++) {
                    if (buffers[i] === buffer) {
                      buffers.splice(i, 1);
                      break;
                    }
                  }
                }
              };

              function Batcher2D(_root) {
                var _this = this;

                this.device = void 0;
                this._screens = [];
                this._bufferBatchPool = new RecyclePool(function () {
                  return new MeshBuffer(_this);
                }, 128);
                this._drawBatchPool = void 0;
                this._meshBuffers = new Map();
                this._customMeshBuffers = new Map();
                this._meshBufferUseCount = new Map();
                this._batches = void 0;
                this._doUploadBuffersCall = new Map();
                this._emptyMaterial = new Material();
                this._currScene = null;
                this._currMaterial = this._emptyMaterial;
                this._currTexture = null;
                this._currSampler = null;
                this._currMeshBuffer = null;
                this._currStaticRoot = null;
                this._currComponent = null;
                this._currTransform = null;
                this._currTextureHash = 0;
                this._currSamplerHash = 0;
                this._currBlendTargetHash = 0;
                this._currLayer = 0;
                this._currDepthStencilStateStage = null;
                this._currIsStatic = false;
                this._descriptorSetCache = new DescriptorSetCache();
                this._root = _root;
                this.device = _root.device;
                this._batches = new CachedArray(64);
                this._drawBatchPool = new Pool$1(function () {
                  return new DrawBatch2D();
                }, 128);
              }

              _proto.initialize = function initialize() {
                return true;
              };

              _proto.destroy = function destroy() {
                var _this2 = this;

                for (var i = 0; i < this._batches.length; i++) {
                  if (this._batches.array[i]) {
                    this._batches.array[i].destroy(this);
                  }
                }

                this._batches.destroy();

                for (var _iterator = _createForOfIteratorHelperLoose(this._meshBuffers.keys()), _step; !(_step = _iterator()).done;) {
                  var size = _step.value;

                  var buffers = this._meshBuffers.get(size);

                  if (buffers) {
                    buffers.forEach(function (buffer) {
                      return buffer.destroy();
                    });
                  }
                }

                if (this._drawBatchPool) {
                  this._drawBatchPool.destroy(function (obj) {
                    obj.destroy(_this2);
                  });
                }

                this._descriptorSetCache.destroy();

                this._meshBuffers.clear();

                StencilManager.sharedManager.destroy();
              };

              _proto.addScreen = function addScreen(comp) {
                this._screens.push(comp);

                this._screens.sort(this._screenSort);
              };

              _proto.getFirstRenderCamera = function getFirstRenderCamera(node) {
                if (node.scene && node.scene.renderScene) {
                  var cameras = node.scene.renderScene.cameras;

                  for (var i = 0; i < cameras.length; i++) {
                    var camera = cameras[i];

                    if (camera.visibility & node.layer) {
                      return camera;
                    }
                  }
                }

                return null;
              };

              _proto.removeScreen = function removeScreen(comp) {
                var idx = this._screens.indexOf(comp);

                if (idx === -1) {
                  return;
                }

                this._screens.splice(idx, 1);
              };

              _proto.sortScreens = function sortScreens() {
                this._screens.sort(this._screenSort);
              };

              _proto.addUploadBuffersFunc = function addUploadBuffersFunc(target, func) {
                this._doUploadBuffersCall.set(target, func);
              };

              _proto.removeUploadBuffersFunc = function removeUploadBuffersFunc(target) {
                this._doUploadBuffersCall["delete"](target);
              };

              _proto.update = function update() {
                var screens = this._screens;

                for (var i = 0; i < screens.length; ++i) {
                  var screen = screens[i];

                  if (!screen.enabledInHierarchy) {
                    continue;
                  }

                  this._recursiveScreenNode(screen.node);
                }

                var batchPriority = 0;

                if (this._batches.length) {
                  for (var _i = 0; _i < this._batches.length; ++_i) {
                    var batch = this._batches.array[_i];
                    if (!batch.renderScene) continue;

                    if (batch.model) {
                      var subModels = batch.model.subModels;

                      for (var j = 0; j < subModels.length; j++) {
                        subModels[j].priority = batchPriority++;
                      }
                    } else {
                      batch.hDescriptorSet = this._descriptorSetCache.getDescriptorSet(batch);
                    }

                    batch.renderScene.addBatch(batch);
                  }
                }
              };

              _proto.uploadBuffers = function uploadBuffers() {
                var _this3 = this;

                if (this._batches.length > 0) {
                  var calls = this._doUploadBuffersCall;
                  calls.forEach(function (value, key) {
                    value.call(key, _this3);
                  });
                  var buffers = this._meshBuffers;
                  buffers.forEach(function (value, key) {
                    value.forEach(function (bb) {
                      bb.uploadBuffers();
                      bb.reset();
                    });
                  });
                  var customs = this._customMeshBuffers;
                  customs.forEach(function (value, key) {
                    value.forEach(function (bb) {
                      bb.uploadBuffers();
                      bb.reset();
                    });
                  });

                  this._descriptorSetCache.update();
                }
              };

              _proto.reset = function reset() {
                for (var i = 0; i < this._batches.length; ++i) {
                  var batch = this._batches.array[i];

                  if (batch.isStatic) {
                    continue;
                  }

                  batch.clear();

                  this._drawBatchPool.free(batch);
                }

                this._currLayer = 0;
                this._currMaterial = this._emptyMaterial;
                this._currTexture = null;
                this._currSampler = null;
                this._currComponent = null;
                this._currTransform = null;
                this._currScene = null;
                this._currMeshBuffer = null;

                this._meshBufferUseCount.clear();

                this._batches.clear();

                StencilManager.sharedManager.reset();

                this._descriptorSetCache.reset();
              };

              _proto.commitComp = function commitComp(comp, frame, assembler, transform) {
                var renderComp = comp;
                var texture;
                var samp;
                var textureHash = 0;
                var samplerHash = 0;

                if (frame) {
                  texture = frame.getGFXTexture();
                  samp = frame.getGFXSampler();
                  textureHash = frame.getHash();
                  samplerHash = frame.getSamplerHash();
                } else {
                  texture = null;
                  samp = null;
                }

                var renderScene = renderComp._getRenderScene();

                var mat = renderComp.getRenderMaterial(0);
                renderComp.stencilStage = StencilManager.sharedManager.stage;
                var blendTargetHash = renderComp.blendHash;
                var depthStencilStateStage = renderComp.stencilStage;

                if (this._currScene !== renderScene || this._currLayer !== comp.node.layer || this._currMaterial !== mat || this._currBlendTargetHash !== blendTargetHash || this._currDepthStencilStateStage !== depthStencilStateStage || this._currTextureHash !== textureHash || this._currSamplerHash !== samplerHash || this._currTransform !== transform) {
                  this.autoMergeBatches(this._currComponent);
                  this._currScene = renderScene;
                  this._currComponent = renderComp;
                  this._currTransform = transform;
                  this._currMaterial = mat;
                  this._currTexture = texture;
                  this._currSampler = samp;
                  this._currTextureHash = textureHash;
                  this._currSamplerHash = samplerHash;
                  this._currBlendTargetHash = blendTargetHash;
                  this._currDepthStencilStateStage = depthStencilStateStage;
                  this._currLayer = comp.node.layer;
                }

                if (assembler) {
                  assembler.fillBuffers(renderComp, this);
                }
              };

              _proto.commitModel = function commitModel(comp, model, mat) {
                if (this._currMaterial !== this._emptyMaterial) {
                  this.autoMergeBatches(this._currComponent);
                }

                var depthStencil;
                var dssHash = 0;

                if (mat) {
                  if (comp.stencilStage === Stage.ENABLED || comp.stencilStage === Stage.DISABLED) {
                    comp.stencilStage = StencilManager.sharedManager.stage;
                  }

                  depthStencil = StencilManager.sharedManager.getStencilStage(comp.stencilStage, mat);
                  dssHash = StencilManager.sharedManager.getStencilHash(comp.stencilStage);
                }

                var stamp = legacyCC.director.getTotalFrames();

                if (model) {
                  model.updateTransform(stamp);
                  model.updateUBOs(stamp);
                }

                for (var i = 0; i < model.subModels.length; i++) {
                  var curDrawBatch = this._drawBatchPool.alloc();

                  var subModel = model.subModels[i];
                  curDrawBatch.renderScene = comp._getRenderScene();
                  curDrawBatch.visFlags = comp.node.layer;
                  curDrawBatch.model = model;
                  curDrawBatch.bufferBatch = null;
                  curDrawBatch.texture = null;
                  curDrawBatch.sampler = null;
                  curDrawBatch.useLocalData = null;

                  if (!depthStencil) {
                    depthStencil = null;
                  }

                  curDrawBatch.fillPasses(mat, depthStencil, dssHash, null, 0, subModel.patches);
                  curDrawBatch.hDescriptorSet = SubModelPool.get(subModel.handle, SubModelView.DESCRIPTOR_SET);
                  curDrawBatch.hInputAssembler = SubModelPool.get(subModel.handle, SubModelView.INPUT_ASSEMBLER);
                  curDrawBatch.model.visFlags = curDrawBatch.visFlags;

                  this._batches.push(curDrawBatch);
                }

                this._currMaterial = this._emptyMaterial;
                this._currScene = null;
                this._currComponent = null;
                this._currTransform = null;
                this._currTexture = null;
                this._currSampler = null;
                this._currTextureHash = 0;
                this._currSamplerHash = 0;
                this._currLayer = 0;
              };

              _proto.commitStaticBatch = function commitStaticBatch(comp) {
                this._batches.concat(comp.drawBatchList);

                this.finishMergeBatches();
              };

              _proto.autoMergeBatches = function autoMergeBatches(renderComp) {
                var buffer = this.currBufferBatch;
                var hIA = buffer === null || buffer === void 0 ? void 0 : buffer.recordBatch();
                var mat = this._currMaterial;

                if (!hIA || !mat || !buffer) {
                  return;
                }

                var blendState;
                var depthStencil;
                var dssHash = 0;
                var bsHash = 0;

                if (renderComp) {
                  blendState = renderComp.blendHash === -1 ? null : renderComp.getBlendState();
                  bsHash = renderComp.blendHash;

                  if (renderComp.customMaterial !== null) {
                    depthStencil = StencilManager.sharedManager.getStencilStage(renderComp.stencilStage, mat);
                  } else {
                    depthStencil = StencilManager.sharedManager.getStencilStage(renderComp.stencilStage);
                  }

                  dssHash = StencilManager.sharedManager.getStencilHash(renderComp.stencilStage);
                }

                var curDrawBatch = this._currStaticRoot ? this._currStaticRoot._requireDrawBatch() : this._drawBatchPool.alloc();
                curDrawBatch.renderScene = this._currScene;
                curDrawBatch.visFlags = this._currLayer;
                curDrawBatch.bufferBatch = buffer;
                curDrawBatch.texture = this._currTexture;
                curDrawBatch.sampler = this._currSampler;
                curDrawBatch.hInputAssembler = hIA;
                curDrawBatch.useLocalData = this._currTransform;
                curDrawBatch.textureHash = this._currTextureHash;
                curDrawBatch.samplerHash = this._currSamplerHash;
                curDrawBatch.fillPasses(mat, depthStencil, dssHash, blendState, bsHash, null);

                this._batches.push(curDrawBatch);

                buffer.vertexStart = buffer.vertexOffset;
                buffer.indicesStart = buffer.indicesOffset;
                buffer.byteStart = buffer.byteOffset;

                if (sys.__isWebIOS14OrIPadOS14Env && !this._currIsStatic) {
                  this._currMeshBuffer = null;
                }
              };

              _proto.forceMergeBatches = function forceMergeBatches(material, frame, renderComp) {
                this._currMaterial = material;

                if (frame) {
                  this._currTexture = frame.getGFXTexture();
                  this._currSampler = frame.getGFXSampler();
                  this._currTextureHash = frame.getHash();
                  this._currSamplerHash = frame.getSamplerHash();
                } else {
                  this._currTexture = this._currSampler = null;
                  this._currTextureHash = this._currSamplerHash = 0;
                }

                this._currLayer = renderComp.node.layer;
                this._currScene = renderComp._getRenderScene();
                this.autoMergeBatches(renderComp);
              };

              _proto.finishMergeBatches = function finishMergeBatches() {
                this.autoMergeBatches();
                this._currMaterial = this._emptyMaterial;
                this._currTexture = null;
                this._currComponent = null;
                this._currTransform = null;
                this._currTextureHash = 0;
                this._currSamplerHash = 0;
                this._currLayer = 0;
              };

              _proto.flushMaterial = function flushMaterial(mat) {
                this._currMaterial = mat;
              };

              _proto.walk = function walk(node, level) {
                if (level === void 0) {
                  level = 0;
                }

                var len = node.children.length;

                this._preProcess(node);

                if (len > 0 && !node._static) {
                  var children = node.children;

                  for (var i = 0; i < children.length; ++i) {
                    var child = children[i];
                    this.walk(child, level);
                  }
                }

                this._postProcess(node);

                level += 1;
              };

              _proto._preProcess = function _preProcess(node) {
                var render = node._uiProps.uiComp;

                if (!render) {
                  var localAlpha = node._uiProps.localOpacity;
                  node._uiProps.opacity = node.parent && node.parent._uiProps ? node.parent._uiProps.opacity * localAlpha : localAlpha;
                }

                if (!node._uiProps.uiTransformComp) {
                  return;
                }

                if (render && render.enabledInHierarchy) {
                  render.updateAssembler(this);
                }
              };

              _proto._postProcess = function _postProcess(node) {
                var render = node._uiProps.uiComp;

                if (render && render.enabledInHierarchy) {
                  render.postUpdateAssembler(this);
                }
              };

              _proto._recursiveScreenNode = function _recursiveScreenNode(screen) {
                this.walk(screen);
                this.autoMergeBatches(this._currComponent);
              };

              _proto._createMeshBuffer = function _createMeshBuffer(attributes) {
                var batch = this._bufferBatchPool.add();

                batch.initialize(attributes, this._recreateMeshBuffer.bind(this, attributes));
                var strideBytes = getAttributeStride(attributes);

                var buffers = this._meshBuffers.get(strideBytes);

                if (!buffers) {
                  buffers = [];

                  this._meshBuffers.set(strideBytes, buffers);
                }

                buffers.push(batch);
                return batch;
              };

              _proto._recreateMeshBuffer = function _recreateMeshBuffer(attributes, vertexCount, indexCount) {
                this.autoMergeBatches();

                this._requireBufferBatch(attributes, vertexCount, indexCount);
              };

              _proto._requireBufferBatch = function _requireBufferBatch(attributes, vertexCount, indexCount) {
                var strideBytes = getAttributeStride(attributes);

                var buffers = this._meshBuffers.get(strideBytes);

                if (!buffers) {
                  buffers = [];

                  this._meshBuffers.set(strideBytes, buffers);
                }

                var meshBufferUseCount = this._meshBufferUseCount.get(strideBytes) || 0;

                if (meshBufferUseCount >= buffers.length) {
                  this._currMeshBuffer = this._createMeshBuffer(attributes);
                } else {
                  this._currMeshBuffer = buffers[meshBufferUseCount];
                }

                this._meshBufferUseCount.set(strideBytes, meshBufferUseCount + 1);

                if (vertexCount && indexCount) {
                  this._currMeshBuffer.request(vertexCount, indexCount);
                }
              };

              _proto._screenSort = function _screenSort(a, b) {
                return a.node.getSiblingIndex() - b.node.getSiblingIndex();
              };

              _proto._releaseDescriptorSetCache = function _releaseDescriptorSetCache(textureHash) {
                this._descriptorSetCache.releaseDescriptorSetCache(textureHash);
              };

              _createClass(Batcher2D, [{
                key: "currBufferBatch",
                get: function get() {
                  if (this._currMeshBuffer) return this._currMeshBuffer;
                  this._currMeshBuffer = this.acquireBufferBatch();
                  return this._currMeshBuffer;
                },
                set: function set(buffer) {
                  if (buffer) {
                    this._currMeshBuffer = buffer;
                  }
                }
              }, {
                key: "batches",
                get: function get() {
                  return this._batches;
                }
              }, {
                key: "currStaticRoot",
                set: function set(value) {
                  this._currStaticRoot = value;
                }
              }, {
                key: "currIsStatic",
                set: function set(value) {
                  this._currIsStatic = value;
                }
              }]);

              return Batcher2D;
            }());

            var LocalDescriptorSet = function () {
              function LocalDescriptorSet() {
                this._handle = null;
                this._transform = null;
                this._textureHash = 0;
                this._samplerHash = 0;
                this._localBuffer = null;
                this._transformUpdate = true;
                var device = legacyCC.director.root.device;
                this._localData = new Float32Array(UBOLocal.COUNT);
                this._localBuffer = device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, UBOLocal.SIZE, UBOLocal.SIZE));
              }

              var _proto2 = LocalDescriptorSet.prototype;

              _proto2.initialize = function initialize(batch) {
                var device = legacyCC.director.root.device;
                this._transform = batch.useLocalData;
                this._textureHash = batch.textureHash;
                this._samplerHash = batch.samplerHash;
                _dsInfo$2.layout = batch.passes[0].localSetLayout;

                if (this._handle) {
                  DSPool.free(this._handle);
                  this._handle = null;
                }

                this._handle = DSPool.alloc(device, _dsInfo$2);
                this._descriptorSet = DSPool.get(this._handle);

                this._descriptorSet.bindBuffer(UBOLocal.BINDING, this._localBuffer);

                var binding = ModelLocalBindings.SAMPLER_SPRITE;

                this._descriptorSet.bindTexture(binding, batch.texture);

                this._descriptorSet.bindSampler(binding, batch.sampler);

                this._descriptorSet.update();

                this._transformUpdate = true;
              };

              _proto2.updateTransform = function updateTransform(transform) {
                if (transform === this._transform) return;
                this._transform = transform;
                this._transformUpdate = true;
                this.uploadLocalData();
              };

              _proto2.updateLocal = function updateLocal() {
                if (!this._transform) return;
                this.uploadLocalData();
              };

              _proto2.equals = function equals(transform, textureHash, samplerHash) {
                return this._transform === transform && this._textureHash === textureHash && this._samplerHash === samplerHash;
              };

              _proto2.reset = function reset() {
                this._transform = null;
                this._textureHash = 0;
                this._samplerHash = 0;
              };

              _proto2.destroy = function destroy() {
                if (this._localBuffer) {
                  this._localBuffer.destroy();

                  this._localBuffer = null;
                }

                if (this._handle) {
                  DSPool.free(this._handle);
                  this._handle = null;
                }

                this._localData = null;
              };

              _proto2.uploadLocalData = function uploadLocalData() {
                var node = this._transform;

                if (node.hasChangedFlags || node._dirtyFlags) {
                  node.updateWorldTransform();
                }

                if (this._transformUpdate) {
                  var worldMatrix = node._mat;
                  Mat4.toArray(this._localData, worldMatrix, UBOLocal.MAT_WORLD_OFFSET);
                  Mat4.inverseTranspose(m4_1$3, worldMatrix);
                  Mat4.toArray(this._localData, m4_1$3, UBOLocal.MAT_WORLD_IT_OFFSET);

                  this._localBuffer.update(this._localData);

                  this._transformUpdate = false;
                }
              };

              _createClass(LocalDescriptorSet, [{
                key: "handle",
                get: function get() {
                  return this._handle;
                }
              }]);

              return LocalDescriptorSet;
            }();

            var DescriptorSetCache = function () {
              function DescriptorSetCache() {
                this._descriptorSetCache = new Map();
                this._localDescriptorSetCache = [];
                this._localCachePool = void 0;
                this._localCachePool = new Pool$1(function () {
                  return new LocalDescriptorSet();
                }, 16);
              }

              var _proto3 = DescriptorSetCache.prototype;

              _proto3.getDescriptorSet = function getDescriptorSet(batch) {
                var root = legacyCC.director.root;

                if (batch.useLocalData) {
                  var caches = this._localDescriptorSetCache;

                  for (var i = 0, len = caches.length; i < len; i++) {
                    var cache = caches[i];

                    if (cache.equals(batch.useLocalData, batch.textureHash, batch.samplerHash)) {
                      return cache.handle;
                    }
                  }

                  var localDs = this._localCachePool.alloc();

                  localDs.initialize(batch);

                  this._localDescriptorSetCache.push(localDs);

                  return localDs.handle;
                } else {
                  var descriptorSetTextureMap = this._descriptorSetCache.get(batch.textureHash);

                  if (descriptorSetTextureMap && descriptorSetTextureMap.has(batch.samplerHash)) {
                    return descriptorSetTextureMap.get(batch.samplerHash);
                  } else {
                    _dsInfo$2.layout = batch.passes[0].localSetLayout;
                    var handle = DSPool.alloc(root.device, _dsInfo$2);
                    var descriptorSet = DSPool.get(handle);
                    var binding = ModelLocalBindings.SAMPLER_SPRITE;
                    descriptorSet.bindTexture(binding, batch.texture);
                    descriptorSet.bindSampler(binding, batch.sampler);
                    descriptorSet.update();

                    if (descriptorSetTextureMap) {
                      this._descriptorSetCache.get(batch.textureHash).set(batch.samplerHash, handle);
                    } else {
                      this._descriptorSetCache.set(batch.textureHash, new Map([[batch.samplerHash, handle]]));
                    }

                    return handle;
                  }
                }
              };

              _proto3.update = function update() {
                var caches = this._localDescriptorSetCache;
                caches.forEach(function (value) {
                  value.updateLocal();
                });
              };

              _proto3.reset = function reset() {
                var _this4 = this;

                var caches = this._localDescriptorSetCache;
                caches.forEach(function (value) {
                  _this4._localCachePool.free(value);
                });
                this._localDescriptorSetCache.length = 0;
              };

              _proto3.releaseDescriptorSetCache = function releaseDescriptorSetCache(textureHash) {
                if (this._descriptorSetCache.has(textureHash)) {
                  this._descriptorSetCache.get(textureHash).forEach(function (value) {
                    DSPool.free(value);
                  });

                  this._descriptorSetCache["delete"](textureHash);
                }
              };

              _proto3.destroy = function destroy() {
                this._descriptorSetCache.forEach(function (value, key, map) {
                  value.forEach(function (hDescriptorSet) {
                    DSPool.free(hDescriptorSet);
                  });
                });

                this._descriptorSetCache.clear();

                this._localDescriptorSetCache.length = 0;

                this._localCachePool.destroy(function (obj) {
                  obj.destroy();
                });
              };

              return DescriptorSetCache;
            }();

            legacyCC.internal.Batcher2D = Batcher2D;

            var _canvasContext = null;

            var _intervalId = -1;

            var _testString = "BES bswy:->@123\u4E01\u3041\u1101";

            var _fontFaces = Object.create(null);

            var _loadingFonts = [];
            var _timeout = 3000;

            var useNativeCheck = function () {
              var nativeCheck;
              return function () {
                if (nativeCheck === undefined) {
                  if ('FontFace' in window) {
                    var match = /Gecko.*Firefox\/(\d+)/.exec(window.navigator.userAgent);
                    var safari10Match = /OS X.*Version\/10\..*Safari/.exec(window.navigator.userAgent) && /Apple/.exec(window.navigator.vendor);

                    if (match) {
                      nativeCheck = parseInt(match[1], 10) > 42;
                    } else if (safari10Match) {
                      nativeCheck = false;
                    } else {
                      nativeCheck = true;
                    }
                  } else {
                    nativeCheck = false;
                  }
                }

                return nativeCheck;
              };
            }();

            function checkFontLoaded() {
              var allFontsLoaded = true;
              var now = Date.now();

              for (var i = _loadingFonts.length - 1; i >= 0; i--) {
                var fontLoadHandle = _loadingFonts[i];
                var fontFamily = fontLoadHandle.fontFamilyName;

                if (now - fontLoadHandle.startTime > _timeout) {
                  warnID(4933, fontFamily);
                  fontLoadHandle.onComplete(null, fontFamily);

                  _loadingFonts.splice(i, 1);

                  continue;
                }

                var oldWidth = fontLoadHandle.refWidth;
                var fontDesc = "40px " + fontFamily;
                _canvasContext.font = fontDesc;
                var newWidth = safeMeasureText(_canvasContext, _testString, fontDesc);

                if (oldWidth !== newWidth) {
                  _loadingFonts.splice(i, 1);

                  fontLoadHandle.onComplete(null, fontFamily);
                } else {
                  allFontsLoaded = false;
                }
              }

              if (allFontsLoaded) {
                clearInterval(_intervalId);
                _intervalId = -1;
              }
            }

            function nativeCheckFontLoaded(start, font, callback) {
              var loader = new Promise(function (resolve, reject) {
                var check = function check() {
                  var now = Date.now();

                  if (now - start >= _timeout) {
                    reject();
                  } else {
                    document.fonts.load("40px " + font).then(function (fonts) {
                      if (fonts.length >= 1) {
                        resolve();
                      } else {
                        setTimeout(check, 100);
                      }
                    }, function () {
                      reject();
                    });
                  }
                };

                check();
              });
              var timeoutId = null;
              var timer = new Promise(function (resolve, reject) {
                timeoutId = setTimeout(reject, _timeout);
              });
              Promise.race([timer, loader]).then(function () {
                if (timeoutId) {
                  clearTimeout(timeoutId);
                  timeoutId = null;
                }

                callback(null, font);
              }, function () {
                warnID(4933, font);
                callback(null, font);
              });
            }

            function loadFont(url, options, onComplete) {
              var fontFamilyName = getFontFamily(url);

              if (_fontFaces[fontFamilyName]) {
                onComplete(null, fontFamilyName);
                return;
              }

              if (!_canvasContext) {
                var labelCanvas = document.createElement('canvas');
                labelCanvas.width = 100;
                labelCanvas.height = 100;
                _canvasContext = labelCanvas.getContext('2d');
              }

              var fontDesc = "40px " + fontFamilyName;
              var refWidth = safeMeasureText(_canvasContext, _testString, fontDesc);
              var fontStyle = document.createElement('style');
              fontStyle.type = 'text/css';
              var fontStr = '';

              if (Number.isNaN(fontFamilyName)) {
                fontStr += "@font-face { font-family:" + fontFamilyName + "; src:";
              } else {
                fontStr += "@font-face { font-family:\"" + fontFamilyName + "\"; src:";
              }

              fontStr += "url(\"" + url + "\");";
              fontStyle.textContent = fontStr + "}";
              document.body.appendChild(fontStyle);
              var preloadDiv = document.createElement('div');
              var divStyle = preloadDiv.style;
              divStyle.fontFamily = fontFamilyName;
              preloadDiv.innerHTML = '.';
              divStyle.position = 'absolute';
              divStyle.left = '-100px';
              divStyle.top = '-100px';
              document.body.appendChild(preloadDiv);

              if (useNativeCheck()) {
                nativeCheckFontLoaded(Date.now(), fontFamilyName, onComplete);
              } else {
                var fontLoadHandle = {
                  fontFamilyName: fontFamilyName,
                  refWidth: refWidth,
                  onComplete: onComplete,
                  startTime: Date.now()
                };

                _loadingFonts.push(fontLoadHandle);

                if (_intervalId === -1) {
                  _intervalId = setInterval(checkFontLoaded, 100);
                }
              }

              _fontFaces[fontFamilyName] = fontStyle;
            }
            function getFontFamily(fontHandle) {
              var ttfIndex = fontHandle.lastIndexOf('.ttf');

              if (ttfIndex === -1) {
                return fontHandle;
              }

              var slashPos = fontHandle.lastIndexOf('/');
              var fontFamilyName;

              if (slashPos === -1) {
                fontFamilyName = fontHandle.substring(0, ttfIndex) + "_LABEL";
              } else {
                fontFamilyName = fontHandle.substring(slashPos + 1, ttfIndex) + "_LABEL";
              }

              if (fontFamilyName.indexOf(' ') !== -1) {
                fontFamilyName = "\"" + fontFamilyName + "\"";
              }

              return fontFamilyName;
            }

            function createFont(id, data, options, onComplete) {
              var out = new TTFFont();
              out._nativeUrl = id;
              out._nativeAsset = data;
              onComplete(null, out);
            }

            downloader.register({
              '.font': loadFont,
              '.eot': loadFont,
              '.ttf': loadFont,
              '.woff': loadFont,
              '.svg': loadFont,
              '.ttc': loadFont
            });
            factory.register({
              '.font': createFont,
              '.eot': createFont,
              '.ttf': createFont,
              '.woff': createFont,
              '.svg': createFont,
              '.ttc': createFont
            });

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

            var _dec$16, _dec2$I, _dec3$A, _dec4$u, _dec5$n, _dec6$h, _dec7$f, _dec8$e, _dec9$b, _dec10$a, _dec11$9, _dec12$9, _dec13$8, _dec14$8, _dec15$8, _dec16$8, _dec17$7, _dec18$7, _dec19$7, _dec20$6, _dec21$6, _dec22$6, _dec23$6, _dec24$6, _dec25$6, _dec26$5, _dec27$4, _dec28$4, _dec29$4, _dec30$4, _dec31$4, _dec32$3, _class$17, _class2$$, _descriptor$Q, _descriptor2$B, _descriptor3$p, _descriptor4$l, _descriptor5$h, _descriptor6$b, _descriptor7$9, _descriptor8$9, _descriptor9$8, _descriptor10$8, _descriptor11$7, _descriptor12$6, _descriptor13$5, _descriptor14$5, _class3$p, _temp$12;

            var _tempColor = new Color();

            var Transition;

            (function (Transition) {
              Transition[Transition["NONE"] = 0] = "NONE";
              Transition[Transition["COLOR"] = 1] = "COLOR";
              Transition[Transition["SPRITE"] = 2] = "SPRITE";
              Transition[Transition["SCALE"] = 3] = "SCALE";
            })(Transition || (Transition = {}));

            ccenum(Transition);
            var State;

            (function (State) {
              State["NORMAL"] = "normal";
              State["HOVER"] = "hover";
              State["PRESSED"] = "pressed";
              State["DISABLED"] = "disabled";
            })(State || (State = {}));

            var EventType$2;

            (function (EventType) {
              EventType["CLICK"] = "click";
            })(EventType$2 || (EventType$2 = {}));

            var Button = function (v) { return exports({ Button: v, ButtonComponent: v }), v; }((_dec$16 = ccclass('cc.Button'), _dec2$I = help(), _dec3$A = executionOrder(110), _dec4$u = menu(), _dec5$n = requireComponent(UITransform), _dec6$h = type(Node$1), _dec7$f = displayOrder(), _dec8$e = tooltip(), _dec9$b = displayOrder(), _dec10$a = tooltip(), _dec11$9 = type(Transition), _dec12$9 = displayOrder(), _dec13$8 = tooltip(), _dec14$8 = tooltip(), _dec15$8 = tooltip(), _dec16$8 = tooltip(), _dec17$7 = tooltip(), _dec18$7 = rangeMin(), _dec19$7 = rangeMax(), _dec20$6 = tooltip(), _dec21$6 = tooltip(), _dec22$6 = type(SpriteFrame), _dec23$6 = tooltip(), _dec24$6 = type(SpriteFrame), _dec25$6 = tooltip(), _dec26$5 = type(SpriteFrame), _dec27$4 = tooltip(), _dec28$4 = type(SpriteFrame), _dec29$4 = tooltip(), _dec30$4 = type([EventHandler]), _dec31$4 = displayOrder(), _dec32$3 = tooltip(), _dec$16(_class$17 = _dec2$I(_class$17 = _dec3$A(_class$17 = _dec4$u(_class$17 = _dec5$n(_class$17 = executeInEditMode(_class$17 = (_class2$$ = (_temp$12 = _class3$p = function (_Component) {
              _inheritsLoose(Button, _Component);

              function Button() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Component.call.apply(_Component, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "clickEvents", _descriptor$Q, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_interactable", _descriptor2$B, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_transition", _descriptor3$p, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_normalColor", _descriptor4$l, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_hoverColor", _descriptor5$h, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_pressedColor", _descriptor6$b, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_disabledColor", _descriptor7$9, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_normalSprite", _descriptor8$9, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_hoverSprite", _descriptor9$8, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_pressedSprite", _descriptor10$8, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_disabledSprite", _descriptor11$7, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_duration", _descriptor12$6, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_zoomScale", _descriptor13$5, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_target", _descriptor14$5, _assertThisInitialized(_this));

                _this._pressed = false;
                _this._hovered = false;
                _this._fromColor = new Color();
                _this._toColor = new Color();
                _this._time = 0;
                _this._transitionFinished = true;
                _this._fromScale = new Vec3();
                _this._toScale = new Vec3();
                _this._originalScale = null;
                _this._sprite = null;
                _this._targetScale = new Vec3();
                return _this;
              }

              var _proto = Button.prototype;

              _proto.__preload = function __preload() {
                if (!this.target) {
                  this.target = this.node;
                }

                var sprite = this.node.getComponent(Sprite);

                if (sprite) {
                  this._normalSprite = sprite.spriteFrame;
                }

                this._applyTarget();

                this._resetState();
              };

              _proto.onEnable = function onEnable() {

                {
                  this._registerNodeEvent();
                }
              };

              _proto.onDisable = function onDisable() {
                this._resetState();

                {
                  this._unregisterNodeEvent();
                }
              };

              _proto.update = function update(dt) {
                var target = this.target;

                if (this._transitionFinished || !target) {
                  return;
                }

                if (this._transition !== Transition.COLOR && this._transition !== Transition.SCALE) {
                  return;
                }

                this._time += dt;
                var ratio = 1.0;

                if (this._duration > 0) {
                  ratio = this._time / this._duration;
                }

                if (ratio >= 1) {
                  ratio = 1;
                }

                if (this._transition === Transition.COLOR) {
                  var renderComp = target._uiProps.uiComp;
                  Color.lerp(_tempColor, this._fromColor, this._toColor, ratio);

                  if (renderComp) {
                    renderComp.color = _tempColor;
                  }
                } else if (this.transition === Transition.SCALE) {
                  target.getScale(this._targetScale);
                  this._targetScale.x = lerp(this._fromScale.x, this._toScale.x, ratio);
                  this._targetScale.y = lerp(this._fromScale.y, this._toScale.y, ratio);
                  target.setScale(this._targetScale);
                }

                if (ratio === 1) {
                  this._transitionFinished = true;
                }
              };

              _proto._resizeNodeToTargetNode = function _resizeNodeToTargetNode() {
                if (!this.target) {
                  return;
                }

                var targetTrans = this.target._uiProps.uiTransformComp;
              };

              _proto._resetState = function _resetState() {
                this._pressed = false;
                this._hovered = false;
                var target = this.target;

                if (!target) {
                  return;
                }

                var renderComp = target.getComponent(Renderable2D);

                if (!renderComp) {
                  return;
                }

                var transition = this._transition;

                if (transition === Transition.COLOR && this._interactable) {
                  renderComp.color = this._normalColor;
                } else if (transition === Transition.SCALE && this._originalScale) {
                  target.setScale(this._originalScale);
                }

                this._transitionFinished = true;
              };

              _proto._registerNodeEvent = function _registerNodeEvent() {
                this.node.on(SystemEventType.TOUCH_START, this._onTouchBegan, this);
                this.node.on(SystemEventType.TOUCH_MOVE, this._onTouchMove, this);
                this.node.on(SystemEventType.TOUCH_END, this._onTouchEnded, this);
                this.node.on(SystemEventType.TOUCH_CANCEL, this._onTouchCancel, this);
                this.node.on(SystemEventType.MOUSE_ENTER, this._onMouseMoveIn, this);
                this.node.on(SystemEventType.MOUSE_LEAVE, this._onMouseMoveOut, this);
              };

              _proto._registerTargetEvent = function _registerTargetEvent(target) {

                target.on(SystemEventType.TRANSFORM_CHANGED, this._onTargetTransformChanged, this);
              };

              _proto._unregisterNodeEvent = function _unregisterNodeEvent() {
                this.node.off(SystemEventType.TOUCH_START, this._onTouchBegan, this);
                this.node.off(SystemEventType.TOUCH_MOVE, this._onTouchMove, this);
                this.node.off(SystemEventType.TOUCH_END, this._onTouchEnded, this);
                this.node.off(SystemEventType.TOUCH_CANCEL, this._onTouchCancel, this);
                this.node.off(SystemEventType.MOUSE_ENTER, this._onMouseMoveIn, this);
                this.node.off(SystemEventType.MOUSE_LEAVE, this._onMouseMoveOut, this);
              };

              _proto._unregisterTargetEvent = function _unregisterTargetEvent(target) {

                target.off(SystemEventType.TRANSFORM_CHANGED);
              };

              _proto._getTargetSprite = function _getTargetSprite(target) {
                var sprite = null;

                if (target) {
                  sprite = target.getComponent(Sprite);
                }

                return sprite;
              };

              _proto._applyTarget = function _applyTarget() {
                if (this.target) {
                  this._sprite = this._getTargetSprite(this.target);

                  if (!this._originalScale) {
                    this._originalScale = new Vec3();
                  }

                  Vec3.copy(this._originalScale, this.target.getScale());
                }
              };

              _proto._onTargetSpriteFrameChanged = function _onTargetSpriteFrameChanged(comp) {
                if (this._transition === Transition.SPRITE) {
                  this._setCurrentStateSpriteFrame(comp.spriteFrame);
                }
              };

              _proto._setCurrentStateSpriteFrame = function _setCurrentStateSpriteFrame(spriteFrame) {
                if (!spriteFrame) {
                  return;
                }

                switch (this._getButtonState()) {
                  case State.NORMAL:
                    this._normalSprite = spriteFrame;
                    break;

                  case State.HOVER:
                    this._hoverSprite = spriteFrame;
                    break;

                  case State.PRESSED:
                    this._pressedSprite = spriteFrame;
                    break;

                  case State.DISABLED:
                    this._disabledSprite = spriteFrame;
                    break;
                }
              };

              _proto._onTargetColorChanged = function _onTargetColorChanged(color) {
                if (this._transition === Transition.COLOR) {
                  this._setCurrentStateColor(color);
                }
              };

              _proto._setCurrentStateColor = function _setCurrentStateColor(color) {
                switch (this._getButtonState()) {
                  case State.NORMAL:
                    this._normalColor = color;
                    break;

                  case State.HOVER:
                    this._hoverColor = color;
                    break;

                  case State.PRESSED:
                    this._pressedColor = color;
                    break;

                  case State.DISABLED:
                    this._disabledColor = color;
                    break;
                }
              };

              _proto._onTargetTransformChanged = function _onTargetTransformChanged(transformBit) {
                if (transformBit | TransformBit.SCALE && this._originalScale && this._transition === Transition.SCALE && this._transitionFinished) {
                  Vec3.copy(this._originalScale, this.target.getScale());
                }
              };

              _proto._onTouchBegan = function _onTouchBegan(event) {
                if (!this._interactable || !this.enabledInHierarchy) {
                  return;
                }

                this._pressed = true;

                this._updateState();

                if (event) {
                  event.propagationStopped = true;
                }
              };

              _proto._onTouchMove = function _onTouchMove(event) {
                if (!this._interactable || !this.enabledInHierarchy || !this._pressed) {
                  return;
                }

                if (!event) {
                  return;
                }

                var touch = event.touch;

                if (!touch) {
                  return;
                }

                var hit = this.node._uiProps.uiTransformComp.isHit(touch.getUILocation());

                if (this._transition === Transition.SCALE && this.target && this._originalScale) {
                  if (hit) {
                    Vec3.copy(this._fromScale, this._originalScale);
                    Vec3.multiplyScalar(this._toScale, this._originalScale, this._zoomScale);
                    this._transitionFinished = false;
                  } else {
                    this._time = 0;
                    this._transitionFinished = true;
                    this.target.setScale(this._originalScale);
                  }
                } else {
                  var state;

                  if (hit) {
                    state = State.PRESSED;
                  } else {
                    state = State.NORMAL;
                  }

                  this._applyTransition(state);
                }

                if (event) {
                  event.propagationStopped = true;
                }
              };

              _proto._onTouchEnded = function _onTouchEnded(event) {
                if (!this._interactable || !this.enabledInHierarchy) {
                  return;
                }

                if (this._pressed) {
                  EventHandler.emitEvents(this.clickEvents, event);
                  this.node.emit(EventType$2.CLICK, this);
                }

                this._pressed = false;

                this._updateState();

                if (event) {
                  event.propagationStopped = true;
                }
              };

              _proto._onTouchCancel = function _onTouchCancel(event) {
                if (!this._interactable || !this.enabledInHierarchy) {
                  return;
                }

                this._pressed = false;

                this._updateState();
              };

              _proto._onMouseMoveIn = function _onMouseMoveIn(event) {
                if (this._pressed || !this.interactable || !this.enabledInHierarchy) {
                  return;
                }

                if (this._transition === Transition.SPRITE && !this._hoverSprite) {
                  return;
                }

                if (!this._hovered) {
                  this._hovered = true;

                  this._updateState();
                }
              };

              _proto._onMouseMoveOut = function _onMouseMoveOut(event) {
                if (this._hovered) {
                  this._hovered = false;

                  this._updateState();
                }
              };

              _proto._updateState = function _updateState() {
                var state = this._getButtonState();

                this._applyTransition(state);
              };

              _proto._getButtonState = function _getButtonState() {
                var state = State.NORMAL;

                if (!this._interactable) {
                  state = State.DISABLED;
                } else if (this._pressed) {
                  state = State.PRESSED;
                } else if (this._hovered) {
                  state = State.HOVER;
                }

                return state.toString();
              };

              _proto._updateColorTransition = function _updateColorTransition(state) {
                var _this$target;

                var color = this[state + "Color"];
                var renderComp = (_this$target = this.target) === null || _this$target === void 0 ? void 0 : _this$target.getComponent(Renderable2D);

                if (!renderComp) {
                  return;
                }

                if ( state === State.DISABLED) {
                  renderComp.color = color;
                } else {
                  this._fromColor = renderComp.color.clone();
                  this._toColor = color;
                  this._time = 0;
                  this._transitionFinished = false;
                }
              };

              _proto._updateSpriteTransition = function _updateSpriteTransition(state) {
                var sprite = this[state + "Sprite"];

                if (this._sprite && sprite) {
                  this._sprite.spriteFrame = sprite;
                }
              };

              _proto._updateScaleTransition = function _updateScaleTransition(state) {
                if (!this._interactable) {
                  return;
                }

                if (state === State.PRESSED) {
                  this._zoomUp();
                } else {
                  this._zoomBack();
                }
              };

              _proto._zoomUp = function _zoomUp() {
                if (!this._originalScale) {
                  return;
                }

                Vec3.copy(this._fromScale, this._originalScale);
                Vec3.multiplyScalar(this._toScale, this._originalScale, this._zoomScale);
                this._time = 0;
                this._transitionFinished = false;
              };

              _proto._zoomBack = function _zoomBack() {
                if (!this.target || !this._originalScale) {
                  return;
                }

                Vec3.copy(this._fromScale, this.target.getScale());
                Vec3.copy(this._toScale, this._originalScale);
                this._time = 0;
                this._transitionFinished = false;
              };

              _proto._applyTransition = function _applyTransition(state) {
                var transition = this._transition;

                if (transition === Transition.COLOR) {
                  this._updateColorTransition(state);
                } else if (transition === Transition.SPRITE) {
                  this._updateSpriteTransition(state);
                } else if (transition === Transition.SCALE) {
                  this._updateScaleTransition(state);
                }
              };

              _createClass(Button, [{
                key: "target",
                get: function get() {
                  return this._target || this.node;
                },
                set: function set(value) {
                  if (this._target === value) {
                    return;
                  }

                  if (this._target) {
                    this._unregisterTargetEvent(this._target);
                  }

                  this._target = value;

                  this._applyTarget();
                }
              }, {
                key: "interactable",
                get: function get() {
                  return this._interactable;
                },
                set: function set(value) {
                  this._interactable = value;

                  this._updateState();

                  if (!this._interactable) {
                    this._resetState();
                  }
                }
              }, {
                key: "_resizeToTarget",
                set: function set(value) {
                  if (value) {
                    this._resizeNodeToTargetNode();
                  }
                }
              }, {
                key: "transition",
                get: function get() {
                  return this._transition;
                },
                set: function set(value) {
                  if (this._transition === value) {
                    return;
                  }

                  if (this._transition === Transition.COLOR) {
                    this._updateColorTransition(State.NORMAL);
                  } else if (this._transition === Transition.SPRITE) {
                    this._updateSpriteTransition(State.NORMAL);
                  }

                  this._transition = value;

                  this._updateState();
                }
              }, {
                key: "normalColor",
                get: function get() {
                  return this._normalColor;
                },
                set: function set(value) {
                  if (this._normalColor === value) {
                    return;
                  }

                  this._normalColor.set(value);

                  this._updateState();
                }
              }, {
                key: "pressedColor",
                get: function get() {
                  return this._pressedColor;
                },
                set: function set(value) {
                  if (this._pressedColor === value) {
                    return;
                  }

                  this._pressedColor.set(value);
                }
              }, {
                key: "hoverColor",
                get: function get() {
                  return this._hoverColor;
                },
                set: function set(value) {
                  if (this._hoverColor === value) {
                    return;
                  }

                  this._hoverColor.set(value);
                }
              }, {
                key: "disabledColor",
                get: function get() {
                  return this._disabledColor;
                },
                set: function set(value) {
                  if (this._disabledColor === value) {
                    return;
                  }

                  this._disabledColor.set(value);

                  this._updateState();
                }
              }, {
                key: "duration",
                get: function get() {
                  return this._duration;
                },
                set: function set(value) {
                  if (this._duration === value) {
                    return;
                  }

                  this._duration = value;
                }
              }, {
                key: "zoomScale",
                get: function get() {
                  return this._zoomScale;
                },
                set: function set(value) {
                  if (this._zoomScale === value) {
                    return;
                  }

                  this._zoomScale = value;
                }
              }, {
                key: "normalSprite",
                get: function get() {
                  return this._normalSprite;
                },
                set: function set(value) {
                  if (this._normalSprite === value) {
                    return;
                  }

                  this._normalSprite = value;
                  var sprite = this.node.getComponent(Sprite);

                  if (sprite) {
                    sprite.spriteFrame = value;
                  }

                  this._updateState();
                }
              }, {
                key: "pressedSprite",
                get: function get() {
                  return this._pressedSprite;
                },
                set: function set(value) {
                  if (this._pressedSprite === value) {
                    return;
                  }

                  this._pressedSprite = value;

                  this._updateState();
                }
              }, {
                key: "hoverSprite",
                get: function get() {
                  return this._hoverSprite;
                },
                set: function set(value) {
                  if (this._hoverSprite === value) {
                    return;
                  }

                  this._hoverSprite = value;

                  this._updateState();
                }
              }, {
                key: "disabledSprite",
                get: function get() {
                  return this._disabledSprite;
                },
                set: function set(value) {
                  if (this._disabledSprite === value) {
                    return;
                  }

                  this._disabledSprite = value;

                  this._updateState();
                }
              }]);

              return Button;
            }(Component), _class3$p.Transition = Transition, _class3$p.EventType = EventType$2, _temp$12), (_applyDecoratedDescriptor(_class2$$.prototype, "target", [_dec6$h, _dec7$f, _dec8$e], Object.getOwnPropertyDescriptor(_class2$$.prototype, "target"), _class2$$.prototype), _applyDecoratedDescriptor(_class2$$.prototype, "interactable", [_dec9$b, _dec10$a], Object.getOwnPropertyDescriptor(_class2$$.prototype, "interactable"), _class2$$.prototype), _applyDecoratedDescriptor(_class2$$.prototype, "transition", [_dec11$9, _dec12$9, _dec13$8], Object.getOwnPropertyDescriptor(_class2$$.prototype, "transition"), _class2$$.prototype), _applyDecoratedDescriptor(_class2$$.prototype, "normalColor", [_dec14$8], Object.getOwnPropertyDescriptor(_class2$$.prototype, "normalColor"), _class2$$.prototype), _applyDecoratedDescriptor(_class2$$.prototype, "pressedColor", [_dec15$8], Object.getOwnPropertyDescriptor(_class2$$.prototype, "pressedColor"), _class2$$.prototype), _applyDecoratedDescriptor(_class2$$.prototype, "hoverColor", [_dec16$8], Object.getOwnPropertyDescriptor(_class2$$.prototype, "hoverColor"), _class2$$.prototype), _applyDecoratedDescriptor(_class2$$.prototype, "disabledColor", [_dec17$7], Object.getOwnPropertyDescriptor(_class2$$.prototype, "disabledColor"), _class2$$.prototype), _applyDecoratedDescriptor(_class2$$.prototype, "duration", [_dec18$7, _dec19$7, _dec20$6], Object.getOwnPropertyDescriptor(_class2$$.prototype, "duration"), _class2$$.prototype), _applyDecoratedDescriptor(_class2$$.prototype, "zoomScale", [_dec21$6], Object.getOwnPropertyDescriptor(_class2$$.prototype, "zoomScale"), _class2$$.prototype), _applyDecoratedDescriptor(_class2$$.prototype, "normalSprite", [_dec22$6, _dec23$6], Object.getOwnPropertyDescriptor(_class2$$.prototype, "normalSprite"), _class2$$.prototype), _applyDecoratedDescriptor(_class2$$.prototype, "pressedSprite", [_dec24$6, _dec25$6], Object.getOwnPropertyDescriptor(_class2$$.prototype, "pressedSprite"), _class2$$.prototype), _applyDecoratedDescriptor(_class2$$.prototype, "hoverSprite", [_dec26$5, _dec27$4], Object.getOwnPropertyDescriptor(_class2$$.prototype, "hoverSprite"), _class2$$.prototype), _applyDecoratedDescriptor(_class2$$.prototype, "disabledSprite", [_dec28$4, _dec29$4], Object.getOwnPropertyDescriptor(_class2$$.prototype, "disabledSprite"), _class2$$.prototype), _descriptor$Q = _applyDecoratedDescriptor(_class2$$.prototype, "clickEvents", [_dec30$4, serializable, _dec31$4, _dec32$3], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor2$B = _applyDecoratedDescriptor(_class2$$.prototype, "_interactable", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _descriptor3$p = _applyDecoratedDescriptor(_class2$$.prototype, "_transition", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return Transition.NONE;
              }
            }), _descriptor4$l = _applyDecoratedDescriptor(_class2$$.prototype, "_normalColor", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return Color.WHITE.clone();
              }
            }), _descriptor5$h = _applyDecoratedDescriptor(_class2$$.prototype, "_hoverColor", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new Color(211, 211, 211, 255);
              }
            }), _descriptor6$b = _applyDecoratedDescriptor(_class2$$.prototype, "_pressedColor", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return Color.WHITE.clone();
              }
            }), _descriptor7$9 = _applyDecoratedDescriptor(_class2$$.prototype, "_disabledColor", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new Color(124, 124, 124, 255);
              }
            }), _descriptor8$9 = _applyDecoratedDescriptor(_class2$$.prototype, "_normalSprite", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor9$8 = _applyDecoratedDescriptor(_class2$$.prototype, "_hoverSprite", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor10$8 = _applyDecoratedDescriptor(_class2$$.prototype, "_pressedSprite", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor11$7 = _applyDecoratedDescriptor(_class2$$.prototype, "_disabledSprite", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor12$6 = _applyDecoratedDescriptor(_class2$$.prototype, "_duration", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0.1;
              }
            }), _descriptor13$5 = _applyDecoratedDescriptor(_class2$$.prototype, "_zoomScale", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1.2;
              }
            }), _descriptor14$5 = _applyDecoratedDescriptor(_class2$$.prototype, "_target", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            })), _class2$$)) || _class$17) || _class$17) || _class$17) || _class$17) || _class$17) || _class$17));

            var tabIndexUtil = function () {
              function tabIndexUtil() {}

              tabIndexUtil.add = function add(editBoxImpl) {
                var list = this._tabIndexList;
                var index = list.indexOf(editBoxImpl);

                if (index === -1) {
                  list.push(editBoxImpl);
                }
              };

              tabIndexUtil.remove = function remove(editBoxImpl) {
                var list = this._tabIndexList;
                var index = list.indexOf(editBoxImpl);

                if (index !== -1) {
                  list.splice(index, 1);
                }
              };

              tabIndexUtil.resort = function resort() {
                this._tabIndexList.sort(function (a, b) {
                  return a._delegate.tabIndex - b._delegate.tabIndex;
                });
              };

              tabIndexUtil.next = function next(editBoxImpl) {
                var list = this._tabIndexList;
                var index = list.indexOf(editBoxImpl);
                editBoxImpl.setFocus(false);

                if (index !== -1) {
                  var nextImpl = list[index + 1];

                  if (nextImpl && nextImpl._delegate.tabIndex >= 0) {
                    nextImpl.setFocus(true);
                  }
                }
              };

              return tabIndexUtil;
            }();
            tabIndexUtil._tabIndexList = [];

            var KeyboardReturnType;

            (function (KeyboardReturnType) {
              KeyboardReturnType[KeyboardReturnType["DEFAULT"] = 0] = "DEFAULT";
              KeyboardReturnType[KeyboardReturnType["DONE"] = 1] = "DONE";
              KeyboardReturnType[KeyboardReturnType["SEND"] = 2] = "SEND";
              KeyboardReturnType[KeyboardReturnType["SEARCH"] = 3] = "SEARCH";
              KeyboardReturnType[KeyboardReturnType["GO"] = 4] = "GO";
              KeyboardReturnType[KeyboardReturnType["NEXT"] = 5] = "NEXT";
            })(KeyboardReturnType || (KeyboardReturnType = {}));

            Enum(KeyboardReturnType);
            var InputMode;

            (function (InputMode) {
              InputMode[InputMode["ANY"] = 0] = "ANY";
              InputMode[InputMode["EMAIL_ADDR"] = 1] = "EMAIL_ADDR";
              InputMode[InputMode["NUMERIC"] = 2] = "NUMERIC";
              InputMode[InputMode["PHONE_NUMBER"] = 3] = "PHONE_NUMBER";
              InputMode[InputMode["URL"] = 4] = "URL";
              InputMode[InputMode["DECIMAL"] = 5] = "DECIMAL";
              InputMode[InputMode["SINGLE_LINE"] = 6] = "SINGLE_LINE";
            })(InputMode || (InputMode = {}));

            Enum(InputMode);
            var InputFlag;

            (function (InputFlag) {
              InputFlag[InputFlag["PASSWORD"] = 0] = "PASSWORD";
              InputFlag[InputFlag["SENSITIVE"] = 1] = "SENSITIVE";
              InputFlag[InputFlag["INITIAL_CAPS_WORD"] = 2] = "INITIAL_CAPS_WORD";
              InputFlag[InputFlag["INITIAL_CAPS_SENTENCE"] = 3] = "INITIAL_CAPS_SENTENCE";
              InputFlag[InputFlag["INITIAL_CAPS_ALL_CHARACTERS"] = 4] = "INITIAL_CAPS_ALL_CHARACTERS";
              InputFlag[InputFlag["DEFAULT"] = 5] = "DEFAULT";
            })(InputFlag || (InputFlag = {}));

            Enum(InputFlag);

            var EditBoxImplBase = function () {
              function EditBoxImplBase() {
                this._editing = false;
                this._delegate = null;
              }

              var _proto = EditBoxImplBase.prototype;

              _proto.init = function init(delegate) {};

              _proto.onEnable = function onEnable() {};

              _proto.update = function update() {};

              _proto.onDisable = function onDisable() {
                if (this._editing) {
                  this.endEditing();
                }
              };

              _proto.clear = function clear() {
                this._delegate = null;
              };

              _proto.setTabIndex = function setTabIndex(index) {};

              _proto.setSize = function setSize(width, height) {};

              _proto.setFocus = function setFocus(value) {
                if (value) {
                  this.beginEditing();
                } else {
                  this.endEditing();
                }
              };

              _proto.isFocused = function isFocused() {
                return this._editing;
              };

              _proto.beginEditing = function beginEditing() {};

              _proto.endEditing = function endEditing() {};

              return EditBoxImplBase;
            }();

            var SCROLLY = 40;
            var LEFT_PADDING = 2;
            var DELAY_TIME = 400;

            var _matrix$1 = new Mat4();

            var _matrix_temp = new Mat4();

            var _vec3$1 = new Vec3();

            var _currentEditBoxImpl = null;
            var _domCount = 0;
            var EditBoxImpl = function (_EditBoxImplBase) {
              _inheritsLoose(EditBoxImpl, _EditBoxImplBase);

              function EditBoxImpl() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _EditBoxImplBase.call.apply(_EditBoxImplBase, [this].concat(args)) || this;
                _this._delegate = null;
                _this._inputMode = -1;
                _this._inputFlag = -1;
                _this._returnType = -1;
                _this.__eventListeners = {};
                _this.__fullscreen = false;
                _this.__autoResize = false;
                _this.__orientationChanged = void 0;
                _this._edTxt = null;
                _this._isTextArea = false;
                _this._textLabelFont = null;
                _this._textLabelFontSize = null;
                _this._textLabelFontColor = null;
                _this._textLabelAlign = null;
                _this._placeholderLabelFont = null;
                _this._placeholderLabelFontSize = null;
                _this._placeholderLabelFontColor = null;
                _this._placeholderLabelAlign = null;
                _this._placeholderLineHeight = null;
                _this._placeholderStyleSheet = null;
                _this._domId = "EditBoxId_" + ++_domCount;
                return _this;
              }

              var _proto = EditBoxImpl.prototype;

              _proto.init = function init(delegate) {
                if (!delegate) {
                  return;
                }

                this._delegate = delegate;

                if (delegate.inputMode === InputMode.ANY) {
                  this._createTextArea();
                } else {
                  this._createInput();
                }

                tabIndexUtil.add(this);
                this.setTabIndex(delegate.tabIndex);

                this._initStyleSheet();

                this._registerEventListeners();

                this._addDomToGameContainer();

                this.__fullscreen = view.isAutoFullScreenEnabled();
                this.__autoResize = view._resizeWithBrowserSize;
              };

              _proto.clear = function clear() {
                this._removeEventListeners();

                this._removeDomFromGameContainer();

                tabIndexUtil.remove(this);

                if (_currentEditBoxImpl === this) {
                  _currentEditBoxImpl = null;
                }

                this._delegate = null;
              };

              _proto.update = function update() {
                this._updateMatrix();
              };

              _proto.setTabIndex = function setTabIndex(index) {
                this._edTxt.tabIndex = index;
                tabIndexUtil.resort();
              };

              _proto.setSize = function setSize(width, height) {
                var elem = this._edTxt;

                if (elem) {
                  elem.style.width = width + "px";
                  elem.style.height = height + "px";
                }
              };

              _proto.beginEditing = function beginEditing() {
                if (_currentEditBoxImpl && _currentEditBoxImpl !== this) {
                  _currentEditBoxImpl.setFocus(false);
                }

                this._editing = true;
                _currentEditBoxImpl = this;

                this._delegate._editBoxEditingDidBegan();

                this._showDom();

                this._edTxt.focus();
              };

              _proto.endEditing = function endEditing() {
                this._edTxt.blur();
              };

              _proto._createInput = function _createInput() {
                this._isTextArea = false;
                this._edTxt = document.createElement('input');
              };

              _proto._createTextArea = function _createTextArea() {
                this._isTextArea = true;
                this._edTxt = document.createElement('textarea');
              };

              _proto._addDomToGameContainer = function _addDomToGameContainer() {
                if (legacyCC.GAME_VIEW && this._edTxt) {
                  legacyCC.gameView.container.appendChild(this._edTxt);
                  legacyCC.gameView.head.appendChild(this._placeholderStyleSheet);
                } else if (game.container && this._edTxt) {
                  game.container.appendChild(this._edTxt);
                  document.head.appendChild(this._placeholderStyleSheet);
                }
              };

              _proto._removeDomFromGameContainer = function _removeDomFromGameContainer() {
                var hasElem = legacyCC.GAME_VIEW ? contains$1(legacyCC.gameView.container, this._edTxt) : contains$1(game.container, this._edTxt);

                if (hasElem && this._edTxt) {
                  if (legacyCC.GAME_VIEW) {
                    legacyCC.gameView.container.removeChild(this._edTxt);
                  } else {
                    game.container.removeChild(this._edTxt);
                  }
                }

                var hasStyleSheet = legacyCC.GAME_VIEW ? contains$1(legacyCC.gameView.head, this._placeholderStyleSheet) : contains$1(document.head, this._placeholderStyleSheet);

                if (hasStyleSheet) {
                  if (legacyCC.GAME_VIEW) {
                    legacyCC.gameView.head.removeChild(this._placeholderStyleSheet);
                  } else {
                    document.head.removeChild(this._placeholderStyleSheet);
                  }
                }

                this._edTxt = null;
                this._placeholderStyleSheet = null;
              };

              _proto._showDom = function _showDom() {
                this._updateMaxLength();

                this._updateInputType();

                this._updateStyleSheet();

                if (this._edTxt && this._delegate) {
                  this._edTxt.style.display = '';

                  this._delegate._hideLabels();
                }

                if (sys.isMobile) {
                  this._showDomOnMobile();
                }
              };

              _proto._hideDom = function _hideDom() {
                var elem = this._edTxt;

                if (elem && this._delegate) {
                  elem.style.display = 'none';

                  this._delegate._showLabels();
                }

                if (sys.isMobile) {
                  this._hideDomOnMobile();
                }
              };

              _proto._showDomOnMobile = function _showDomOnMobile() {
                if (system.os !== OS.ANDROID && system.os !== OS.OHOS) {
                  return;
                }

                if (this.__fullscreen) {
                  view.enableAutoFullScreen(false);
                  screen.exitFullScreen();
                }

                if (this.__autoResize) {
                  view.resizeWithBrowserSize(false);
                }

                this._adjustWindowScroll();
              };

              _proto._hideDomOnMobile = function _hideDomOnMobile() {
                var _this2 = this;

                if (system.os === OS.ANDROID || system.os === OS.OHOS) {
                  if (this.__autoResize) {
                    view.resizeWithBrowserSize(true);
                  }

                  setTimeout(function () {
                    if (!_currentEditBoxImpl) {
                      if (_this2.__fullscreen) {
                        view.enableAutoFullScreen(true);
                      }
                    }
                  }, DELAY_TIME);
                }

                this._scrollBackWindow();
              };

              _proto._adjustWindowScroll = function _adjustWindowScroll() {
                var _this3 = this;

                setTimeout(function () {
                  if (window.scrollY < SCROLLY) {
                    _this3._edTxt.scrollIntoView({
                      block: 'start',
                      inline: 'nearest',
                      behavior: 'smooth'
                    });
                  }
                }, DELAY_TIME);
              };

              _proto._scrollBackWindow = function _scrollBackWindow() {
                setTimeout(function () {
                  if (system.browserType === BrowserType.WECHAT && system.os === OS.IOS) {
                    if (window.top) {
                      window.top.scrollTo(0, 0);
                    }

                    return;
                  }

                  window.scrollTo(0, 0);
                }, DELAY_TIME);
              };

              _proto._updateMatrix = function _updateMatrix() {
                if (!this._edTxt) {
                  return;
                }

                var node = this._delegate.node;
                var scaleX = view.getScaleX();
                var scaleY = view.getScaleY();
                var widthRatio = 1;
                var heightRatio = 1;

                if (legacyCC.GAME_VIEW) {
                  widthRatio = legacyCC.gameView.canvas.width / legacyCC.game.canvas.width;
                  heightRatio = legacyCC.gameView.canvas.height / legacyCC.game.canvas.height;
                }

                scaleX *= widthRatio;
                scaleY *= heightRatio;
                var viewport = view.getViewportRect();
                var dpr = view.getDevicePixelRatio();
                node.getWorldMatrix(_matrix$1);
                var transform = node._uiProps.uiTransformComp;

                if (transform) {
                  Vec3.set(_vec3$1, -transform.anchorX * transform.width, -transform.anchorY * transform.height, _vec3$1.z);
                }

                Mat4.transform(_matrix$1, _matrix$1, _vec3$1);

                if (!node._uiProps.uiTransformComp) {
                  return;
                }

                var camera = director.root.batcher2D.getFirstRenderCamera(node);
                if (!camera) return;
                camera.node.getWorldRT(_matrix_temp);
                var m12 = _matrix_temp.m12;
                var m13 = _matrix_temp.m13;
                var center = visibleRect.center;
                _matrix_temp.m12 = center.x - (_matrix_temp.m00 * m12 + _matrix_temp.m04 * m13);
                _matrix_temp.m13 = center.y - (_matrix_temp.m01 * m12 + _matrix_temp.m05 * m13);
                Mat4.multiply(_matrix_temp, _matrix_temp, _matrix$1);
                scaleX /= dpr;
                scaleY /= dpr;
                var container = legacyCC.GAME_VIEW ? legacyCC.gameView.container : game.container;
                var a = _matrix_temp.m00 * scaleX;
                var b = _matrix$1.m01;
                var c = _matrix$1.m04;
                var d = _matrix_temp.m05 * scaleY;
                var offsetX = parseInt(container && container.style.paddingLeft || '0');
                offsetX += viewport.x * widthRatio / dpr;
                var offsetY = parseInt(container && container.style.paddingBottom || '0');
                offsetY += viewport.y / dpr;
                var tx = _matrix_temp.m12 * scaleX + offsetX;
                var ty = _matrix_temp.m13 * scaleY + offsetY;
                var matrix = "matrix(" + a + "," + -b + "," + -c + "," + d + "," + tx + "," + -ty + ")";
                this._edTxt.style.transform = matrix;
                this._edTxt.style['-webkit-transform'] = matrix;
                this._edTxt.style['transform-origin'] = '0px 100% 0px';
                this._edTxt.style['-webkit-transform-origin'] = '0px 100% 0px';
              };

              _proto._updateInputType = function _updateInputType() {
                var delegate = this._delegate;
                var inputMode = delegate.inputMode;
                var inputFlag = delegate.inputFlag;
                var returnType = delegate.returnType;
                var elem = this._edTxt;

                if (this._inputMode === inputMode && this._inputFlag === inputFlag && this._returnType === returnType) {
                  return;
                }

                this._inputMode = inputMode;
                this._inputFlag = inputFlag;
                this._returnType = returnType;

                if (this._isTextArea) {
                  var transform = 'none';

                  if (inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS) {
                    transform = 'uppercase';
                  } else if (inputFlag === InputFlag.INITIAL_CAPS_WORD) {
                    transform = 'capitalize';
                  }

                  elem.style.textTransform = transform;
                  return;
                }

                elem = elem;

                if (inputFlag === InputFlag.PASSWORD) {
                  elem.type = 'password';
                  elem.style.textTransform = 'none';
                  return;
                }

                var type = elem.type;

                if (inputMode === InputMode.EMAIL_ADDR) {
                  type = 'email';
                } else if (inputMode === InputMode.NUMERIC || inputMode === InputMode.DECIMAL) {
                  type = 'number';
                } else if (inputMode === InputMode.PHONE_NUMBER) {
                  type = 'number';
                  elem.pattern = '[0-9]*';
                } else if (inputMode === InputMode.URL) {
                  type = 'url';
                } else {
                  type = 'text';

                  if (returnType === KeyboardReturnType.SEARCH) {
                    type = 'search';
                  }
                }

                elem.type = type;
                var textTransform = 'none';

                if (inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS) {
                  textTransform = 'uppercase';
                } else if (inputFlag === InputFlag.INITIAL_CAPS_WORD) {
                  textTransform = 'capitalize';
                }

                elem.style.textTransform = textTransform;
              };

              _proto._updateMaxLength = function _updateMaxLength() {
                var maxLength = this._delegate.maxLength;

                if (maxLength < 0) {
                  maxLength = 65535;
                }

                this._edTxt.maxLength = maxLength;
              };

              _proto._initStyleSheet = function _initStyleSheet() {
                if (!this._edTxt) {
                  return;
                }

                var elem = this._edTxt;
                elem.style.color = '#000000';
                elem.style.border = '0px';
                elem.style.background = 'transparent';
                elem.style.width = '100%';
                elem.style.height = '100%';
                elem.style.outline = 'medium';
                elem.style.padding = '0';
                elem.style.textTransform = 'none';
                elem.style.display = 'none';
                elem.style.position = 'absolute';
                elem.style.bottom = '0px';
                elem.style.left = LEFT_PADDING + "px";
                elem.className = 'cocosEditBox';
                elem.style.fontFamily = 'Arial';
                elem.id = this._domId;

                if (!this._isTextArea) {
                  elem = elem;
                  elem.type = 'text';
                  elem.style['-moz-appearance'] = 'textfield';
                } else {
                  elem.style.resize = 'none';
                  elem.style.overflowY = 'scroll';
                }

                this._placeholderStyleSheet = document.createElement('style');
              };

              _proto._updateStyleSheet = function _updateStyleSheet() {
                var delegate = this._delegate;
                var elem = this._edTxt;

                if (elem && delegate) {
                  elem.value = delegate.string;
                  elem.placeholder = delegate.placeholder;

                  this._updateTextLabel(delegate.textLabel);

                  this._updatePlaceholderLabel(delegate.placeholderLabel);
                }
              };

              _proto._updateTextLabel = function _updateTextLabel(textLabel) {
                if (!textLabel) {
                  return;
                }

                var font = textLabel.font;

                if (font && !(font instanceof BitmapFont)) {
                  font = font._fontFamily;
                } else {
                  font = textLabel.fontFamily;
                }

                var fontSize = textLabel.fontSize * textLabel.node.scale.y;

                if (this._textLabelFont === font && this._textLabelFontSize === fontSize && this._textLabelFontColor === textLabel.fontColor && this._textLabelAlign === textLabel.horizontalAlign) {
                  return;
                }

                this._textLabelFont = font;
                this._textLabelFontSize = fontSize;
                this._textLabelFontColor = textLabel.fontColor;
                this._textLabelAlign = textLabel.horizontalAlign;

                if (!this._edTxt) {
                  return;
                }

                var elem = this._edTxt;
                elem.style.fontSize = fontSize + "px";
                elem.style.color = textLabel.color.toCSS();
                elem.style.fontFamily = font;

                switch (textLabel.horizontalAlign) {
                  case Label.HorizontalAlign.LEFT:
                    elem.style.textAlign = 'left';
                    break;

                  case Label.HorizontalAlign.CENTER:
                    elem.style.textAlign = 'center';
                    break;

                  case Label.HorizontalAlign.RIGHT:
                    elem.style.textAlign = 'right';
                    break;
                }
              };

              _proto._updatePlaceholderLabel = function _updatePlaceholderLabel(placeholderLabel) {
                if (!placeholderLabel) {
                  return;
                }

                var font = placeholderLabel.font;

                if (font && !(font instanceof BitmapFont)) {
                  font = placeholderLabel.font._fontFamily;
                } else {
                  font = placeholderLabel.fontFamily;
                }

                var fontSize = placeholderLabel.fontSize * placeholderLabel.node.scale.y;

                if (this._placeholderLabelFont === font && this._placeholderLabelFontSize === fontSize && this._placeholderLabelFontColor === placeholderLabel.fontColor && this._placeholderLabelAlign === placeholderLabel.horizontalAlign && this._placeholderLineHeight === placeholderLabel.fontSize) {
                  return;
                }

                this._placeholderLabelFont = font;
                this._placeholderLabelFontSize = fontSize;
                this._placeholderLabelFontColor = placeholderLabel.fontColor;
                this._placeholderLabelAlign = placeholderLabel.horizontalAlign;
                this._placeholderLineHeight = placeholderLabel.fontSize;
                var styleEl = this._placeholderStyleSheet;
                var fontColor = placeholderLabel.color.toCSS();
                var lineHeight = placeholderLabel.fontSize;
                var horizontalAlign = '';

                switch (placeholderLabel.horizontalAlign) {
                  case Label.HorizontalAlign.LEFT:
                    horizontalAlign = 'left';
                    break;

                  case Label.HorizontalAlign.CENTER:
                    horizontalAlign = 'center';
                    break;

                  case Label.HorizontalAlign.RIGHT:
                    horizontalAlign = 'right';
                    break;
                }

                styleEl.innerHTML = "#" + this._domId + "::-webkit-input-placeholder{text-transform: initial;-family: " + font + ";font-size: " + fontSize + "px;color: " + fontColor + ";line-height: " + lineHeight + "px;text-align: " + horizontalAlign + ";}" + ("#" + this._domId + "::-moz-placeholder{text-transform: initial;-family: " + font + ";font-size: " + fontSize + "px;color: " + fontColor + ";line-height: " + lineHeight + "px;text-align: " + horizontalAlign + ";}") + ("#" + this._domId + "::-ms-input-placeholder{text-transform: initial;-family: " + font + ";font-size: " + fontSize + "px;color: " + fontColor + ";line-height: " + lineHeight + "px;text-align: " + horizontalAlign + ";}");

                if (system.browserType === BrowserType.EDGE) {
                  styleEl.innerHTML += "#" + this._domId + "::-ms-clear{display: none;}";
                }
              };

              _proto._registerEventListeners = function _registerEventListeners() {
                var _this4 = this;

                if (!this._edTxt) {
                  return;
                }

                var elem = this._edTxt;
                var inputLock = false;
                var cbs = this.__eventListeners;

                cbs.compositionStart = function () {
                  inputLock = true;
                };

                cbs.compositionEnd = function () {
                  inputLock = false;

                  _this4._delegate._editBoxTextChanged(elem.value);
                };

                cbs.onInput = function () {
                  if (inputLock) {
                    return;
                  }

                  var delegate = _this4._delegate;
                  var maxLength = delegate.maxLength;

                  if (maxLength >= 0) {
                    elem.value = elem.value.slice(0, maxLength);
                  }

                  delegate._editBoxTextChanged(elem.value);
                };

                cbs.onClick = function () {
                  if (_this4._editing) {
                    if (sys.isMobile) {
                      _this4._adjustWindowScroll();
                    }
                  }
                };

                cbs.onKeydown = function (e) {
                  if (e.keyCode === macro.KEY.enter) {
                    e.propagationStopped = true;

                    _this4._delegate._editBoxEditingReturn();

                    if (!_this4._isTextArea) {
                      elem.blur();
                    }
                  } else if (e.keyCode === macro.KEY.tab) {
                    e.propagationStopped = true;
                    e.preventDefault();
                    tabIndexUtil.next(_this4);
                  }
                };

                cbs.onBlur = function () {
                  if (sys.isMobile && inputLock) {
                    cbs.compositionEnd();
                  }

                  _this4._editing = false;
                  _currentEditBoxImpl = null;

                  _this4._hideDom();

                  _this4._delegate._editBoxEditingDidEnded();
                };

                elem.addEventListener('compositionstart', cbs.compositionStart);
                elem.addEventListener('compositionend', cbs.compositionEnd);
                elem.addEventListener('input', cbs.onInput);
                elem.addEventListener('keydown', cbs.onKeydown);
                elem.addEventListener('blur', cbs.onBlur);
                elem.addEventListener('touchstart', cbs.onClick);
              };

              _proto._removeEventListeners = function _removeEventListeners() {
                if (!this._edTxt) {
                  return;
                }

                var elem = this._edTxt;
                var cbs = this.__eventListeners;
                elem.removeEventListener('compositionstart', cbs.compositionStart);
                elem.removeEventListener('compositionend', cbs.compositionEnd);
                elem.removeEventListener('input', cbs.onInput);
                elem.removeEventListener('keydown', cbs.onKeydown);
                elem.removeEventListener('blur', cbs.onBlur);
                elem.removeEventListener('touchstart', cbs.onClick);
                cbs.compositionStart = null;
                cbs.compositionEnd = null;
                cbs.onInput = null;
                cbs.onKeydown = null;
                cbs.onBlur = null;
                cbs.onClick = null;
              };

              return EditBoxImpl;
            }(EditBoxImplBase);

            var _dec$17, _dec2$J, _dec3$B, _dec4$v, _dec5$o, _dec6$i, _dec7$g, _dec8$f, _dec9$c, _dec10$b, _dec11$a, _dec12$a, _dec13$9, _dec14$9, _dec15$9, _dec16$9, _dec17$8, _dec18$8, _dec19$8, _dec20$7, _dec21$7, _dec22$7, _dec23$7, _dec24$7, _dec25$7, _dec26$6, _dec27$5, _dec28$5, _dec29$5, _dec30$5, _dec31$5, _dec32$4, _dec33$3, _dec34$3, _dec35$3, _dec36$3, _dec37$3, _dec38$3, _dec39$3, _dec40$3, _dec41$2, _dec42$2, _dec43$2, _class$18, _class2$10, _descriptor$R, _descriptor2$C, _descriptor3$q, _descriptor4$m, _descriptor5$i, _descriptor6$c, _descriptor7$a, _descriptor8$a, _descriptor9$9, _descriptor10$9, _descriptor11$8, _descriptor12$7, _descriptor13$6, _class3$q, _temp$13;
            var LEFT_PADDING$1 = 2;

            function capitalize(str) {
              return str.replace(/(?:^|\s)\S/g, function (a) {
                return a.toUpperCase();
              });
            }

            function capitalizeFirstLetter(str) {
              return str.charAt(0).toUpperCase() + str.slice(1);
            }

            var EventType$3;

            (function (EventType) {
              EventType["EDITING_DID_BEGAN"] = "editing-did-began";
              EventType["EDITING_DID_ENDED"] = "editing-did-ended";
              EventType["TEXT_CHANGED"] = "text-changed";
              EventType["EDITING_RETURN"] = "editing-return";
            })(EventType$3 || (EventType$3 = {}));

            var EditBox = function (v) { return exports({ EditBox: v, EditBoxComponent: v }), v; }((_dec$17 = ccclass('cc.EditBox'), _dec2$J = help(), _dec3$B = executionOrder(110), _dec4$v = menu(), _dec5$o = requireComponent(UITransform), _dec6$i = displayOrder(), _dec7$g = tooltip(), _dec8$f = displayOrder(), _dec9$c = tooltip(), _dec10$b = type(Label), _dec11$a = displayOrder(), _dec12$a = tooltip(), _dec13$9 = type(Label), _dec14$9 = displayOrder(), _dec15$9 = tooltip(), _dec16$9 = type(SpriteFrame), _dec17$8 = displayOrder(), _dec18$8 = tooltip(), _dec19$8 = type(InputFlag), _dec20$7 = displayOrder(), _dec21$7 = tooltip(), _dec22$7 = type(InputMode), _dec23$7 = displayOrder(), _dec24$7 = tooltip(), _dec25$7 = type(KeyboardReturnType), _dec26$6 = displayOrder(), _dec27$5 = tooltip(), _dec28$5 = displayOrder(), _dec29$5 = tooltip(), _dec30$5 = displayOrder(), _dec31$5 = tooltip(), _dec32$4 = type([EventHandler]), _dec33$3 = displayOrder(), _dec34$3 = tooltip(), _dec35$3 = type([EventHandler]), _dec36$3 = displayOrder(), _dec37$3 = tooltip(), _dec38$3 = type([EventHandler]), _dec39$3 = displayOrder(), _dec40$3 = tooltip(), _dec41$2 = type([EventHandler]), _dec42$2 = displayOrder(), _dec43$2 = tooltip(), _dec$17(_class$18 = _dec2$J(_class$18 = _dec3$B(_class$18 = _dec4$v(_class$18 = _dec5$o(_class$18 = executeInEditMode(_class$18 = (_class2$10 = (_temp$13 = _class3$q = function (_Component) {
              _inheritsLoose(EditBox, _Component);

              function EditBox() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Component.call.apply(_Component, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "editingDidBegan", _descriptor$R, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "textChanged", _descriptor2$C, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "editingDidEnded", _descriptor3$q, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "editingReturn", _descriptor4$m, _assertThisInitialized(_this));

                _this._impl = null;
                _this._background = null;

                _initializerDefineProperty(_this, "_textLabel", _descriptor5$i, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_placeholderLabel", _descriptor6$c, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_returnType", _descriptor7$a, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_string", _descriptor8$a, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_tabIndex", _descriptor9$9, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_backgroundImage", _descriptor10$9, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_inputFlag", _descriptor11$8, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_inputMode", _descriptor12$7, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_maxLength", _descriptor13$6, _assertThisInitialized(_this));

                _this._isLabelVisible = false;
                return _this;
              }

              var _proto = EditBox.prototype;

              _proto.__preload = function __preload() {
                this._init();
              };

              _proto.onEnable = function onEnable() {
                {
                  this._registerEvent();
                }

                if (this._impl) {
                  this._impl.onEnable();
                }
              };

              _proto.update = function update() {
                if (this._impl) {
                  this._impl.update();
                }
              };

              _proto.onDisable = function onDisable() {
                {
                  this._unregisterEvent();
                }

                if (this._impl) {
                  this._impl.onDisable();
                }
              };

              _proto.onDestroy = function onDestroy() {
                if (this._impl) {
                  this._impl.clear();
                }
              };

              _proto.setFocus = function setFocus() {
                if (this._impl) {
                  this._impl.setFocus(true);
                }
              };

              _proto.focus = function focus() {
                if (this._impl) {
                  this._impl.setFocus(true);
                }
              };

              _proto.blur = function blur() {
                if (this._impl) {
                  this._impl.setFocus(false);
                }
              };

              _proto.isFocused = function isFocused() {
                if (this._impl) {
                  return this._impl.isFocused();
                }

                return false;
              };

              _proto._editBoxEditingDidBegan = function _editBoxEditingDidBegan() {
                EventHandler.emitEvents(this.editingDidBegan, this);
                this.node.emit(EventType$3.EDITING_DID_BEGAN, this);
              };

              _proto._editBoxEditingDidEnded = function _editBoxEditingDidEnded() {
                EventHandler.emitEvents(this.editingDidEnded, this);
                this.node.emit(EventType$3.EDITING_DID_ENDED, this);
              };

              _proto._editBoxTextChanged = function _editBoxTextChanged(text) {
                text = this._updateLabelStringStyle(text, true);
                this.string = text;
                EventHandler.emitEvents(this.textChanged, text, this);
                this.node.emit(EventType$3.TEXT_CHANGED, this);
              };

              _proto._editBoxEditingReturn = function _editBoxEditingReturn() {
                EventHandler.emitEvents(this.editingReturn, this);
                this.node.emit(EventType$3.EDITING_RETURN, this);
              };

              _proto._showLabels = function _showLabels() {
                this._isLabelVisible = true;

                this._updateLabels();
              };

              _proto._hideLabels = function _hideLabels() {
                this._isLabelVisible = false;

                if (this._textLabel) {
                  this._textLabel.node.active = false;
                }

                if (this._placeholderLabel) {
                  this._placeholderLabel.node.active = false;
                }
              };

              _proto._onTouchBegan = function _onTouchBegan(event) {
                event.propagationStopped = true;
              };

              _proto._onTouchCancel = function _onTouchCancel(event) {
                event.propagationStopped = true;
              };

              _proto._onTouchEnded = function _onTouchEnded(event) {
                if (this._impl) {
                  this._impl.beginEditing();
                }

                event.propagationStopped = true;
              };

              _proto._init = function _init() {
                this._createBackgroundSprite();

                this._updatePlaceholderLabel();

                this._updateTextLabel();

                this._isLabelVisible = true;
                this.node.on(SystemEventType.SIZE_CHANGED, this._resizeChildNodes, this);
                var impl = this._impl = new EditBox._EditBoxImpl();
                impl.init(this);

                this._updateString(this._string);

                this._syncSize();
              };

              _proto._createBackgroundSprite = function _createBackgroundSprite() {
                if (!this._background) {
                  this._background = this.node.getComponent(Sprite);

                  if (!this._background) {
                    this._background = this.node.addComponent(Sprite);
                  }
                }

                this._background.type = Sprite.Type.SLICED;
                this._background.spriteFrame = this._backgroundImage;
              };

              _proto._updateTextLabel = function _updateTextLabel() {
                var textLabel = this._textLabel;

                if (!textLabel) {
                  var node = this.node.getChildByName('TEXT_LABEL');

                  if (!node) {
                    node = new Node$1('TEXT_LABEL');
                  }

                  textLabel = node.getComponent(Label);

                  if (!textLabel) {
                    textLabel = node.addComponent(Label);
                  }

                  node.parent = this.node;
                  this._textLabel = textLabel;
                }

                var transformComp = this._textLabel.node._uiProps.uiTransformComp;
                transformComp.setAnchorPoint(0, 1);
                textLabel.overflow = Label.Overflow.CLAMP;

                if (this._inputMode === InputMode.ANY) {
                  textLabel.verticalAlign = VerticalTextAlignment.TOP;
                  textLabel.enableWrapText = true;
                } else {
                  textLabel.enableWrapText = false;
                }

                textLabel.string = this._updateLabelStringStyle(this._string);
              };

              _proto._updatePlaceholderLabel = function _updatePlaceholderLabel() {
                var placeholderLabel = this._placeholderLabel;

                if (!placeholderLabel) {
                  var node = this.node.getChildByName('PLACEHOLDER_LABEL');

                  if (!node) {
                    node = new Node$1('PLACEHOLDER_LABEL');
                  }

                  placeholderLabel = node.getComponent(Label);

                  if (!placeholderLabel) {
                    placeholderLabel = node.addComponent(Label);
                  }

                  node.parent = this.node;
                  this._placeholderLabel = placeholderLabel;
                }

                var transform = this._placeholderLabel.node._uiProps.uiTransformComp;
                transform.setAnchorPoint(0, 1);
                placeholderLabel.overflow = Label.Overflow.CLAMP;

                if (this._inputMode === InputMode.ANY) {
                  placeholderLabel.verticalAlign = VerticalTextAlignment.TOP;
                  placeholderLabel.enableWrapText = true;
                } else {
                  placeholderLabel.enableWrapText = false;
                }

                placeholderLabel.string = this.placeholder;
              };

              _proto._syncSize = function _syncSize() {
                var trans = this.node._uiProps.uiTransformComp;
                var size = trans.contentSize;

                if (this._background) {
                  var bgTrans = this._background.node._uiProps.uiTransformComp;
                  bgTrans.anchorPoint = trans.anchorPoint;
                  bgTrans.setContentSize(size);
                }

                this._updateLabelPosition(size);

                if (this._impl) {
                  this._impl.setSize(size.width, size.height);
                }
              };

              _proto._updateLabels = function _updateLabels() {
                if (this._isLabelVisible) {
                  var content = this._string;

                  if (this._textLabel) {
                    this._textLabel.node.active = content !== '';
                  }

                  if (this._placeholderLabel) {
                    this._placeholderLabel.node.active = content === '';
                  }
                }
              };

              _proto._updateString = function _updateString(text) {
                var textLabel = this._textLabel;

                if (!textLabel) {
                  return;
                }

                var displayText = text;

                if (displayText) {
                  displayText = this._updateLabelStringStyle(displayText);
                }

                textLabel.string = displayText;

                this._updateLabels();
              };

              _proto._updateLabelStringStyle = function _updateLabelStringStyle(text, ignorePassword) {
                if (ignorePassword === void 0) {
                  ignorePassword = false;
                }

                var inputFlag = this._inputFlag;

                if (!ignorePassword && inputFlag === InputFlag.PASSWORD) {
                  var passwordString = '';
                  var len = text.length;

                  for (var i = 0; i < len; ++i) {
                    passwordString += "\u25CF";
                  }

                  text = passwordString;
                } else if (inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS) {
                  text = text.toUpperCase();
                } else if (inputFlag === InputFlag.INITIAL_CAPS_WORD) {
                  text = capitalize(text);
                } else if (inputFlag === InputFlag.INITIAL_CAPS_SENTENCE) {
                  text = capitalizeFirstLetter(text);
                }

                return text;
              };

              _proto._registerEvent = function _registerEvent() {
                this.node.on(SystemEventType.TOUCH_START, this._onTouchBegan, this);
                this.node.on(SystemEventType.TOUCH_END, this._onTouchEnded, this);
              };

              _proto._unregisterEvent = function _unregisterEvent() {
                this.node.off(SystemEventType.TOUCH_START, this._onTouchBegan, this);
                this.node.off(SystemEventType.TOUCH_END, this._onTouchEnded, this);
              };

              _proto._updateLabelPosition = function _updateLabelPosition(size) {
                var trans = this.node._uiProps.uiTransformComp;
                var offX = -trans.anchorX * trans.width;
                var offY = -trans.anchorY * trans.height;
                var placeholderLabel = this._placeholderLabel;
                var textLabel = this._textLabel;

                if (textLabel) {
                  textLabel.node._uiProps.uiTransformComp.setContentSize(size.width - LEFT_PADDING$1, size.height);

                  textLabel.node.setPosition(offX + LEFT_PADDING$1, offY + size.height, textLabel.node.position.z);

                  if (this._inputMode === InputMode.ANY) {
                    textLabel.verticalAlign = VerticalTextAlignment.TOP;
                  }

                  textLabel.enableWrapText = this._inputMode === InputMode.ANY;
                }

                if (placeholderLabel) {
                  placeholderLabel.node._uiProps.uiTransformComp.setContentSize(size.width - LEFT_PADDING$1, size.height);

                  placeholderLabel.lineHeight = size.height;
                  placeholderLabel.node.setPosition(offX + LEFT_PADDING$1, offY + size.height, placeholderLabel.node.position.z);

                  if (this._inputMode === InputMode.ANY) {
                    placeholderLabel.verticalAlign = VerticalTextAlignment.TOP;
                  }

                  placeholderLabel.enableWrapText = this._inputMode === InputMode.ANY;
                }
              };

              _proto._resizeChildNodes = function _resizeChildNodes() {
                var trans = this.node._uiProps.uiTransformComp;
                var textLabelNode = this._textLabel && this._textLabel.node;

                if (textLabelNode) {
                  textLabelNode.setPosition(-trans.width / 2, trans.height / 2, textLabelNode.position.z);

                  textLabelNode._uiProps.uiTransformComp.setContentSize(trans.contentSize);
                }

                var placeholderLabelNode = this._placeholderLabel && this._placeholderLabel.node;

                if (placeholderLabelNode) {
                  placeholderLabelNode.setPosition(-trans.width / 2, trans.height / 2, placeholderLabelNode.position.z);

                  placeholderLabelNode._uiProps.uiTransformComp.setContentSize(trans.contentSize);
                }

                var backgroundNode = this._background && this._background.node;

                if (backgroundNode) {
                  backgroundNode._uiProps.uiTransformComp.setContentSize(trans.contentSize);
                }
              };

              _createClass(EditBox, [{
                key: "string",
                get: function get() {
                  return this._string;
                },
                set: function set(value) {
                  if (this._maxLength >= 0 && value.length >= this._maxLength) {
                    value = value.slice(0, this._maxLength);
                  }

                  this._string = value;

                  this._updateString(value);
                }
              }, {
                key: "placeholder",
                get: function get() {
                  if (!this._placeholderLabel) {
                    return '';
                  }

                  return this._placeholderLabel.string;
                },
                set: function set(value) {
                  if (this._placeholderLabel) {
                    this._placeholderLabel.string = value;
                  }
                }
              }, {
                key: "textLabel",
                get: function get() {
                  return this._textLabel;
                },
                set: function set(oldValue) {
                  if (this._textLabel !== oldValue) {
                    this._textLabel = oldValue;

                    if (this._textLabel) {
                      this._updateTextLabel();

                      this._updateLabels();
                    }
                  }
                }
              }, {
                key: "placeholderLabel",
                get: function get() {
                  return this._placeholderLabel;
                },
                set: function set(oldValue) {
                  if (this._placeholderLabel !== oldValue) {
                    this._placeholderLabel = oldValue;

                    if (this._placeholderLabel) {
                      this._updatePlaceholderLabel();

                      this._updateLabels();
                    }
                  }
                }
              }, {
                key: "backgroundImage",
                get: function get() {
                  return this._backgroundImage;
                },
                set: function set(value) {
                  if (this._backgroundImage === value) {
                    return;
                  }

                  this._backgroundImage = value;

                  this._createBackgroundSprite();
                }
              }, {
                key: "inputFlag",
                get: function get() {
                  return this._inputFlag;
                },
                set: function set(value) {
                  this._inputFlag = value;

                  this._updateString(this._string);
                }
              }, {
                key: "inputMode",
                get: function get() {
                  return this._inputMode;
                },
                set: function set(oldValue) {
                  if (this._inputMode !== oldValue) {
                    this._inputMode = oldValue;

                    this._updateTextLabel();

                    this._updatePlaceholderLabel();
                  }
                }
              }, {
                key: "returnType",
                get: function get() {
                  return this._returnType;
                },
                set: function set(value) {
                  this._returnType = value;
                }
              }, {
                key: "maxLength",
                get: function get() {
                  return this._maxLength;
                },
                set: function set(value) {
                  this._maxLength = value;
                }
              }, {
                key: "tabIndex",
                get: function get() {
                  return this._tabIndex;
                },
                set: function set(value) {
                  if (this._tabIndex !== value) {
                    this._tabIndex = value;

                    if (this._impl) {
                      this._impl.setTabIndex(value);
                    }
                  }
                }
              }]);

              return EditBox;
            }(Component), _class3$q._EditBoxImpl = EditBoxImplBase, _class3$q.KeyboardReturnType = KeyboardReturnType, _class3$q.InputFlag = InputFlag, _class3$q.InputMode = InputMode, _class3$q.EventType = EventType$3, _temp$13), (_applyDecoratedDescriptor(_class2$10.prototype, "string", [_dec6$i, _dec7$g], Object.getOwnPropertyDescriptor(_class2$10.prototype, "string"), _class2$10.prototype), _applyDecoratedDescriptor(_class2$10.prototype, "placeholder", [_dec8$f, _dec9$c], Object.getOwnPropertyDescriptor(_class2$10.prototype, "placeholder"), _class2$10.prototype), _applyDecoratedDescriptor(_class2$10.prototype, "textLabel", [_dec10$b, _dec11$a, _dec12$a], Object.getOwnPropertyDescriptor(_class2$10.prototype, "textLabel"), _class2$10.prototype), _applyDecoratedDescriptor(_class2$10.prototype, "placeholderLabel", [_dec13$9, _dec14$9, _dec15$9], Object.getOwnPropertyDescriptor(_class2$10.prototype, "placeholderLabel"), _class2$10.prototype), _applyDecoratedDescriptor(_class2$10.prototype, "backgroundImage", [_dec16$9, _dec17$8, _dec18$8], Object.getOwnPropertyDescriptor(_class2$10.prototype, "backgroundImage"), _class2$10.prototype), _applyDecoratedDescriptor(_class2$10.prototype, "inputFlag", [_dec19$8, _dec20$7, _dec21$7], Object.getOwnPropertyDescriptor(_class2$10.prototype, "inputFlag"), _class2$10.prototype), _applyDecoratedDescriptor(_class2$10.prototype, "inputMode", [_dec22$7, _dec23$7, _dec24$7], Object.getOwnPropertyDescriptor(_class2$10.prototype, "inputMode"), _class2$10.prototype), _applyDecoratedDescriptor(_class2$10.prototype, "returnType", [_dec25$7, _dec26$6, _dec27$5], Object.getOwnPropertyDescriptor(_class2$10.prototype, "returnType"), _class2$10.prototype), _applyDecoratedDescriptor(_class2$10.prototype, "maxLength", [_dec28$5, _dec29$5], Object.getOwnPropertyDescriptor(_class2$10.prototype, "maxLength"), _class2$10.prototype), _applyDecoratedDescriptor(_class2$10.prototype, "tabIndex", [_dec30$5, _dec31$5], Object.getOwnPropertyDescriptor(_class2$10.prototype, "tabIndex"), _class2$10.prototype), _descriptor$R = _applyDecoratedDescriptor(_class2$10.prototype, "editingDidBegan", [_dec32$4, serializable, _dec33$3, _dec34$3], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor2$C = _applyDecoratedDescriptor(_class2$10.prototype, "textChanged", [_dec35$3, serializable, _dec36$3, _dec37$3], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor3$q = _applyDecoratedDescriptor(_class2$10.prototype, "editingDidEnded", [_dec38$3, serializable, _dec39$3, _dec40$3], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor4$m = _applyDecoratedDescriptor(_class2$10.prototype, "editingReturn", [_dec41$2, serializable, _dec42$2, _dec43$2], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor5$i = _applyDecoratedDescriptor(_class2$10.prototype, "_textLabel", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor6$c = _applyDecoratedDescriptor(_class2$10.prototype, "_placeholderLabel", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor7$a = _applyDecoratedDescriptor(_class2$10.prototype, "_returnType", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return KeyboardReturnType.DEFAULT;
              }
            }), _descriptor8$a = _applyDecoratedDescriptor(_class2$10.prototype, "_string", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return '';
              }
            }), _descriptor9$9 = _applyDecoratedDescriptor(_class2$10.prototype, "_tabIndex", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor10$9 = _applyDecoratedDescriptor(_class2$10.prototype, "_backgroundImage", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor11$8 = _applyDecoratedDescriptor(_class2$10.prototype, "_inputFlag", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return InputFlag.DEFAULT;
              }
            }), _descriptor12$7 = _applyDecoratedDescriptor(_class2$10.prototype, "_inputMode", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return InputMode.ANY;
              }
            }), _descriptor13$6 = _applyDecoratedDescriptor(_class2$10.prototype, "_maxLength", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 20;
              }
            })), _class2$10)) || _class$18) || _class$18) || _class$18) || _class$18) || _class$18) || _class$18));

            if (typeof window === 'object' && typeof document === 'object' && !MINIGAME && !JSB && !RUNTIME_BASED) {
              EditBox._EditBoxImpl = EditBoxImpl;
            }

            var _dec$18, _dec2$K, _dec3$C, _dec4$w, _dec5$p, _dec6$j, _dec7$h, _dec8$g, _dec9$d, _dec10$c, _dec11$b, _dec12$b, _dec13$a, _dec14$a, _dec15$a, _dec16$a, _dec17$9, _dec18$9, _dec19$9, _dec20$8, _dec21$8, _dec22$8, _dec23$8, _dec24$8, _dec25$8, _dec26$7, _dec27$6, _dec28$6, _dec29$6, _dec30$6, _dec31$6, _dec32$5, _dec33$4, _dec34$4, _class$19, _class2$11, _descriptor$S, _descriptor2$D, _descriptor3$r, _descriptor4$n, _descriptor5$j, _descriptor6$d, _descriptor7$b, _descriptor8$b, _descriptor9$a, _descriptor10$a, _descriptor11$9, _descriptor12$8, _descriptor13$7, _descriptor14$6, _descriptor15$5, _descriptor16$5, _class3$r, _temp$14;
            var NodeEvent = SystemEventType;
            var Type$1;

            (function (Type) {
              Type[Type["NONE"] = 0] = "NONE";
              Type[Type["HORIZONTAL"] = 1] = "HORIZONTAL";
              Type[Type["VERTICAL"] = 2] = "VERTICAL";
              Type[Type["GRID"] = 3] = "GRID";
            })(Type$1 || (Type$1 = {}));

            ccenum(Type$1);
            var ResizeMode;

            (function (ResizeMode) {
              ResizeMode[ResizeMode["NONE"] = 0] = "NONE";
              ResizeMode[ResizeMode["CONTAINER"] = 1] = "CONTAINER";
              ResizeMode[ResizeMode["CHILDREN"] = 2] = "CHILDREN";
            })(ResizeMode || (ResizeMode = {}));

            ccenum(ResizeMode);
            var AxisDirection;

            (function (AxisDirection) {
              AxisDirection[AxisDirection["HORIZONTAL"] = 0] = "HORIZONTAL";
              AxisDirection[AxisDirection["VERTICAL"] = 1] = "VERTICAL";
            })(AxisDirection || (AxisDirection = {}));

            ccenum(AxisDirection);
            var VerticalDirection;

            (function (VerticalDirection) {
              VerticalDirection[VerticalDirection["BOTTOM_TO_TOP"] = 0] = "BOTTOM_TO_TOP";
              VerticalDirection[VerticalDirection["TOP_TO_BOTTOM"] = 1] = "TOP_TO_BOTTOM";
            })(VerticalDirection || (VerticalDirection = {}));

            ccenum(VerticalDirection);
            var HorizontalDirection;

            (function (HorizontalDirection) {
              HorizontalDirection[HorizontalDirection["LEFT_TO_RIGHT"] = 0] = "LEFT_TO_RIGHT";
              HorizontalDirection[HorizontalDirection["RIGHT_TO_LEFT"] = 1] = "RIGHT_TO_LEFT";
            })(HorizontalDirection || (HorizontalDirection = {}));

            ccenum(HorizontalDirection);
            var Constraint;

            (function (Constraint) {
              Constraint[Constraint["NONE"] = 0] = "NONE";
              Constraint[Constraint["FIXED_ROW"] = 1] = "FIXED_ROW";
              Constraint[Constraint["FIXED_COL"] = 2] = "FIXED_COL";
            })(Constraint || (Constraint = {}));

            ccenum(Constraint);

            var _tempVec3$1 = new Vec3();

            var Layout = function (v) { return exports({ Layout: v, LayoutComponent: v }), v; }((_dec$18 = ccclass('cc.Layout'), _dec2$K = help(), _dec3$C = executionOrder(110), _dec4$w = menu(), _dec5$p = requireComponent(UITransform), _dec6$j = visible(), _dec7$h = tooltip(), _dec8$g = visible(), _dec9$d = tooltip(), _dec10$c = type(Type$1), _dec11$b = tooltip(), _dec12$b = type(ResizeMode), _dec13$a = visible(), _dec14$a = tooltip(), _dec15$a = visible(), _dec16$a = tooltip(), _dec17$9 = type(AxisDirection), _dec18$9 = tooltip(), _dec19$9 = tooltip(), _dec20$8 = tooltip(), _dec21$8 = tooltip(), _dec22$8 = tooltip(), _dec23$8 = tooltip(), _dec24$8 = tooltip(), _dec25$8 = type(VerticalDirection), _dec26$7 = tooltip(), _dec27$6 = type(HorizontalDirection), _dec28$6 = tooltip(), _dec29$6 = type(Constraint), _dec30$6 = visible(), _dec31$6 = tooltip(), _dec32$5 = visible(), _dec33$4 = tooltip(), _dec34$4 = tooltip(), _dec$18(_class$19 = _dec2$K(_class$19 = _dec3$C(_class$19 = _dec4$w(_class$19 = _dec5$p(_class$19 = executeInEditMode(_class$19 = (_class2$11 = (_temp$14 = _class3$r = function (_Component) {
              _inheritsLoose(Layout, _Component);

              function Layout() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Component.call.apply(_Component, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "_resizeMode", _descriptor$S, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_layoutType", _descriptor2$D, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_cellSize", _descriptor3$r, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_startAxis", _descriptor4$n, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_paddingLeft", _descriptor5$j, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_paddingRight", _descriptor6$d, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_paddingTop", _descriptor7$b, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_paddingBottom", _descriptor8$b, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_spacingX", _descriptor9$a, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_spacingY", _descriptor10$a, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_verticalDirection", _descriptor11$9, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_horizontalDirection", _descriptor12$8, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_constraint", _descriptor13$7, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_constraintNum", _descriptor14$6, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_affectedByScale", _descriptor15$5, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_isAlign", _descriptor16$5, _assertThisInitialized(_this));

                _this._layoutSize = new Size(300, 200);
                _this._layoutDirty = true;
                _this._childrenDirty = false;
                _this._usefulLayoutObj = [];
                _this._init = false;
                return _this;
              }

              var _proto = Layout.prototype;

              _proto.updateLayout = function updateLayout(force) {
                if (force === void 0) {
                  force = false;
                }

                if ((this._layoutDirty || force) && this.node.children.length > 0) {
                  this._doLayout();

                  this._layoutDirty = false;
                }
              };

              _proto.onEnable = function onEnable() {
                this._addEventListeners();

                var trans = this.node._uiProps.uiTransformComp;

                if (trans.contentSize.equals(Size.ZERO)) {
                  trans.setContentSize(this._layoutSize);
                }

                this._childrenChanged();
              };

              _proto.onDisable = function onDisable() {
                this._usefulLayoutObj.length = 0;

                this._removeEventListeners();
              };

              _proto._checkUsefulObj = function _checkUsefulObj() {
                this._usefulLayoutObj.length = 0;
                var children = this.node.children;

                for (var i = 0; i < children.length; ++i) {
                  var child = children[i];
                  var uiTrans = child._uiProps.uiTransformComp;

                  if (child.activeInHierarchy && uiTrans) {
                    this._usefulLayoutObj.push(uiTrans);
                  }
                }
              };

              _proto._addEventListeners = function _addEventListeners() {
                director.on(Director.EVENT_AFTER_UPDATE, this.updateLayout, this);
                this.node.on(NodeEvent.SIZE_CHANGED, this._resized, this);
                this.node.on(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this);
                this.node.on(NodeEvent.CHILD_ADDED, this._childAdded, this);
                this.node.on(NodeEvent.CHILD_REMOVED, this._childRemoved, this);
                this.node.on(NodeEvent.SIBLING_ORDER_CHANGED, this._childrenChanged, this);
                this.node.on('childrenSiblingOrderChanged', this.updateLayout, this);

                this._addChildrenEventListeners();
              };

              _proto._removeEventListeners = function _removeEventListeners() {
                director.off(Director.EVENT_AFTER_UPDATE, this.updateLayout, this);
                this.node.off(NodeEvent.SIZE_CHANGED, this._resized, this);
                this.node.off(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this);
                this.node.off(NodeEvent.CHILD_ADDED, this._childAdded, this);
                this.node.off(NodeEvent.CHILD_REMOVED, this._childRemoved, this);
                this.node.off(NodeEvent.SIBLING_ORDER_CHANGED, this._childrenChanged, this);
                this.node.off('childrenSiblingOrderChanged', this.updateLayout, this);

                this._removeChildrenEventListeners();
              };

              _proto._addChildrenEventListeners = function _addChildrenEventListeners() {
                var children = this.node.children;

                for (var i = 0; i < children.length; ++i) {
                  var child = children[i];
                  child.on(NodeEvent.SIZE_CHANGED, this._doLayoutDirty, this);
                  child.on(NodeEvent.TRANSFORM_CHANGED, this._transformDirty, this);
                  child.on(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this);
                  child.on('active-in-hierarchy-changed', this._childrenChanged, this);
                }
              };

              _proto._removeChildrenEventListeners = function _removeChildrenEventListeners() {
                var children = this.node.children;

                for (var i = 0; i < children.length; ++i) {
                  var child = children[i];
                  child.off(NodeEvent.SIZE_CHANGED, this._doLayoutDirty, this);
                  child.off(NodeEvent.TRANSFORM_CHANGED, this._transformDirty, this);
                  child.off(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this);
                  child.off('active-in-hierarchy-changed', this._childrenChanged, this);
                }
              };

              _proto._childAdded = function _childAdded(child) {
                child.on(NodeEvent.SIZE_CHANGED, this._doLayoutDirty, this);
                child.on(NodeEvent.TRANSFORM_CHANGED, this._transformDirty, this);
                child.on(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this);
                child.on('active-in-hierarchy-changed', this._childrenChanged, this);

                this._childrenChanged();
              };

              _proto._childRemoved = function _childRemoved(child) {
                child.off(NodeEvent.SIZE_CHANGED, this._doLayoutDirty, this);
                child.off(NodeEvent.TRANSFORM_CHANGED, this._transformDirty, this);
                child.off(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this);
                child.off('active-in-hierarchy-changed', this._childrenChanged, this);

                this._childrenChanged();
              };

              _proto._resized = function _resized() {
                this._layoutSize.set(this.node._uiProps.uiTransformComp.contentSize);

                this._doLayoutDirty();
              };

              _proto._doLayoutHorizontally = function _doLayoutHorizontally(baseWidth, rowBreak, fnPositionY, applyChildren) {
                var trans = this.node._uiProps.uiTransformComp;
                var layoutAnchor = trans.anchorPoint;

                var limit = this._getFixedBreakingNum();

                var sign = 1;
                var paddingX = this._paddingLeft;

                if (this._horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) {
                  sign = -1;
                  paddingX = this._paddingRight;
                }

                var startPos = (this._horizontalDirection - layoutAnchor.x) * baseWidth + sign * paddingX;
                var nextX = startPos - sign * this._spacingX;
                var totalHeight = 0;
                var rowMaxHeight = 0;
                var tempMaxHeight = 0;
                var maxHeight = 0;
                var isBreak = false;
                var activeChildCount = this._usefulLayoutObj.length;
                var newChildWidth = this._cellSize.width;

                var paddingH = this._getPaddingH();

                if (this._layoutType !== Type$1.GRID && this._resizeMode === ResizeMode.CHILDREN) {
                  newChildWidth = (baseWidth - paddingH - (activeChildCount - 1) * this._spacingX) / activeChildCount;
                }

                var children = this._usefulLayoutObj;

                for (var i = 0; i < children.length; ++i) {
                  var childTrans = children[i];
                  var child = childTrans.node;
                  var scale = child.scale;

                  var childScaleX = this._getUsedScaleValue(scale.x);

                  var childScaleY = this._getUsedScaleValue(scale.y);

                  if (this._resizeMode === ResizeMode.CHILDREN) {
                    childTrans.width = newChildWidth / childScaleX;

                    if (this._layoutType === Type$1.GRID) {
                      childTrans.height = this._cellSize.height / childScaleY;
                    }
                  }

                  var anchorX = Math.abs(this._horizontalDirection - childTrans.anchorX);
                  var childBoundingBoxWidth = childTrans.width * childScaleX;
                  var childBoundingBoxHeight = childTrans.height * childScaleY;

                  if (childBoundingBoxHeight > tempMaxHeight) {
                    maxHeight = Math.max(tempMaxHeight, maxHeight);
                    rowMaxHeight = tempMaxHeight || childBoundingBoxHeight;
                    tempMaxHeight = childBoundingBoxHeight;
                  }

                  nextX += sign * (anchorX * childBoundingBoxWidth + this._spacingX);
                  var rightBoundaryOfChild = sign * (1 - anchorX) * childBoundingBoxWidth;

                  if (rowBreak) {
                    if (limit > 0) {
                      isBreak = i / limit > 0 && i % limit === 0;

                      if (isBreak) {
                        rowMaxHeight = tempMaxHeight > childBoundingBoxHeight ? tempMaxHeight : rowMaxHeight;
                      }
                    } else if (childBoundingBoxWidth > baseWidth - paddingH) {
                      if (nextX > startPos + sign * (anchorX * childBoundingBoxWidth)) {
                        isBreak = true;
                      }
                    } else {
                      var boundary = (1 - this._horizontalDirection - layoutAnchor.x) * baseWidth;
                      var rowBreakBoundary = nextX + rightBoundaryOfChild + sign * (sign > 0 ? this._paddingRight : this._paddingLeft);
                      isBreak = Math.abs(rowBreakBoundary) > Math.abs(boundary);
                    }

                    if (isBreak) {
                      nextX = startPos + sign * (anchorX * childBoundingBoxWidth);

                      if (childBoundingBoxHeight !== tempMaxHeight) {
                        rowMaxHeight = tempMaxHeight;
                      }

                      totalHeight += rowMaxHeight + this._spacingY;
                      rowMaxHeight = tempMaxHeight = childBoundingBoxHeight;
                    }
                  }

                  var finalPositionY = fnPositionY(child, childTrans, totalHeight);

                  if (applyChildren) {
                    child.setPosition(nextX, finalPositionY);
                  }

                  nextX += rightBoundaryOfChild;
                }

                rowMaxHeight = Math.max(rowMaxHeight, tempMaxHeight);

                var containerResizeBoundary = Math.max(maxHeight, totalHeight + rowMaxHeight) + this._getPaddingV();

                return containerResizeBoundary;
              };

              _proto._doLayoutVertically = function _doLayoutVertically(baseHeight, columnBreak, fnPositionX, applyChildren) {
                var trans = this.node._uiProps.uiTransformComp;
                var layoutAnchor = trans.anchorPoint;

                var limit = this._getFixedBreakingNum();

                var sign = 1;
                var paddingY = this._paddingBottom;

                if (this._verticalDirection === VerticalDirection.TOP_TO_BOTTOM) {
                  sign = -1;
                  paddingY = this._paddingTop;
                }

                var startPos = (this._verticalDirection - layoutAnchor.y) * baseHeight + sign * paddingY;
                var nextY = startPos - sign * this._spacingY;
                var tempMaxWidth = 0;
                var maxWidth = 0;
                var colMaxWidth = 0;
                var totalWidth = 0;
                var isBreak = false;
                var activeChildCount = this._usefulLayoutObj.length;
                var newChildHeight = this._cellSize.height;

                var paddingV = this._getPaddingV();

                if (this._layoutType !== Type$1.GRID && this._resizeMode === ResizeMode.CHILDREN) {
                  newChildHeight = (baseHeight - paddingV - (activeChildCount - 1) * this._spacingY) / activeChildCount;
                }

                var children = this._usefulLayoutObj;

                for (var i = 0; i < children.length; ++i) {
                  var childTrans = children[i];
                  var child = childTrans.node;
                  var scale = child.scale;

                  var childScaleX = this._getUsedScaleValue(scale.x);

                  var childScaleY = this._getUsedScaleValue(scale.y);

                  if (this._resizeMode === ResizeMode.CHILDREN) {
                    childTrans.height = newChildHeight / childScaleY;

                    if (this._layoutType === Type$1.GRID) {
                      childTrans.width = this._cellSize.width / childScaleX;
                    }
                  }

                  var anchorY = Math.abs(this._verticalDirection - childTrans.anchorY);
                  var childBoundingBoxWidth = childTrans.width * childScaleX;
                  var childBoundingBoxHeight = childTrans.height * childScaleY;

                  if (childBoundingBoxWidth > tempMaxWidth) {
                    maxWidth = Math.max(tempMaxWidth, maxWidth);
                    colMaxWidth = tempMaxWidth || childBoundingBoxWidth;
                    tempMaxWidth = childBoundingBoxWidth;
                  }

                  nextY += sign * (anchorY * childBoundingBoxHeight + this._spacingY);
                  var topBoundaryOfChild = sign * (1 - anchorY) * childBoundingBoxHeight;

                  if (columnBreak) {
                    if (limit > 0) {
                      isBreak = i / limit > 0 && i % limit === 0;

                      if (isBreak) {
                        colMaxWidth = tempMaxWidth > childBoundingBoxHeight ? tempMaxWidth : colMaxWidth;
                      }
                    } else if (childBoundingBoxHeight > baseHeight - paddingV) {
                      if (nextY > startPos + sign * (anchorY * childBoundingBoxHeight)) {
                        isBreak = true;
                      }
                    } else {
                      var boundary = (1 - this._verticalDirection - layoutAnchor.y) * baseHeight;
                      var columnBreakBoundary = nextY + topBoundaryOfChild + sign * (sign > 0 ? this._paddingTop : this._paddingBottom);
                      isBreak = Math.abs(columnBreakBoundary) > Math.abs(boundary);
                    }

                    if (isBreak) {
                      nextY = startPos + sign * (anchorY * childBoundingBoxHeight);

                      if (childBoundingBoxWidth !== tempMaxWidth) {
                        colMaxWidth = tempMaxWidth;
                      }

                      totalWidth += colMaxWidth + this._spacingX;
                      colMaxWidth = tempMaxWidth = childBoundingBoxWidth;
                    }
                  }

                  var finalPositionX = fnPositionX(child, childTrans, totalWidth);

                  if (applyChildren) {
                    child.getPosition(_tempVec3$1);
                    child.setPosition(finalPositionX, nextY, _tempVec3$1.z);
                  }

                  nextY += topBoundaryOfChild;
                }

                colMaxWidth = Math.max(colMaxWidth, tempMaxWidth);

                var containerResizeBoundary = Math.max(maxWidth, totalWidth + colMaxWidth) + this._getPaddingH();

                return containerResizeBoundary;
              };

              _proto._doLayoutGridAxisHorizontal = function _doLayoutGridAxisHorizontal(layoutAnchor, layoutSize) {
                var _this2 = this;

                var baseWidth = layoutSize.width;
                var sign = 1;
                var bottomBoundaryOfLayout = -layoutAnchor.y * layoutSize.height;
                var paddingY = this._paddingBottom;

                if (this._verticalDirection === VerticalDirection.TOP_TO_BOTTOM) {
                  sign = -1;
                  bottomBoundaryOfLayout = (1 - layoutAnchor.y) * layoutSize.height;
                  paddingY = this._paddingTop;
                }

                var fnPositionY = function fnPositionY(child, childTrans, topOffset) {
                  return bottomBoundaryOfLayout + sign * (topOffset + (1 - childTrans.anchorY) * childTrans.height * _this2._getUsedScaleValue(child.scale.y) + paddingY);
                };

                var newHeight = 0;

                if (this._resizeMode === ResizeMode.CONTAINER) {
                  newHeight = this._doLayoutHorizontally(baseWidth, true, fnPositionY, false);
                  bottomBoundaryOfLayout = -layoutAnchor.y * newHeight;

                  if (this._verticalDirection === VerticalDirection.TOP_TO_BOTTOM) {
                    sign = -1;
                    bottomBoundaryOfLayout = (1 - layoutAnchor.y) * newHeight;
                  }
                }

                this._doLayoutHorizontally(baseWidth, true, fnPositionY, true);

                if (this._resizeMode === ResizeMode.CONTAINER) {
                  this.node._uiProps.uiTransformComp.setContentSize(baseWidth, newHeight);
                }
              };

              _proto._doLayoutGridAxisVertical = function _doLayoutGridAxisVertical(layoutAnchor, layoutSize) {
                var _this3 = this;

                var baseHeight = layoutSize.height;
                var sign = 1;
                var leftBoundaryOfLayout = -layoutAnchor.x * layoutSize.width;
                var paddingX = this._paddingLeft;

                if (this._horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) {
                  sign = -1;
                  leftBoundaryOfLayout = (1 - layoutAnchor.x) * layoutSize.width;
                  paddingX = this._paddingRight;
                }

                var fnPositionX = function fnPositionX(child, childTrans, leftOffset) {
                  return leftBoundaryOfLayout + sign * (leftOffset + (1 - childTrans.anchorX) * childTrans.width * _this3._getUsedScaleValue(child.scale.x) + paddingX);
                };

                var newWidth = 0;

                if (this._resizeMode === ResizeMode.CONTAINER) {
                  newWidth = this._doLayoutVertically(baseHeight, true, fnPositionX, false);
                  leftBoundaryOfLayout = -layoutAnchor.x * newWidth;

                  if (this._horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) {
                    sign = -1;
                    leftBoundaryOfLayout = (1 - layoutAnchor.x) * newWidth;
                  }
                }

                this._doLayoutVertically(baseHeight, true, fnPositionX, true);

                if (this._resizeMode === ResizeMode.CONTAINER) {
                  this.node._uiProps.uiTransformComp.setContentSize(newWidth, baseHeight);
                }
              };

              _proto._doLayoutGrid = function _doLayoutGrid() {
                var trans = this.node._uiProps.uiTransformComp;
                var layoutAnchor = trans.anchorPoint;
                var layoutSize = trans.contentSize;

                if (this.startAxis === AxisDirection.HORIZONTAL) {
                  this._doLayoutGridAxisHorizontal(layoutAnchor, layoutSize);
                } else if (this.startAxis === AxisDirection.VERTICAL) {
                  this._doLayoutGridAxisVertical(layoutAnchor, layoutSize);
                }
              };

              _proto._getHorizontalBaseWidth = function _getHorizontalBaseWidth(horizontal) {

                var children = this._usefulLayoutObj;
                var baseSize = 0;
                var activeChildCount = children.length;

                if (this._resizeMode === ResizeMode.CONTAINER) {
                  for (var i = 0; i < children.length; ++i) {
                    var childTrans = children[i];
                    var child = childTrans.node;
                    var scale = child.scale;
                    baseSize += childTrans.width * this._getUsedScaleValue(scale.x);
                  }

                  baseSize += (activeChildCount - 1) * this._spacingX + this._getPaddingH();
                } else {
                  baseSize = this.node._uiProps.uiTransformComp.width;
                }

                return baseSize;
              };

              _proto._getVerticalBaseHeight = function _getVerticalBaseHeight() {
                var children = this._usefulLayoutObj;
                var baseSize = 0;
                var activeChildCount = children.length;

                if (this._resizeMode === ResizeMode.CONTAINER) {
                  for (var i = 0; i < children.length; ++i) {
                    var childTrans = children[i];
                    var child = childTrans.node;
                    var scale = child.scale;
                    baseSize += childTrans.height * this._getUsedScaleValue(scale.y);
                  }

                  baseSize += (activeChildCount - 1) * this._spacingY + this._getPaddingV();
                } else {
                  baseSize = this.node._uiProps.uiTransformComp.height;
                }

                return baseSize;
              };

              _proto._doLayout = function _doLayout() {
                var _this4 = this;

                if (!this._init || this._childrenDirty) {
                  this._checkUsefulObj();

                  this._init = true;
                  this._childrenDirty = false;
                }

                if (this._layoutType === Type$1.HORIZONTAL) {
                  var newWidth = this._getHorizontalBaseWidth();

                  var fnPositionY = function fnPositionY(child) {
                    var pos = _this4._isAlign ? Vec3.ZERO : child.position;
                    return pos.y;
                  };

                  this._doLayoutHorizontally(newWidth, false, fnPositionY, true);

                  this.node._uiProps.uiTransformComp.width = newWidth;
                } else if (this._layoutType === Type$1.VERTICAL) {
                  var newHeight = this._getVerticalBaseHeight();

                  var fnPositionX = function fnPositionX(child) {
                    var pos = _this4._isAlign ? Vec3.ZERO : child.position;
                    return pos.x;
                  };

                  this._doLayoutVertically(newHeight, false, fnPositionX, true);

                  this.node._uiProps.uiTransformComp.height = newHeight;
                } else if (this._layoutType === Type$1.GRID) {
                  this._doLayoutGrid();
                }
              };

              _proto._getUsedScaleValue = function _getUsedScaleValue(value) {
                return this._affectedByScale ? Math.abs(value) : 1;
              };

              _proto._transformDirty = function _transformDirty(type) {
                if (!(type & TransformBit.SCALE) || !(type & TransformBit.POSITION) || !this._affectedByScale) {
                  return;
                }

                this._doLayoutDirty();
              };

              _proto._doLayoutDirty = function _doLayoutDirty() {
                this._layoutDirty = true;
              };

              _proto._childrenChanged = function _childrenChanged() {
                this._childrenDirty = true;

                this._doLayoutDirty();
              };

              _proto._getPaddingH = function _getPaddingH() {
                return this._paddingLeft + this._paddingRight;
              };

              _proto._getPaddingV = function _getPaddingV() {
                return this._paddingTop + this._paddingBottom;
              };

              _proto._getFixedBreakingNum = function _getFixedBreakingNum() {
                if (this._layoutType !== Type$1.GRID || this._constraint === Constraint.NONE || this._constraintNum <= 0) {
                  return 0;
                }

                var num = this._constraint === Constraint.FIXED_ROW ? Math.ceil(this._usefulLayoutObj.length / this._constraintNum) : this._constraintNum;

                if (this._startAxis === AxisDirection.VERTICAL) {
                  num = this._constraint === Constraint.FIXED_COL ? Math.ceil(this._usefulLayoutObj.length / this._constraintNum) : this._constraintNum;
                }

                return num;
              };

              _createClass(Layout, [{
                key: "alignHorizontal",
                get: function get() {
                  return this._isAlign;
                },
                set: function set(value) {
                  if (this._layoutType !== Type$1.HORIZONTAL) {
                    return;
                  }

                  this._isAlign = value;

                  this._doLayoutDirty();
                }
              }, {
                key: "alignVertical",
                get: function get() {
                  return this._isAlign;
                },
                set: function set(value) {
                  if (this._layoutType !== Type$1.VERTICAL) {
                    return;
                  }

                  this._isAlign = value;

                  this._doLayoutDirty();
                }
              }, {
                key: "type",
                get: function get() {
                  return this._layoutType;
                },
                set: function set(value) {
                  this._layoutType = value;

                  this._doLayoutDirty();
                }
              }, {
                key: "resizeMode",
                get: function get() {
                  return this._resizeMode;
                },
                set: function set(value) {
                  if (this._layoutType === Type$1.NONE) {
                    return;
                  }

                  this._resizeMode = value;

                  this._doLayoutDirty();
                }
              }, {
                key: "cellSize",
                get: function get() {
                  return this._cellSize;
                },
                set: function set(value) {
                  if (this._cellSize === value) {
                    return;
                  }

                  this._cellSize.set(value);

                  this._doLayoutDirty();
                }
              }, {
                key: "startAxis",
                get: function get() {
                  return this._startAxis;
                },
                set: function set(value) {
                  if (this._startAxis === value) {
                    return;
                  }

                  this._startAxis = value;

                  this._doLayoutDirty();
                }
              }, {
                key: "paddingLeft",
                get: function get() {
                  return this._paddingLeft;
                },
                set: function set(value) {
                  if (this._paddingLeft === value) {
                    return;
                  }

                  this._paddingLeft = value;

                  this._doLayoutDirty();
                }
              }, {
                key: "paddingRight",
                get: function get() {
                  return this._paddingRight;
                },
                set: function set(value) {
                  if (this._paddingRight === value) {
                    return;
                  }

                  this._paddingRight = value;

                  this._doLayoutDirty();
                }
              }, {
                key: "paddingTop",
                get: function get() {
                  return this._paddingTop;
                },
                set: function set(value) {
                  if (this._paddingTop === value) {
                    return;
                  }

                  this._paddingTop = value;

                  this._doLayoutDirty();
                }
              }, {
                key: "paddingBottom",
                get: function get() {
                  return this._paddingBottom;
                },
                set: function set(value) {
                  if (this._paddingBottom === value) {
                    return;
                  }

                  this._paddingBottom = value;

                  this._doLayoutDirty();
                }
              }, {
                key: "spacingX",
                get: function get() {
                  return this._spacingX;
                },
                set: function set(value) {
                  if (this._spacingX === value) {
                    return;
                  }

                  this._spacingX = value;

                  this._doLayoutDirty();
                }
              }, {
                key: "spacingY",
                get: function get() {
                  return this._spacingY;
                },
                set: function set(value) {
                  if (this._spacingY === value) {
                    return;
                  }

                  this._spacingY = value;

                  this._doLayoutDirty();
                }
              }, {
                key: "verticalDirection",
                get: function get() {
                  return this._verticalDirection;
                },
                set: function set(value) {
                  if (this._verticalDirection === value) {
                    return;
                  }

                  this._verticalDirection = value;

                  this._doLayoutDirty();
                }
              }, {
                key: "horizontalDirection",
                get: function get() {
                  return this._horizontalDirection;
                },
                set: function set(value) {
                  if (this._horizontalDirection === value) {
                    return;
                  }

                  this._horizontalDirection = value;

                  this._doLayoutDirty();
                }
              }, {
                key: "padding",
                get: function get() {
                  return this._paddingLeft;
                },
                set: function set(value) {
                  if (this.paddingLeft !== value || this._paddingRight !== value || this._paddingTop !== value || this._paddingBottom !== value) {
                    this._paddingLeft = this._paddingRight = this._paddingTop = this._paddingBottom = value;

                    this._doLayoutDirty();
                  }
                }
              }, {
                key: "constraint",
                get: function get() {
                  return this._constraint;
                },
                set: function set(value) {
                  if (this._layoutType === Type$1.NONE || this._constraint === value) {
                    return;
                  }

                  this._constraint = value;

                  this._doLayoutDirty();
                }
              }, {
                key: "constraintNum",
                get: function get() {
                  return this._constraintNum;
                },
                set: function set(value) {
                  if (this._constraint === Constraint.NONE || this._constraintNum === value) {
                    return;
                  }

                  if (value <= 0) {
                    warn('Limit values to be greater than 0');
                  }

                  this._constraintNum = value;

                  this._doLayoutDirty();
                }
              }, {
                key: "affectedByScale",
                get: function get() {
                  return this._affectedByScale;
                },
                set: function set(value) {
                  this._affectedByScale = value;

                  this._doLayoutDirty();
                }
              }]);

              return Layout;
            }(Component), _class3$r.Type = Type$1, _class3$r.VerticalDirection = VerticalDirection, _class3$r.HorizontalDirection = HorizontalDirection, _class3$r.ResizeMode = ResizeMode, _class3$r.AxisDirection = AxisDirection, _class3$r.Constraint = Constraint, _temp$14), (_applyDecoratedDescriptor(_class2$11.prototype, "alignHorizontal", [_dec6$j, _dec7$h], Object.getOwnPropertyDescriptor(_class2$11.prototype, "alignHorizontal"), _class2$11.prototype), _applyDecoratedDescriptor(_class2$11.prototype, "alignVertical", [_dec8$g, _dec9$d], Object.getOwnPropertyDescriptor(_class2$11.prototype, "alignVertical"), _class2$11.prototype), _applyDecoratedDescriptor(_class2$11.prototype, "type", [_dec10$c, _dec11$b], Object.getOwnPropertyDescriptor(_class2$11.prototype, "type"), _class2$11.prototype), _applyDecoratedDescriptor(_class2$11.prototype, "resizeMode", [_dec12$b, _dec13$a, _dec14$a], Object.getOwnPropertyDescriptor(_class2$11.prototype, "resizeMode"), _class2$11.prototype), _applyDecoratedDescriptor(_class2$11.prototype, "cellSize", [_dec15$a, _dec16$a], Object.getOwnPropertyDescriptor(_class2$11.prototype, "cellSize"), _class2$11.prototype), _applyDecoratedDescriptor(_class2$11.prototype, "startAxis", [_dec17$9, _dec18$9], Object.getOwnPropertyDescriptor(_class2$11.prototype, "startAxis"), _class2$11.prototype), _applyDecoratedDescriptor(_class2$11.prototype, "paddingLeft", [_dec19$9], Object.getOwnPropertyDescriptor(_class2$11.prototype, "paddingLeft"), _class2$11.prototype), _applyDecoratedDescriptor(_class2$11.prototype, "paddingRight", [_dec20$8], Object.getOwnPropertyDescriptor(_class2$11.prototype, "paddingRight"), _class2$11.prototype), _applyDecoratedDescriptor(_class2$11.prototype, "paddingTop", [_dec21$8], Object.getOwnPropertyDescriptor(_class2$11.prototype, "paddingTop"), _class2$11.prototype), _applyDecoratedDescriptor(_class2$11.prototype, "paddingBottom", [_dec22$8], Object.getOwnPropertyDescriptor(_class2$11.prototype, "paddingBottom"), _class2$11.prototype), _applyDecoratedDescriptor(_class2$11.prototype, "spacingX", [_dec23$8], Object.getOwnPropertyDescriptor(_class2$11.prototype, "spacingX"), _class2$11.prototype), _applyDecoratedDescriptor(_class2$11.prototype, "spacingY", [_dec24$8], Object.getOwnPropertyDescriptor(_class2$11.prototype, "spacingY"), _class2$11.prototype), _applyDecoratedDescriptor(_class2$11.prototype, "verticalDirection", [_dec25$8, _dec26$7], Object.getOwnPropertyDescriptor(_class2$11.prototype, "verticalDirection"), _class2$11.prototype), _applyDecoratedDescriptor(_class2$11.prototype, "horizontalDirection", [_dec27$6, _dec28$6], Object.getOwnPropertyDescriptor(_class2$11.prototype, "horizontalDirection"), _class2$11.prototype), _applyDecoratedDescriptor(_class2$11.prototype, "constraint", [_dec29$6, _dec30$6, _dec31$6], Object.getOwnPropertyDescriptor(_class2$11.prototype, "constraint"), _class2$11.prototype), _applyDecoratedDescriptor(_class2$11.prototype, "constraintNum", [_dec32$5, _dec33$4], Object.getOwnPropertyDescriptor(_class2$11.prototype, "constraintNum"), _class2$11.prototype), _applyDecoratedDescriptor(_class2$11.prototype, "affectedByScale", [_dec34$4], Object.getOwnPropertyDescriptor(_class2$11.prototype, "affectedByScale"), _class2$11.prototype), _descriptor$S = _applyDecoratedDescriptor(_class2$11.prototype, "_resizeMode", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return ResizeMode.NONE;
              }
            }), _descriptor2$D = _applyDecoratedDescriptor(_class2$11.prototype, "_layoutType", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return Type$1.NONE;
              }
            }), _descriptor3$r = _applyDecoratedDescriptor(_class2$11.prototype, "_cellSize", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new Size(40, 40);
              }
            }), _descriptor4$n = _applyDecoratedDescriptor(_class2$11.prototype, "_startAxis", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return AxisDirection.HORIZONTAL;
              }
            }), _descriptor5$j = _applyDecoratedDescriptor(_class2$11.prototype, "_paddingLeft", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor6$d = _applyDecoratedDescriptor(_class2$11.prototype, "_paddingRight", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor7$b = _applyDecoratedDescriptor(_class2$11.prototype, "_paddingTop", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor8$b = _applyDecoratedDescriptor(_class2$11.prototype, "_paddingBottom", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor9$a = _applyDecoratedDescriptor(_class2$11.prototype, "_spacingX", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor10$a = _applyDecoratedDescriptor(_class2$11.prototype, "_spacingY", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor11$9 = _applyDecoratedDescriptor(_class2$11.prototype, "_verticalDirection", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return VerticalDirection.TOP_TO_BOTTOM;
              }
            }), _descriptor12$8 = _applyDecoratedDescriptor(_class2$11.prototype, "_horizontalDirection", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return HorizontalDirection.LEFT_TO_RIGHT;
              }
            }), _descriptor13$7 = _applyDecoratedDescriptor(_class2$11.prototype, "_constraint", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return Constraint.NONE;
              }
            }), _descriptor14$6 = _applyDecoratedDescriptor(_class2$11.prototype, "_constraintNum", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 2;
              }
            }), _descriptor15$5 = _applyDecoratedDescriptor(_class2$11.prototype, "_affectedByScale", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor16$5 = _applyDecoratedDescriptor(_class2$11.prototype, "_isAlign", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            })), _class2$11)) || _class$19) || _class$19) || _class$19) || _class$19) || _class$19) || _class$19));

            var _dec$19, _dec2$L, _dec3$D, _dec4$x, _dec5$q, _dec6$k, _dec7$i, _dec8$h, _dec9$e, _dec10$d, _dec11$c, _dec12$c, _dec13$b, _class$1a, _class2$12, _descriptor$T, _descriptor2$E, _descriptor3$s, _descriptor4$o, _descriptor5$k, _class3$s, _temp$15;
            var Mode;

            (function (Mode) {
              Mode[Mode["HORIZONTAL"] = 0] = "HORIZONTAL";
              Mode[Mode["VERTICAL"] = 1] = "VERTICAL";
              Mode[Mode["FILLED"] = 2] = "FILLED";
            })(Mode || (Mode = {}));

            Enum(Mode);
            var ProgressBar = function (v) { return exports({ ProgressBar: v, ProgressBarComponent: v }), v; }((_dec$19 = ccclass('cc.ProgressBar'), _dec2$L = help(), _dec3$D = executionOrder(110), _dec4$x = menu(), _dec5$q = requireComponent(UITransform), _dec6$k = type(Sprite), _dec7$i = tooltip(), _dec8$h = type(Mode), _dec9$e = tooltip(), _dec10$d = tooltip(), _dec11$c = range(), _dec12$c = tooltip(), _dec13$b = tooltip(), _dec$19(_class$1a = _dec2$L(_class$1a = _dec3$D(_class$1a = _dec4$x(_class$1a = _dec5$q(_class$1a = (_class2$12 = (_temp$15 = _class3$s = function (_Component) {
              _inheritsLoose(ProgressBar, _Component);

              function ProgressBar() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Component.call.apply(_Component, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "_barSprite", _descriptor$T, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_mode", _descriptor2$E, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_totalLength", _descriptor3$s, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_progress", _descriptor4$o, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_reverse", _descriptor5$k, _assertThisInitialized(_this));

                return _this;
              }

              var _proto = ProgressBar.prototype;

              _proto._initBarSprite = function _initBarSprite() {
                if (this._barSprite) {
                  var entity = this._barSprite.node;

                  if (!entity) {
                    return;
                  }

                  var trans = this.node._uiProps.uiTransformComp;
                  var nodeSize = trans.contentSize;
                  var nodeAnchor = trans.anchorPoint;
                  var barSpriteSize = entity._uiProps.uiTransformComp.contentSize;

                  if (this._barSprite.fillType === Sprite.FillType.RADIAL) {
                    this._mode = Mode.FILLED;
                  }

                  if (this._mode === Mode.HORIZONTAL) {
                    this.totalLength = barSpriteSize.width;
                  } else if (this._mode === Mode.VERTICAL) {
                    this.totalLength = barSpriteSize.height;
                  } else {
                    this.totalLength = this._barSprite.fillRange;
                  }

                  if (entity.parent === this.node) {
                    var x = -nodeSize.width * nodeAnchor.x;
                    entity.setPosition(x, 0, 0);
                  }
                }
              };

              _proto._updateBarStatus = function _updateBarStatus() {
                if (this._barSprite) {
                  var entity = this._barSprite.node;

                  if (!entity) {
                    return;
                  }

                  var entTrans = entity._uiProps.uiTransformComp;
                  var entityAnchorPoint = entTrans.anchorPoint;
                  var entitySize = entTrans.contentSize;
                  var entityPosition = entity.getPosition();
                  var anchorPoint = new Vec2(0, 0.5);
                  var progress = clamp01(this._progress);
                  var actualLenth = this._totalLength * progress;
                  var finalContentSize = entitySize;
                  var totalWidth = 0;
                  var totalHeight = 0;

                  switch (this._mode) {
                    case Mode.HORIZONTAL:
                      if (this._reverse) {
                        anchorPoint = new Vec2(1, 0.5);
                      }

                      finalContentSize = new Size(actualLenth, entitySize.height);
                      totalWidth = this._totalLength;
                      totalHeight = entitySize.height;
                      break;

                    case Mode.VERTICAL:
                      if (this._reverse) {
                        anchorPoint = new Vec2(0.5, 1);
                      } else {
                        anchorPoint = new Vec2(0.5, 0);
                      }

                      finalContentSize = new Size(entitySize.width, actualLenth);
                      totalWidth = entitySize.width;
                      totalHeight = this._totalLength;
                      break;
                  }

                  if (this._mode === Mode.FILLED) {
                    if (this._barSprite.type !== Sprite.Type.FILLED) {
                      warn('ProgressBar FILLED mode only works when barSprite\'s Type is FILLED!');
                    } else {
                      if (this._reverse) {
                        actualLenth *= -1;
                      }

                      this._barSprite.fillRange = actualLenth;
                    }
                  } else if (this._barSprite.type !== Sprite.Type.FILLED) {
                    var anchorOffsetX = anchorPoint.x - entityAnchorPoint.x;
                    var anchorOffsetY = anchorPoint.y - entityAnchorPoint.y;
                    var finalPosition = new Vec3(totalWidth * anchorOffsetX, totalHeight * anchorOffsetY, 0);
                    entity.setPosition(entityPosition.x + finalPosition.x, entityPosition.y + finalPosition.y, entityPosition.z);
                    entTrans.setAnchorPoint(anchorPoint);
                    entTrans.setContentSize(finalContentSize);
                  } else {
                    warn('ProgressBar non-FILLED mode only works when barSprite\'s Type is non-FILLED!');
                  }
                }
              };

              _createClass(ProgressBar, [{
                key: "barSprite",
                get: function get() {
                  return this._barSprite;
                },
                set: function set(value) {
                  if (this._barSprite === value) {
                    return;
                  }

                  this._barSprite = value;

                  this._initBarSprite();
                }
              }, {
                key: "mode",
                get: function get() {
                  return this._mode;
                },
                set: function set(value) {
                  if (this._mode === value) {
                    return;
                  }

                  this._mode = value;

                  if (this._barSprite) {
                    var entity = this._barSprite.node;

                    if (!entity) {
                      return;
                    }

                    var entitySize = entity._uiProps.uiTransformComp.contentSize;

                    if (this._mode === Mode.HORIZONTAL) {
                      this.totalLength = entitySize.width;
                    } else if (this._mode === Mode.VERTICAL) {
                      this.totalLength = entitySize.height;
                    } else if (this._mode === Mode.FILLED) {
                      this.totalLength = this._barSprite.fillRange;
                    }
                  }
                }
              }, {
                key: "totalLength",
                get: function get() {
                  return this._totalLength;
                },
                set: function set(value) {
                  if (this._mode === Mode.FILLED) {
                    value = clamp01(value);
                  }

                  this._totalLength = value;

                  this._updateBarStatus();
                }
              }, {
                key: "progress",
                get: function get() {
                  return this._progress;
                },
                set: function set(value) {
                  if (this._progress === value) {
                    return;
                  }

                  this._progress = value;

                  this._updateBarStatus();
                }
              }, {
                key: "reverse",
                get: function get() {
                  return this._reverse;
                },
                set: function set(value) {
                  if (this._reverse === value) {
                    return;
                  }

                  this._reverse = value;

                  if (this._barSprite) {
                    this._barSprite.fillStart = 1 - this._barSprite.fillStart;
                  }

                  this._updateBarStatus();
                }
              }]);

              return ProgressBar;
            }(Component), _class3$s.Mode = Mode, _temp$15), (_applyDecoratedDescriptor(_class2$12.prototype, "barSprite", [_dec6$k, _dec7$i], Object.getOwnPropertyDescriptor(_class2$12.prototype, "barSprite"), _class2$12.prototype), _applyDecoratedDescriptor(_class2$12.prototype, "mode", [_dec8$h, _dec9$e], Object.getOwnPropertyDescriptor(_class2$12.prototype, "mode"), _class2$12.prototype), _applyDecoratedDescriptor(_class2$12.prototype, "totalLength", [_dec10$d], Object.getOwnPropertyDescriptor(_class2$12.prototype, "totalLength"), _class2$12.prototype), _applyDecoratedDescriptor(_class2$12.prototype, "progress", [_dec11$c, slide, _dec12$c], Object.getOwnPropertyDescriptor(_class2$12.prototype, "progress"), _class2$12.prototype), _applyDecoratedDescriptor(_class2$12.prototype, "reverse", [_dec13$b], Object.getOwnPropertyDescriptor(_class2$12.prototype, "reverse"), _class2$12.prototype), _descriptor$T = _applyDecoratedDescriptor(_class2$12.prototype, "_barSprite", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor2$E = _applyDecoratedDescriptor(_class2$12.prototype, "_mode", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return Mode.HORIZONTAL;
              }
            }), _descriptor3$s = _applyDecoratedDescriptor(_class2$12.prototype, "_totalLength", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1;
              }
            }), _descriptor4$o = _applyDecoratedDescriptor(_class2$12.prototype, "_progress", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0.1;
              }
            }), _descriptor5$k = _applyDecoratedDescriptor(_class2$12.prototype, "_reverse", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            })), _class2$12)) || _class$1a) || _class$1a) || _class$1a) || _class$1a) || _class$1a));

            var _dec$1a, _dec2$M, _dec3$E, _dec4$y, _dec5$r, _dec6$l, _dec7$j, _dec8$i, _dec9$f, _dec10$e, _dec11$d, _dec12$d, _dec13$c, _dec14$b, _dec15$b, _class$1b, _class2$13, _descriptor$U, _descriptor2$F, _descriptor3$t, _descriptor4$p, _descriptor5$l, _class3$t, _temp$16;
            var GETTING_SHORTER_FACTOR = 20;

            var _tempPos_1 = new Vec3();

            var _tempPos_2 = new Vec3();

            var _tempVec3$2 = new Vec3();

            var defaultAnchor = new Vec2();

            var _tempColor$1 = new Color();

            var _tempVec2 = new Vec2();

            var Direction;

            (function (Direction) {
              Direction[Direction["HORIZONTAL"] = 0] = "HORIZONTAL";
              Direction[Direction["VERTICAL"] = 1] = "VERTICAL";
            })(Direction || (Direction = {}));

            ccenum(Direction);
            var ScrollBar = function (v) { return exports({ ScrollBar: v, ScrollBarComponent: v }), v; }((_dec$1a = ccclass('cc.ScrollBar'), _dec2$M = help(), _dec3$E = executionOrder(110), _dec4$y = menu(), _dec5$r = requireComponent(UITransform), _dec6$l = type(Sprite), _dec7$j = displayOrder(), _dec8$i = tooltip(), _dec9$f = type(Direction), _dec10$e = displayOrder(), _dec11$d = tooltip(), _dec12$d = displayOrder(), _dec13$c = tooltip(), _dec14$b = displayOrder(), _dec15$b = tooltip(), _dec$1a(_class$1b = _dec2$M(_class$1b = _dec3$E(_class$1b = _dec4$y(_class$1b = _dec5$r(_class$1b = (_class2$13 = (_temp$16 = _class3$t = function (_Component) {
              _inheritsLoose(ScrollBar, _Component);

              function ScrollBar() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Component.call.apply(_Component, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "_scrollView", _descriptor$U, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_handle", _descriptor2$F, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_direction", _descriptor3$t, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_enableAutoHide", _descriptor4$p, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_autoHideTime", _descriptor5$l, _assertThisInitialized(_this));

                _this._touching = false;
                _this._opacity = 255;
                _this._autoHideRemainingTime = 0;
                return _this;
              }

              var _proto = ScrollBar.prototype;

              _proto.hide = function hide() {
                this._autoHideRemainingTime = 0;

                this._setOpacity(0);
              };

              _proto.show = function show() {
                this._autoHideRemainingTime = this._autoHideTime;

                this._setOpacity(this._opacity);
              };

              _proto.onScroll = function onScroll(outOfBoundary) {
                if (!this._scrollView) {
                  return;
                }

                var content = this._scrollView.content;

                if (!content) {
                  return;
                }

                var contentSize = content._uiProps.uiTransformComp.contentSize;
                var scrollViewSize = this._scrollView.node._uiProps.uiTransformComp.contentSize;
                var barSize = this.node._uiProps.uiTransformComp.contentSize;

                if (this._conditionalDisableScrollBar(contentSize, scrollViewSize)) {
                  return;
                }

                if (this._enableAutoHide) {
                  this._autoHideRemainingTime = this._autoHideTime;

                  this._setOpacity(this._opacity);
                }

                var contentMeasure = 0;
                var scrollViewMeasure = 0;
                var outOfBoundaryValue = 0;
                var contentPosition = 0;
                var handleNodeMeasure = 0;
                var outOfContentPosition = _tempVec2;
                outOfContentPosition.set(0, 0);

                if (this._direction === Direction.HORIZONTAL) {
                  contentMeasure = contentSize.width;
                  scrollViewMeasure = scrollViewSize.width;
                  handleNodeMeasure = barSize.width;
                  outOfBoundaryValue = outOfBoundary.x;

                  this._convertToScrollViewSpace(outOfContentPosition, content);

                  contentPosition = -outOfContentPosition.x;
                } else if (this._direction === Direction.VERTICAL) {
                  contentMeasure = contentSize.height;
                  scrollViewMeasure = scrollViewSize.height;
                  handleNodeMeasure = barSize.height;
                  outOfBoundaryValue = outOfBoundary.y;

                  this._convertToScrollViewSpace(outOfContentPosition, content);

                  contentPosition = -outOfContentPosition.y;
                }

                var length = this._calculateLength(contentMeasure, scrollViewMeasure, handleNodeMeasure, outOfBoundaryValue);

                var position = _tempVec2;

                this._calculatePosition(position, contentMeasure, scrollViewMeasure, handleNodeMeasure, contentPosition, outOfBoundaryValue, length);

                this._updateLength(length);

                this._updateHandlerPosition(position);
              };

              _proto.setScrollView = function setScrollView(scrollView) {
                this._scrollView = scrollView;
              };

              _proto.onTouchBegan = function onTouchBegan() {
                if (!this._enableAutoHide) {
                  return;
                }

                this._touching = true;
              };

              _proto.onTouchEnded = function onTouchEnded() {
                if (!this._enableAutoHide) {
                  return;
                }

                this._touching = false;

                if (this._autoHideTime <= 0) {
                  return;
                }

                if (this._scrollView) {
                  var content = this._scrollView.content;

                  if (content) {
                    var contentSize = content._uiProps.uiTransformComp.contentSize;
                    var scrollViewSize = this._scrollView.node._uiProps.uiTransformComp.contentSize;

                    if (this._conditionalDisableScrollBar(contentSize, scrollViewSize)) {
                      return;
                    }
                  }
                }

                this._autoHideRemainingTime = this._autoHideTime;
              };

              _proto.onEnable = function onEnable() {
                var renderComp = this.node.getComponent(Sprite);

                if (renderComp) {
                  this._opacity = renderComp.color.a;
                }
              };

              _proto.start = function start() {
                if (this._enableAutoHide) {
                  this._setOpacity(0);
                }
              };

              _proto.update = function update(dt) {
                this._processAutoHide(dt);
              };

              _proto._convertToScrollViewSpace = function _convertToScrollViewSpace(out, content) {
                var scrollTrans = this._scrollView && this._scrollView.node._uiProps.uiTransformComp;
                var contentTrans = content._uiProps.uiTransformComp;

                if (!scrollTrans || !contentTrans) {
                  out.set(Vec2.ZERO);
                } else {
                  _tempPos_1.set(-contentTrans.anchorX * contentTrans.width, -contentTrans.anchorY * contentTrans.height, 0);

                  contentTrans.convertToWorldSpaceAR(_tempPos_1, _tempPos_2);
                  var scrollViewSpacePos = scrollTrans.convertToNodeSpaceAR(_tempPos_2);
                  scrollViewSpacePos.x += scrollTrans.anchorX * scrollTrans.width;
                  scrollViewSpacePos.y += scrollTrans.anchorY * scrollTrans.height;
                  out.set(scrollViewSpacePos.x, scrollViewSpacePos.y);
                }
              };

              _proto._setOpacity = function _setOpacity(opacity) {
                if (this._handle) {
                  var renderComp = this.node.getComponent(Sprite);

                  if (renderComp) {
                    _tempColor$1.set(renderComp.color);

                    _tempColor$1.a = opacity;
                    renderComp.color = _tempColor$1;
                  }

                  renderComp = this._handle.getComponent(Sprite);

                  if (renderComp) {
                    _tempColor$1.set(renderComp.color);

                    _tempColor$1.a = opacity;
                    renderComp.color = _tempColor$1;
                  }
                }
              };

              _proto._updateHandlerPosition = function _updateHandlerPosition(position) {
                if (this._handle) {
                  var oldPosition = _tempVec3$2;

                  this._fixupHandlerPosition(oldPosition);

                  this._handle.node.setPosition(position.x + oldPosition.x, position.y + oldPosition.y, oldPosition.z);
                }
              };

              _proto._fixupHandlerPosition = function _fixupHandlerPosition(out) {
                var uiTrans = this.node._uiProps.uiTransformComp;
                var barSize = uiTrans.contentSize;
                var barAnchor = uiTrans.anchorPoint;
                var handleSize = this.handle.node._uiProps.uiTransformComp.contentSize;
                var handleParent = this.handle.node.parent;
                Vec3.set(_tempPos_1, -barSize.width * barAnchor.x, -barSize.height * barAnchor.y, 0);

                var leftBottomWorldPosition = this.node._uiProps.uiTransformComp.convertToWorldSpaceAR(_tempPos_1, _tempPos_2);

                var fixupPosition = out;
                fixupPosition.set(0, 0, 0);

                handleParent._uiProps.uiTransformComp.convertToNodeSpaceAR(leftBottomWorldPosition, fixupPosition);

                if (this.direction === Direction.HORIZONTAL) {
                  fixupPosition.set(fixupPosition.x, fixupPosition.y + (barSize.height - handleSize.height) / 2, fixupPosition.z);
                } else if (this.direction === Direction.VERTICAL) {
                  fixupPosition.set(fixupPosition.x + (barSize.width - handleSize.width) / 2, fixupPosition.y, fixupPosition.z);
                }

                this.handle.node.setPosition(fixupPosition);
              };

              _proto._conditionalDisableScrollBar = function _conditionalDisableScrollBar(contentSize, scrollViewSize) {
                if (contentSize.width <= scrollViewSize.width && this._direction === Direction.HORIZONTAL) {
                  return true;
                }

                if (contentSize.height <= scrollViewSize.height && this._direction === Direction.VERTICAL) {
                  return true;
                }

                return false;
              };

              _proto._calculateLength = function _calculateLength(contentMeasure, scrollViewMeasure, handleNodeMeasure, outOfBoundary) {
                var denominatorValue = contentMeasure;

                if (outOfBoundary) {
                  denominatorValue += (outOfBoundary > 0 ? outOfBoundary : -outOfBoundary) * GETTING_SHORTER_FACTOR;
                }

                var lengthRation = scrollViewMeasure / denominatorValue;
                return handleNodeMeasure * lengthRation;
              };

              _proto._calculatePosition = function _calculatePosition(out, contentMeasure, scrollViewMeasure, handleNodeMeasure, contentPosition, outOfBoundary, actualLenth) {
                var denominatorValue = contentMeasure - scrollViewMeasure;

                if (outOfBoundary) {
                  denominatorValue += Math.abs(outOfBoundary);
                }

                var positionRatio = 0;

                if (denominatorValue) {
                  positionRatio = contentPosition / denominatorValue;
                  positionRatio = clamp01(positionRatio);
                }

                var position = (handleNodeMeasure - actualLenth) * positionRatio;

                if (this._direction === Direction.VERTICAL) {
                  out.set(0, position);
                } else {
                  out.set(position, 0);
                }
              };

              _proto._updateLength = function _updateLength(length) {
                if (this._handle) {
                  var handleNode = this._handle.node;
                  var handleTrans = handleNode._uiProps.uiTransformComp;
                  var handleNodeSize = handleTrans.contentSize;
                  var anchor = handleTrans.anchorPoint;

                  if (anchor.x !== defaultAnchor.x || anchor.y !== defaultAnchor.y) {
                    handleTrans.setAnchorPoint(defaultAnchor);
                  }

                  if (this._direction === Direction.HORIZONTAL) {
                    handleTrans.setContentSize(length, handleNodeSize.height);
                  } else {
                    handleTrans.setContentSize(handleNodeSize.width, length);
                  }
                }
              };

              _proto._processAutoHide = function _processAutoHide(deltaTime) {
                if (!this._enableAutoHide || this._autoHideRemainingTime <= 0) {
                  return;
                } else if (this._touching) {
                  return;
                }

                this._autoHideRemainingTime -= deltaTime;

                if (this._autoHideRemainingTime <= this._autoHideTime) {
                  this._autoHideRemainingTime = Math.max(0, this._autoHideRemainingTime);
                  var opacity = this._opacity * (this._autoHideRemainingTime / this._autoHideTime);

                  this._setOpacity(opacity);
                }
              };

              _createClass(ScrollBar, [{
                key: "handle",
                get: function get() {
                  return this._handle;
                },
                set: function set(value) {
                  if (this._handle === value) {
                    return;
                  }

                  this._handle = value;
                  this.onScroll(Vec2.ZERO);
                }
              }, {
                key: "direction",
                get: function get() {
                  return this._direction;
                },
                set: function set(value) {
                  if (this._direction === value) {
                    return;
                  }

                  this._direction = value;
                  this.onScroll(Vec2.ZERO);
                }
              }, {
                key: "enableAutoHide",
                get: function get() {
                  return this._enableAutoHide;
                },
                set: function set(value) {
                  if (this._enableAutoHide === value) {
                    return;
                  }

                  this._enableAutoHide = value;

                  if (this._enableAutoHide) {
                    this._setOpacity(0);
                  }
                }
              }, {
                key: "autoHideTime",
                get: function get() {
                  return this._autoHideTime;
                },
                set: function set(value) {
                  if (this._autoHideTime === value) {
                    return;
                  }

                  this._autoHideTime = value;
                }
              }]);

              return ScrollBar;
            }(Component), _class3$t.Direction = Direction, _temp$16), (_applyDecoratedDescriptor(_class2$13.prototype, "handle", [_dec6$l, _dec7$j, _dec8$i], Object.getOwnPropertyDescriptor(_class2$13.prototype, "handle"), _class2$13.prototype), _applyDecoratedDescriptor(_class2$13.prototype, "direction", [_dec9$f, _dec10$e, _dec11$d], Object.getOwnPropertyDescriptor(_class2$13.prototype, "direction"), _class2$13.prototype), _applyDecoratedDescriptor(_class2$13.prototype, "enableAutoHide", [_dec12$d, _dec13$c], Object.getOwnPropertyDescriptor(_class2$13.prototype, "enableAutoHide"), _class2$13.prototype), _applyDecoratedDescriptor(_class2$13.prototype, "autoHideTime", [_dec14$b, _dec15$b], Object.getOwnPropertyDescriptor(_class2$13.prototype, "autoHideTime"), _class2$13.prototype), _descriptor$U = _applyDecoratedDescriptor(_class2$13.prototype, "_scrollView", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor2$F = _applyDecoratedDescriptor(_class2$13.prototype, "_handle", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor3$t = _applyDecoratedDescriptor(_class2$13.prototype, "_direction", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return Direction.HORIZONTAL;
              }
            }), _descriptor4$p = _applyDecoratedDescriptor(_class2$13.prototype, "_enableAutoHide", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor5$l = _applyDecoratedDescriptor(_class2$13.prototype, "_autoHideTime", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1.0;
              }
            })), _class2$13)) || _class$1b) || _class$1b) || _class$1b) || _class$1b) || _class$1b));

            var _dec$1b, _dec2$N, _class$1c;
            var ViewGroup = exports('ViewGroup', (_dec$1b = ccclass('cc.ViewGroup'), _dec2$N = executionOrder(110), _dec$1b(_class$1c = _dec2$N(_class$1c = function (_Component) {
              _inheritsLoose(ViewGroup, _Component);

              function ViewGroup() {
                return _Component.apply(this, arguments) || this;
              }

              return ViewGroup;
            }(Component)) || _class$1c) || _class$1c));
            legacyCC.ViewGroup = ViewGroup;

            var _dec$1c, _dec2$O, _dec3$F, _dec4$z, _dec5$s, _dec6$m, _dec7$k, _dec8$j, _dec9$g, _dec10$f, _dec11$e, _dec12$e, _dec13$d, _dec14$c, _dec15$c, _dec16$b, _dec17$a, _dec18$a, _dec19$a, _dec20$9, _dec21$9, _dec22$9, _dec23$9, _dec24$9, _dec25$9, _dec26$8, _dec27$7, _dec28$7, _dec29$7, _dec30$7, _dec31$7, _dec32$6, _dec33$5, _class$1d, _class2$14, _descriptor$V, _descriptor2$G, _descriptor3$u, _descriptor4$q, _descriptor5$m, _descriptor6$e, _descriptor7$c, _descriptor8$c, _descriptor9$b, _descriptor10$b, _descriptor11$a, _class3$u, _temp$17;
            var NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED = 5;
            var OUT_OF_BOUNDARY_BREAKING_FACTOR = 0.05;
            var EPSILON$2 = 1e-4;
            var TOLERANCE = 1e4;
            var MOVEMENT_FACTOR = 0.7;

            var _tempVec3$3 = new Vec3();

            var _tempVec3_1 = new Vec3();

            var _tempVec2$1 = new Vec2();

            var _tempVec2_1 = new Vec2();

            var quintEaseOut = function quintEaseOut(time) {
              time -= 1;
              return time * time * time * time * time + 1;
            };

            var getTimeInMilliseconds = function getTimeInMilliseconds() {
              var currentTime = new Date();
              return currentTime.getMilliseconds();
            };

            var eventMap = {
              'scroll-to-top': 0,
              'scroll-to-bottom': 1,
              'scroll-to-left': 2,
              'scroll-to-right': 3,
              scrolling: 4,
              'bounce-bottom': 6,
              'bounce-left': 7,
              'bounce-right': 8,
              'bounce-top': 5,
              'scroll-ended': 9,
              'touch-up': 10,
              'scroll-ended-with-threshold': 11,
              'scroll-began': 12
            };
            var EventType$4;

            (function (EventType) {
              EventType["SCROLL_TO_TOP"] = "scroll-to-top";
              EventType["SCROLL_TO_BOTTOM"] = "scroll-to-bottom";
              EventType["SCROLL_TO_LEFT"] = "scroll-to-left";
              EventType["SCROLL_TO_RIGHT"] = "scroll-to-right";
              EventType["SCROLL_BEGAN"] = "scroll-began";
              EventType["SCROLL_ENDED"] = "scroll-ended";
              EventType["BOUNCE_TOP"] = "bounce-top";
              EventType["BOUNCE_BOTTOM"] = "bounce-bottom";
              EventType["BOUNCE_LEFT"] = "bounce-left";
              EventType["BOUNCE_RIGHT"] = "bounce-right";
              EventType["SCROLLING"] = "scrolling";
              EventType["SCROLL_ENG_WITH_THRESHOLD"] = "scroll-ended-with-threshold";
              EventType["TOUCH_UP"] = "touch-up";
            })(EventType$4 || (EventType$4 = {}));

            var ScrollView = function (v) { return exports({ ScrollView: v, ScrollViewComponent: v }), v; }((_dec$1c = ccclass('cc.ScrollView'), _dec2$O = help(), _dec3$F = executionOrder(110), _dec4$z = menu(), _dec5$s = requireComponent(UITransform), _dec6$m = range(), _dec7$k = displayOrder(), _dec8$j = tooltip(), _dec9$g = range(), _dec10$f = displayOrder(), _dec11$e = tooltip(), _dec12$e = displayOrder(), _dec13$d = tooltip(), _dec14$c = displayOrder(), _dec15$c = tooltip(), _dec16$b = type(Node$1), _dec17$a = displayOrder(), _dec18$a = tooltip(), _dec19$a = displayOrder(), _dec20$9 = tooltip(), _dec21$9 = type(ScrollBar), _dec22$9 = displayOrder(), _dec23$9 = tooltip(), _dec24$9 = displayOrder(), _dec25$9 = tooltip(), _dec26$8 = type(ScrollBar), _dec27$7 = displayOrder(), _dec28$7 = tooltip(), _dec29$7 = displayOrder(), _dec30$7 = tooltip(), _dec31$7 = type([EventHandler]), _dec32$6 = displayOrder(), _dec33$5 = tooltip(), _dec$1c(_class$1d = _dec2$O(_class$1d = _dec3$F(_class$1d = _dec4$z(_class$1d = _dec5$s(_class$1d = (_class2$14 = (_temp$17 = _class3$u = function (_ViewGroup) {
              _inheritsLoose(ScrollView, _ViewGroup);

              function ScrollView() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _ViewGroup.call.apply(_ViewGroup, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "bounceDuration", _descriptor$V, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "brake", _descriptor2$G, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "elastic", _descriptor3$u, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "inertia", _descriptor4$q, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "horizontal", _descriptor5$m, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "vertical", _descriptor6$e, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "cancelInnerEvents", _descriptor7$c, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "scrollEvents", _descriptor8$c, _assertThisInitialized(_this));

                _this._autoScrolling = false;
                _this._scrolling = false;

                _initializerDefineProperty(_this, "_content", _descriptor9$b, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_horizontalScrollBar", _descriptor10$b, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_verticalScrollBar", _descriptor11$a, _assertThisInitialized(_this));

                _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();
                return _this;
              }

              var _proto = ScrollView.prototype;

              _proto.scrollToBottom = function scrollToBottom(timeInSecond, attenuated) {
                if (attenuated === void 0) {
                  attenuated = true;
                }

                var moveDelta = this._calculateMovePercentDelta({
                  anchor: new Vec2(0, 0),
                  applyToHorizontal: false,
                  applyToVertical: true
                });

                if (timeInSecond) {
                  this._startAutoScroll(moveDelta, timeInSecond, attenuated !== false);
                } else {
                  this._moveContent(moveDelta, true);
                }
              };

              _proto.scrollToTop = function scrollToTop(timeInSecond, attenuated) {
                if (attenuated === void 0) {
                  attenuated = true;
                }

                var moveDelta = this._calculateMovePercentDelta({
                  anchor: new Vec2(0, 1),
                  applyToHorizontal: false,
                  applyToVertical: true
                });

                if (timeInSecond) {
                  this._startAutoScroll(moveDelta, timeInSecond, attenuated !== false);
                } else {
                  this._moveContent(moveDelta);
                }
              };

              _proto.scrollToLeft = function scrollToLeft(timeInSecond, attenuated) {
                if (attenuated === void 0) {
                  attenuated = true;
                }

                var moveDelta = this._calculateMovePercentDelta({
                  anchor: new Vec2(0, 0),
                  applyToHorizontal: true,
                  applyToVertical: false
                });

                if (timeInSecond) {
                  this._startAutoScroll(moveDelta, timeInSecond, attenuated !== false);
                } else {
                  this._moveContent(moveDelta);
                }
              };

              _proto.scrollToRight = function scrollToRight(timeInSecond, attenuated) {
                if (attenuated === void 0) {
                  attenuated = true;
                }

                var moveDelta = this._calculateMovePercentDelta({
                  anchor: new Vec2(1, 0),
                  applyToHorizontal: true,
                  applyToVertical: false
                });

                if (timeInSecond) {
                  this._startAutoScroll(moveDelta, timeInSecond, attenuated !== false);
                } else {
                  this._moveContent(moveDelta);
                }
              };

              _proto.scrollToTopLeft = function scrollToTopLeft(timeInSecond, attenuated) {
                if (attenuated === void 0) {
                  attenuated = true;
                }

                var moveDelta = this._calculateMovePercentDelta({
                  anchor: new Vec2(0, 1),
                  applyToHorizontal: true,
                  applyToVertical: true
                });

                if (timeInSecond) {
                  this._startAutoScroll(moveDelta, timeInSecond, attenuated !== false);
                } else {
                  this._moveContent(moveDelta);
                }
              };

              _proto.scrollToTopRight = function scrollToTopRight(timeInSecond, attenuated) {
                if (attenuated === void 0) {
                  attenuated = true;
                }

                var moveDelta = this._calculateMovePercentDelta({
                  anchor: new Vec2(1, 1),
                  applyToHorizontal: true,
                  applyToVertical: true
                });

                if (timeInSecond) {
                  this._startAutoScroll(moveDelta, timeInSecond, attenuated !== false);
                } else {
                  this._moveContent(moveDelta);
                }
              };

              _proto.scrollToBottomLeft = function scrollToBottomLeft(timeInSecond, attenuated) {
                if (attenuated === void 0) {
                  attenuated = true;
                }

                var moveDelta = this._calculateMovePercentDelta({
                  anchor: new Vec2(0, 0),
                  applyToHorizontal: true,
                  applyToVertical: true
                });

                if (timeInSecond) {
                  this._startAutoScroll(moveDelta, timeInSecond, attenuated !== false);
                } else {
                  this._moveContent(moveDelta);
                }
              };

              _proto.scrollToBottomRight = function scrollToBottomRight(timeInSecond, attenuated) {
                if (attenuated === void 0) {
                  attenuated = true;
                }

                var moveDelta = this._calculateMovePercentDelta({
                  anchor: new Vec2(1, 0),
                  applyToHorizontal: true,
                  applyToVertical: true
                });

                if (timeInSecond) {
                  this._startAutoScroll(moveDelta, timeInSecond, attenuated !== false);
                } else {
                  this._moveContent(moveDelta);
                }
              };

              _proto.scrollToOffset = function scrollToOffset(offset, timeInSecond, attenuated) {
                if (attenuated === void 0) {
                  attenuated = true;
                }

                var maxScrollOffset = this.getMaxScrollOffset();
                var anchor = new Vec2(0, 0);

                if (maxScrollOffset.x === 0) {
                  anchor.x = 0;
                } else {
                  anchor.x = offset.x / maxScrollOffset.x;
                }

                if (maxScrollOffset.y === 0) {
                  anchor.y = 1;
                } else {
                  anchor.y = (maxScrollOffset.y - offset.y) / maxScrollOffset.y;
                }

                this.scrollTo(anchor, timeInSecond, attenuated);
              };

              _proto.getScrollOffset = function getScrollOffset() {
                var topDelta = this._getContentTopBoundary() - this._topBoundary;

                var leftDelta = this._getContentLeftBoundary() - this._leftBoundary;

                return new Vec2(leftDelta, topDelta);
              };

              _proto.getMaxScrollOffset = function getMaxScrollOffset() {
                if (!this._content || !this.view) {
                  return Vec2.ZERO;
                }

                var contentSize = this._content._uiProps.uiTransformComp.contentSize;
                var horizontalMaximizeOffset = contentSize.width - this.view.width;
                var verticalMaximizeOffset = contentSize.height - this.view.height;
                horizontalMaximizeOffset = horizontalMaximizeOffset >= 0 ? horizontalMaximizeOffset : 0;
                verticalMaximizeOffset = verticalMaximizeOffset >= 0 ? verticalMaximizeOffset : 0;
                return new Vec2(horizontalMaximizeOffset, verticalMaximizeOffset);
              };

              _proto.scrollToPercentHorizontal = function scrollToPercentHorizontal(percent, timeInSecond, attenuated) {
                var moveDelta = this._calculateMovePercentDelta({
                  anchor: new Vec2(percent, 0),
                  applyToHorizontal: true,
                  applyToVertical: false
                });

                if (timeInSecond) {
                  this._startAutoScroll(moveDelta, timeInSecond, attenuated !== false);
                } else {
                  this._moveContent(moveDelta);
                }
              };

              _proto.scrollTo = function scrollTo(anchor, timeInSecond, attenuated) {
                var moveDelta = this._calculateMovePercentDelta({
                  anchor: new Vec2(anchor),
                  applyToHorizontal: true,
                  applyToVertical: true
                });

                if (timeInSecond) {
                  this._startAutoScroll(moveDelta, timeInSecond, attenuated);
                } else {
                  this._moveContent(moveDelta);
                }
              };

              _proto.scrollToPercentVertical = function scrollToPercentVertical(percent, timeInSecond, attenuated) {
                var moveDelta = this._calculateMovePercentDelta({
                  anchor: new Vec2(0, percent),
                  applyToHorizontal: false,
                  applyToVertical: true
                });

                if (timeInSecond) {
                  this._startAutoScroll(moveDelta, timeInSecond, attenuated);
                } else {
                  this._moveContent(moveDelta);
                }
              };

              _proto.stopAutoScroll = function stopAutoScroll() {
                this._autoScrolling = false;
                this._autoScrollAccumulatedTime = this._autoScrollTotalTime;
              };

              _proto.setContentPosition = function setContentPosition(position) {
                this._setContentPosition(position);
              };

              _proto._setContentPosition = function _setContentPosition(position) {
                if (!this._content) {
                  return;
                }

                var contentPos = this._getContentPosition();

                if (Math.abs(position.x - contentPos.x) < EPSILON$2 && Math.abs(position.y - contentPos.y) < EPSILON$2) {
                  return;
                }

                this._content.setPosition(position);

                this._outOfBoundaryAmountDirty = true;
              };

              _proto.getContentPosition = function getContentPosition() {
                return this._getContentPosition();
              };

              _proto._getContentPosition = function _getContentPosition() {
                if (!this._content) {
                  return Vec3.ZERO;
                }

                this._contentPos.set(this._content.position);

                return this._contentPos;
              };

              _proto.isScrolling = function isScrolling() {
                return this._scrolling;
              };

              _proto.isAutoScrolling = function isAutoScrolling() {
                return this._autoScrolling;
              };

              _proto.getScrollEndedEventTiming = function getScrollEndedEventTiming() {
                return EPSILON$2;
              };

              _proto.start = function start() {
                this._calculateBoundary();

                if (this._content) {
                  director.once(Director.EVENT_BEFORE_DRAW, this._adjustContentOutOfBoundary, this);
                }
              };

              _proto.onEnable = function onEnable() {
                {
                  this._registerEvent();

                  if (this._content) {
                    this._content.on(Node$1.EventType.SIZE_CHANGED, this._calculateBoundary, this);

                    this._content.on(Node$1.EventType.TRANSFORM_CHANGED, this._scaleChanged, this);

                    if (this.view) {
                      this.view.node.on(Node$1.EventType.TRANSFORM_CHANGED, this._scaleChanged, this);
                      this.view.node.on(Node$1.EventType.SIZE_CHANGED, this._calculateBoundary, this);
                    }
                  }

                  this._calculateBoundary();
                }

                this._updateScrollBarState();
              };

              _proto.update = function update(dt) {
                if (this._autoScrolling) {
                  this._processAutoScrolling(dt);
                }
              };

              _proto.onDisable = function onDisable() {
                {
                  this._unregisterEvent();

                  if (this._content) {
                    this._content.off(Node$1.EventType.SIZE_CHANGED, this._calculateBoundary, this);

                    this._content.off(Node$1.EventType.TRANSFORM_CHANGED, this._scaleChanged, this);

                    if (this.view) {
                      this.view.node.off(Node$1.EventType.TRANSFORM_CHANGED, this._scaleChanged, this);
                      this.view.node.off(Node$1.EventType.SIZE_CHANGED, this._calculateBoundary, this);
                    }
                  }
                }

                this._hideScrollBar();

                this.stopAutoScroll();
              };

              _proto._registerEvent = function _registerEvent() {
                this.node.on(Node$1.EventType.TOUCH_START, this._onTouchBegan, this, true);
                this.node.on(Node$1.EventType.TOUCH_MOVE, this._onTouchMoved, this, true);
                this.node.on(Node$1.EventType.TOUCH_END, this._onTouchEnded, this, true);
                this.node.on(Node$1.EventType.TOUCH_CANCEL, this._onTouchCancelled, this, true);
                this.node.on(Node$1.EventType.MOUSE_WHEEL, this._onMouseWheel, this, true);
              };

              _proto._unregisterEvent = function _unregisterEvent() {
                this.node.off(Node$1.EventType.TOUCH_START, this._onTouchBegan, this, true);
                this.node.off(Node$1.EventType.TOUCH_MOVE, this._onTouchMoved, this, true);
                this.node.off(Node$1.EventType.TOUCH_END, this._onTouchEnded, this, true);
                this.node.off(Node$1.EventType.TOUCH_CANCEL, this._onTouchCancelled, this, true);
                this.node.off(Node$1.EventType.MOUSE_WHEEL, this._onMouseWheel, this, true);
              };

              _proto._onMouseWheel = function _onMouseWheel(event, captureListeners) {
                if (!this.enabledInHierarchy) {
                  return;
                }

                if (this._hasNestedViewGroup(event, captureListeners)) {
                  return;
                }

                var deltaMove = new Vec3();
                var wheelPrecision = -0.1;
                var scrollY = event.getScrollY();

                if (this.vertical) {
                  deltaMove.set(0, scrollY * wheelPrecision, 0);
                } else if (this.horizontal) {
                  deltaMove.set(scrollY * wheelPrecision, 0, 0);
                }

                this._mouseWheelEventElapsedTime = 0;

                this._processDeltaMove(deltaMove);

                if (!this._stopMouseWheel) {
                  this._handlePressLogic();

                  this.schedule(this._checkMouseWheel, 1.0 / 60, NaN, 0);
                  this._stopMouseWheel = true;
                }

                this._stopPropagationIfTargetIsMe(event);
              };

              _proto._onTouchBegan = function _onTouchBegan(event, captureListeners) {
                if (!this.enabledInHierarchy || !this._content) {
                  return;
                }

                if (this._hasNestedViewGroup(event, captureListeners)) {
                  return;
                }

                this._handlePressLogic();

                this._touchMoved = false;

                this._stopPropagationIfTargetIsMe(event);
              };

              _proto._onTouchMoved = function _onTouchMoved(event, captureListeners) {
                if (!this.enabledInHierarchy || !this._content) {
                  return;
                }

                if (this._hasNestedViewGroup(event, captureListeners)) {
                  return;
                }

                var touch = event.touch;

                this._handleMoveLogic(touch);

                if (!this.cancelInnerEvents) {
                  return;
                }

                var deltaMove = touch.getUILocation(_tempVec2$1);
                deltaMove.subtract(touch.getUIStartLocation(_tempVec2_1));

                if (deltaMove.length() > 7) {
                  if (!this._touchMoved && event.target !== this.node) {
                    var cancelEvent = new EventTouch(event.getTouches(), event.bubbles);
                    cancelEvent.type = Node$1.EventType.TOUCH_CANCEL;
                    cancelEvent.touch = event.touch;
                    cancelEvent.simulate = true;
                    event.target.dispatchEvent(cancelEvent);
                    this._touchMoved = true;
                  }
                }

                this._stopPropagationIfTargetIsMe(event);
              };

              _proto._onTouchEnded = function _onTouchEnded(event, captureListeners) {
                if (!this.enabledInHierarchy || !this._content || !event) {
                  return;
                }

                if (this._hasNestedViewGroup(event, captureListeners)) {
                  return;
                }

                this._dispatchEvent(EventType$4.TOUCH_UP);

                var touch = event.touch;

                this._handleReleaseLogic(touch);

                if (this._touchMoved) {
                  event.propagationStopped = true;
                } else {
                  this._stopPropagationIfTargetIsMe(event);
                }
              };

              _proto._onTouchCancelled = function _onTouchCancelled(event, captureListeners) {
                if (!this.enabledInHierarchy || !this._content) {
                  return;
                }

                if (this._hasNestedViewGroup(event, captureListeners)) {
                  return;
                }

                if (event && !event.simulate) {
                  var touch = event.touch;

                  this._handleReleaseLogic(touch);
                }

                this._stopPropagationIfTargetIsMe(event);
              };

              _proto._calculateBoundary = function _calculateBoundary() {
                if (this._content && this.view) {
                  var layout = this._content.getComponent(Layout);

                  if (layout && layout.enabledInHierarchy) {
                    layout.updateLayout();
                  }

                  var viewTrans = this.view;
                  var anchorX = viewTrans.width * viewTrans.anchorX;
                  var anchorY = viewTrans.height * viewTrans.anchorY;
                  this._leftBoundary = -anchorX;
                  this._bottomBoundary = -anchorY;
                  this._rightBoundary = this._leftBoundary + viewTrans.width;
                  this._topBoundary = this._bottomBoundary + viewTrans.height;

                  this._moveContentToTopLeft(viewTrans.contentSize);
                }
              };

              _proto._hasNestedViewGroup = function _hasNestedViewGroup(event, captureListeners) {
                if (!event || event.eventPhase !== Event.CAPTURING_PHASE) {
                  return false;
                }

                if (captureListeners) {
                  for (var _iterator = _createForOfIteratorHelperLoose(captureListeners), _step; !(_step = _iterator()).done;) {
                    var listener = _step.value;
                    var item = listener;

                    if (this.node === item) {
                      if (event.target && event.target.getComponent(ViewGroup)) {
                        return true;
                      }

                      return false;
                    }

                    if (item.getComponent(ViewGroup)) {
                      return true;
                    }
                  }
                }

                return false;
              };

              _proto._startInertiaScroll = function _startInertiaScroll(touchMoveVelocity) {
                var inertiaTotalMovement = new Vec3(touchMoveVelocity);
                inertiaTotalMovement.multiplyScalar(MOVEMENT_FACTOR);

                this._startAttenuatingAutoScroll(inertiaTotalMovement, touchMoveVelocity);
              };

              _proto._calculateAttenuatedFactor = function _calculateAttenuatedFactor(distance) {
                if (this.brake <= 0) {
                  return 1 - this.brake;
                }

                return (1 - this.brake) * (1 / (1 + distance * 0.000014 + distance * distance * 0.000000008));
              };

              _proto._startAttenuatingAutoScroll = function _startAttenuatingAutoScroll(deltaMove, initialVelocity) {
                var targetDelta = deltaMove.clone();
                targetDelta.normalize();

                if (this._content && this.view) {
                  var contentSize = this._content._uiProps.uiTransformComp.contentSize;
                  var scrollViewSize = this.view.contentSize;
                  var totalMoveWidth = contentSize.width - scrollViewSize.width;
                  var totalMoveHeight = contentSize.height - scrollViewSize.height;

                  var attenuatedFactorX = this._calculateAttenuatedFactor(totalMoveWidth);

                  var attenuatedFactorY = this._calculateAttenuatedFactor(totalMoveHeight);

                  targetDelta.x = targetDelta.x * totalMoveWidth * (1 - this.brake) * attenuatedFactorX;
                  targetDelta.y = targetDelta.y * totalMoveHeight * attenuatedFactorY * (1 - this.brake);
                  targetDelta.z = 0;
                }

                var originalMoveLength = deltaMove.length();
                var factor = targetDelta.length() / originalMoveLength;
                targetDelta.add(deltaMove);

                if (this.brake > 0 && factor > 7) {
                  factor = Math.sqrt(factor);
                  var clonedDeltaMove = deltaMove.clone();
                  clonedDeltaMove.multiplyScalar(factor);
                  targetDelta.set(clonedDeltaMove);
                  targetDelta.add(deltaMove);
                }

                var time = this._calculateAutoScrollTimeByInitialSpeed(initialVelocity.length());

                if (this.brake > 0 && factor > 3) {
                  factor = 3;
                  time *= factor;
                }

                if (this.brake === 0 && factor > 1) {
                  time *= factor;
                }

                this._startAutoScroll(targetDelta, time, true);
              };

              _proto._calculateAutoScrollTimeByInitialSpeed = function _calculateAutoScrollTimeByInitialSpeed(initialSpeed) {
                return Math.sqrt(Math.sqrt(initialSpeed / 5));
              };

              _proto._startAutoScroll = function _startAutoScroll(deltaMove, timeInSecond, attenuated) {
                if (attenuated === void 0) {
                  attenuated = false;
                }

                var adjustedDeltaMove = this._flattenVectorByDirection(deltaMove);

                this._autoScrolling = true;
                this._autoScrollTargetDelta = adjustedDeltaMove;
                this._autoScrollAttenuate = attenuated;
                Vec3.copy(this._autoScrollStartPosition, this._getContentPosition());
                this._autoScrollTotalTime = timeInSecond;
                this._autoScrollAccumulatedTime = 0;
                this._autoScrollBraking = false;
                this._isScrollEndedWithThresholdEventFired = false;

                this._autoScrollBrakingStartPosition.set(0, 0, 0);

                var currentOutOfBoundary = this._getHowMuchOutOfBoundary();

                if (!currentOutOfBoundary.equals(Vec3.ZERO, EPSILON$2)) {
                  this._autoScrollCurrentlyOutOfBoundary = true;
                }
              };

              _proto._calculateTouchMoveVelocity = function _calculateTouchMoveVelocity() {
                var out = new Vec3();
                var totalTime = 0;
                totalTime = this._touchMoveTimeDeltas.reduce(function (a, b) {
                  return a + b;
                }, totalTime);

                if (totalTime <= 0 || totalTime >= 0.5) {
                  out.set(Vec3.ZERO);
                } else {
                  var totalMovement = new Vec3();
                  totalMovement = this._touchMoveDisplacements.reduce(function (a, b) {
                    a.add(b);
                    return a;
                  }, totalMovement);
                  out.set(totalMovement.x * (1 - this.brake) / totalTime, totalMovement.y * (1 - this.brake) / totalTime, totalMovement.z);
                }

                return out;
              };

              _proto._flattenVectorByDirection = function _flattenVectorByDirection(vector) {
                var result = vector;
                result.x = this.horizontal ? result.x : 0;
                result.y = this.vertical ? result.y : 0;
                return result;
              };

              _proto._moveContent = function _moveContent(deltaMove, canStartBounceBack) {
                var adjustedMove = this._flattenVectorByDirection(deltaMove);

                _tempVec3$3.set(this._getContentPosition());

                _tempVec3$3.add(adjustedMove);

                _tempVec3$3.set(Math.floor(_tempVec3$3.x * TOLERANCE) * EPSILON$2, Math.floor(_tempVec3$3.y * TOLERANCE) * EPSILON$2, _tempVec3$3.z);

                this._setContentPosition(_tempVec3$3);

                var outOfBoundary = this._getHowMuchOutOfBoundary();

                _tempVec2$1.set(outOfBoundary.x, outOfBoundary.y);

                this._updateScrollBar(_tempVec2$1);

                if (this.elastic && canStartBounceBack) {
                  this._startBounceBackIfNeeded();
                }
              };

              _proto._getContentLeftBoundary = function _getContentLeftBoundary() {
                if (!this._content) {
                  return -1;
                }

                var contentPos = this._getContentPosition();

                var uiTrans = this._content._uiProps.uiTransformComp;
                return contentPos.x - uiTrans.anchorX * uiTrans.width;
              };

              _proto._getContentRightBoundary = function _getContentRightBoundary() {
                if (!this._content) {
                  return -1;
                }

                var uiTrans = this._content._uiProps.uiTransformComp;
                return this._getContentLeftBoundary() + uiTrans.width;
              };

              _proto._getContentTopBoundary = function _getContentTopBoundary() {
                if (!this._content) {
                  return -1;
                }

                var uiTrans = this._content._uiProps.uiTransformComp;
                return this._getContentBottomBoundary() + uiTrans.height;
              };

              _proto._getContentBottomBoundary = function _getContentBottomBoundary() {
                if (!this._content) {
                  return -1;
                }

                var contentPos = this._getContentPosition();

                var uiTrans = this._content._uiProps.uiTransformComp;
                return contentPos.y - uiTrans.anchorY * uiTrans.height;
              };

              _proto._getHowMuchOutOfBoundary = function _getHowMuchOutOfBoundary(addition) {
                addition = addition || new Vec3();

                if (addition.equals(Vec3.ZERO, EPSILON$2) && !this._outOfBoundaryAmountDirty) {
                  return this._outOfBoundaryAmount;
                }

                var outOfBoundaryAmount = new Vec3();

                if (this._getContentLeftBoundary() + addition.x > this._leftBoundary) {
                  outOfBoundaryAmount.x = this._leftBoundary - (this._getContentLeftBoundary() + addition.x);
                } else if (this._getContentRightBoundary() + addition.x < this._rightBoundary) {
                  outOfBoundaryAmount.x = this._rightBoundary - (this._getContentRightBoundary() + addition.x);
                }

                if (this._getContentTopBoundary() + addition.y < this._topBoundary) {
                  outOfBoundaryAmount.y = this._topBoundary - (this._getContentTopBoundary() + addition.y);
                } else if (this._getContentBottomBoundary() + addition.y > this._bottomBoundary) {
                  outOfBoundaryAmount.y = this._bottomBoundary - (this._getContentBottomBoundary() + addition.y);
                }

                if (addition.equals(Vec3.ZERO, EPSILON$2)) {
                  this._outOfBoundaryAmount = outOfBoundaryAmount;
                  this._outOfBoundaryAmountDirty = false;
                }

                this._clampDelta(outOfBoundaryAmount);

                return outOfBoundaryAmount;
              };

              _proto._updateScrollBar = function _updateScrollBar(outOfBoundary) {
                if (this._horizontalScrollBar) {
                  this._horizontalScrollBar.onScroll(outOfBoundary);
                }

                if (this.verticalScrollBar) {
                  this.verticalScrollBar.onScroll(outOfBoundary);
                }
              };

              _proto._onScrollBarTouchBegan = function _onScrollBarTouchBegan() {
                if (this._horizontalScrollBar) {
                  this._horizontalScrollBar.onTouchBegan();
                }

                if (this.verticalScrollBar) {
                  this.verticalScrollBar.onTouchBegan();
                }
              };

              _proto._onScrollBarTouchEnded = function _onScrollBarTouchEnded() {
                if (this._horizontalScrollBar) {
                  this._horizontalScrollBar.onTouchEnded();
                }

                if (this.verticalScrollBar) {
                  this.verticalScrollBar.onTouchEnded();
                }
              };

              _proto._dispatchEvent = function _dispatchEvent(event) {
                if (event === EventType$4.SCROLL_ENDED) {
                  this._scrollEventEmitMask = 0;
                } else if (event === EventType$4.SCROLL_TO_TOP || event === EventType$4.SCROLL_TO_BOTTOM || event === EventType$4.SCROLL_TO_LEFT || event === EventType$4.SCROLL_TO_RIGHT) {
                  var flag = 1 << eventMap[event];

                  if (this._scrollEventEmitMask & flag) {
                    return;
                  } else {
                    this._scrollEventEmitMask |= flag;
                  }
                }

                EventHandler.emitEvents(this.scrollEvents, this, eventMap[event]);
                this.node.emit(event, this);
              };

              _proto._adjustContentOutOfBoundary = function _adjustContentOutOfBoundary() {
                if (!this._content) {
                  return;
                }

                this._outOfBoundaryAmountDirty = true;

                if (this._isOutOfBoundary()) {
                  var outOfBoundary = this._getHowMuchOutOfBoundary();

                  _tempVec3$3.set(this._getContentPosition());

                  _tempVec3$3.add(outOfBoundary);

                  this._content.setPosition(_tempVec3$3);

                  this._updateScrollBar(Vec2.ZERO);
                }
              };

              _proto._hideScrollBar = function _hideScrollBar() {
                if (this._horizontalScrollBar) {
                  this._horizontalScrollBar.hide();
                }

                if (this._verticalScrollBar) {
                  this._verticalScrollBar.hide();
                }
              };

              _proto._updateScrollBarState = function _updateScrollBarState() {
                if (!this._content || !this.view) {
                  return;
                }

                var viewTrans = this.view;
                var uiTrans = this._content._uiProps.uiTransformComp;

                if (this.verticalScrollBar) {
                  if (uiTrans.height < viewTrans.height) {
                    this.verticalScrollBar.hide();
                  } else {
                    this.verticalScrollBar.show();
                  }
                }

                if (this.horizontalScrollBar) {
                  if (uiTrans.width < viewTrans.width) {
                    this.horizontalScrollBar.hide();
                  } else {
                    this.horizontalScrollBar.show();
                  }
                }
              };

              _proto._stopPropagationIfTargetIsMe = function _stopPropagationIfTargetIsMe(event) {
                if (event.eventPhase === Event.AT_TARGET && event.target === this.node) {
                  event.propagationStopped = true;
                }
              };

              _proto._processDeltaMove = function _processDeltaMove(deltaMove) {
                this._scrollChildren(deltaMove);

                this._gatherTouchMove(deltaMove);
              };

              _proto._handleMoveLogic = function _handleMoveLogic(touch) {
                this._getLocalAxisAlignDelta(this._deltaPos, touch);

                this._processDeltaMove(this._deltaPos);
              };

              _proto._handleReleaseLogic = function _handleReleaseLogic(touch) {
                this._getLocalAxisAlignDelta(this._deltaPos, touch);

                this._gatherTouchMove(this._deltaPos);

                this._processInertiaScroll();

                if (this._scrolling) {
                  this._scrolling = false;

                  if (!this._autoScrolling) {
                    this._dispatchEvent(EventType$4.SCROLL_ENDED);
                  }
                }
              };

              _proto._getLocalAxisAlignDelta = function _getLocalAxisAlignDelta(out, touch) {
                var uiTransformComp = this.node._uiProps.uiTransformComp;
                var vec = new Vec3();

                if (uiTransformComp) {
                  touch.getUILocation(_tempVec2$1);
                  touch.getUIPreviousLocation(_tempVec2_1);

                  _tempVec3$3.set(_tempVec2$1.x, _tempVec2$1.y, 0);

                  _tempVec3_1.set(_tempVec2_1.x, _tempVec2_1.y, 0);

                  uiTransformComp.convertToNodeSpaceAR(_tempVec3$3, _tempVec3$3);
                  uiTransformComp.convertToNodeSpaceAR(_tempVec3_1, _tempVec3_1);
                  Vec3.subtract(vec, _tempVec3$3, _tempVec3_1);
                }

                out.set(vec);
              };

              _proto._scrollChildren = function _scrollChildren(deltaMove) {
                this._clampDelta(deltaMove);

                var realMove = deltaMove;
                var outOfBoundary;

                if (this.elastic) {
                  outOfBoundary = this._getHowMuchOutOfBoundary();
                  realMove.x *= outOfBoundary.x === 0 ? 1 : 0.5;
                  realMove.y *= outOfBoundary.y === 0 ? 1 : 0.5;
                }

                if (!this.elastic) {
                  outOfBoundary = this._getHowMuchOutOfBoundary(realMove);
                  realMove.add(outOfBoundary);
                }

                var scrollEventType;

                if (this._content) {
                  var _ref = this._content._uiProps.uiTransformComp,
                      anchorX = _ref.anchorX,
                      anchorY = _ref.anchorY,
                      width = _ref.width,
                      height = _ref.height;
                  var pos = this._content.position || Vec3.ZERO;

                  if (realMove.y > 0) {
                    var icBottomPos = pos.y - anchorY * height;

                    if (icBottomPos + realMove.y >= this._bottomBoundary) {
                      scrollEventType = EventType$4.SCROLL_TO_BOTTOM;
                    }
                  } else if (realMove.y < 0) {
                    var icTopPos = pos.y - anchorY * height + height;

                    if (icTopPos + realMove.y <= this._topBoundary) {
                      scrollEventType = EventType$4.SCROLL_TO_TOP;
                    }
                  }

                  if (realMove.x < 0) {
                    var icRightPos = pos.x - anchorX * width + width;

                    if (icRightPos + realMove.x <= this._rightBoundary) {
                      scrollEventType = EventType$4.SCROLL_TO_RIGHT;
                    }
                  } else if (realMove.x > 0) {
                    var icLeftPos = pos.x - anchorX * width;

                    if (icLeftPos + realMove.x >= this._leftBoundary) {
                      scrollEventType = EventType$4.SCROLL_TO_LEFT;
                    }
                  }
                }

                this._moveContent(realMove, false);

                if (realMove.x !== 0 || realMove.y !== 0) {
                  if (!this._scrolling) {
                    this._scrolling = true;

                    this._dispatchEvent(EventType$4.SCROLL_BEGAN);
                  }

                  this._dispatchEvent(EventType$4.SCROLLING);
                }

                if (scrollEventType && scrollEventType.length > 0) {
                  this._dispatchEvent(scrollEventType);
                }
              };

              _proto._handlePressLogic = function _handlePressLogic() {
                if (this._autoScrolling) {
                  this._dispatchEvent(EventType$4.SCROLL_ENDED);
                }

                this._autoScrolling = false;
                this._isBouncing = false;
                this._touchMovePreviousTimestamp = getTimeInMilliseconds();
                this._touchMoveDisplacements.length = 0;
                this._touchMoveTimeDeltas.length = 0;

                this._onScrollBarTouchBegan();
              };

              _proto._clampDelta = function _clampDelta(out) {
                if (this._content && this.view) {
                  var scrollViewSize = this.view.contentSize;
                  var uiTrans = this._content._uiProps.uiTransformComp;

                  if (uiTrans.width < scrollViewSize.width) {
                    out.x = 0;
                  }

                  if (uiTrans.height < scrollViewSize.height) {
                    out.y = 0;
                  }
                }
              };

              _proto._gatherTouchMove = function _gatherTouchMove(delta) {
                var clampDt = delta.clone();

                this._clampDelta(clampDt);

                while (this._touchMoveDisplacements.length >= NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED) {
                  this._touchMoveDisplacements.shift();

                  this._touchMoveTimeDeltas.shift();
                }

                this._touchMoveDisplacements.push(clampDt);

                var timeStamp = getTimeInMilliseconds();

                this._touchMoveTimeDeltas.push((timeStamp - this._touchMovePreviousTimestamp) / 1000);

                this._touchMovePreviousTimestamp = timeStamp;
              };

              _proto._startBounceBackIfNeeded = function _startBounceBackIfNeeded() {
                if (!this.elastic) {
                  return false;
                }

                var bounceBackAmount = this._getHowMuchOutOfBoundary();

                this._clampDelta(bounceBackAmount);

                if (bounceBackAmount.equals(Vec3.ZERO, EPSILON$2)) {
                  return false;
                }

                var bounceBackTime = Math.max(this.bounceDuration, 0);

                this._startAutoScroll(bounceBackAmount, bounceBackTime, true);

                if (!this._isBouncing) {
                  if (bounceBackAmount.y > 0) {
                    this._dispatchEvent(EventType$4.BOUNCE_TOP);
                  }

                  if (bounceBackAmount.y < 0) {
                    this._dispatchEvent(EventType$4.BOUNCE_BOTTOM);
                  }

                  if (bounceBackAmount.x > 0) {
                    this._dispatchEvent(EventType$4.BOUNCE_RIGHT);
                  }

                  if (bounceBackAmount.x < 0) {
                    this._dispatchEvent(EventType$4.BOUNCE_LEFT);
                  }

                  this._isBouncing = true;
                }

                return true;
              };

              _proto._processInertiaScroll = function _processInertiaScroll() {
                var bounceBackStarted = this._startBounceBackIfNeeded();

                if (!bounceBackStarted && this.inertia) {
                  var touchMoveVelocity = this._calculateTouchMoveVelocity();

                  if (!touchMoveVelocity.equals(_tempVec3$3, EPSILON$2) && this.brake < 1) {
                    this._startInertiaScroll(touchMoveVelocity);
                  }
                }

                this._onScrollBarTouchEnded();
              };

              _proto._isOutOfBoundary = function _isOutOfBoundary() {
                var outOfBoundary = this._getHowMuchOutOfBoundary();

                return !outOfBoundary.equals(Vec3.ZERO, EPSILON$2);
              };

              _proto._isNecessaryAutoScrollBrake = function _isNecessaryAutoScrollBrake() {
                if (this._autoScrollBraking) {
                  return true;
                }

                if (this._isOutOfBoundary()) {
                  if (!this._autoScrollCurrentlyOutOfBoundary) {
                    this._autoScrollCurrentlyOutOfBoundary = true;
                    this._autoScrollBraking = true;
                    this._autoScrollBrakingStartPosition = this._getContentPosition();
                    return true;
                  }
                } else {
                  this._autoScrollCurrentlyOutOfBoundary = false;
                }

                return false;
              };

              _proto._processAutoScrolling = function _processAutoScrolling(dt) {
                var isAutoScrollBrake = this._isNecessaryAutoScrollBrake();

                var brakingFactor = isAutoScrollBrake ? OUT_OF_BOUNDARY_BREAKING_FACTOR : 1;
                this._autoScrollAccumulatedTime += dt * (1 / brakingFactor);
                var percentage = Math.min(1, this._autoScrollAccumulatedTime / this._autoScrollTotalTime);

                if (this._autoScrollAttenuate) {
                  percentage = quintEaseOut(percentage);
                }

                var clonedAutoScrollTargetDelta = this._autoScrollTargetDelta.clone();

                clonedAutoScrollTargetDelta.multiplyScalar(percentage);

                var clonedAutoScrollStartPosition = this._autoScrollStartPosition.clone();

                clonedAutoScrollStartPosition.add(clonedAutoScrollTargetDelta);
                var reachedEnd = Math.abs(percentage - 1) <= EPSILON$2;
                var fireEvent = Math.abs(percentage - 1) <= this.getScrollEndedEventTiming();

                if (fireEvent && !this._isScrollEndedWithThresholdEventFired) {
                  this._dispatchEvent(EventType$4.SCROLL_ENG_WITH_THRESHOLD);

                  this._isScrollEndedWithThresholdEventFired = true;
                }

                if (this.elastic) {
                  var brakeOffsetPosition = clonedAutoScrollStartPosition.clone();
                  brakeOffsetPosition.subtract(this._autoScrollBrakingStartPosition);

                  if (isAutoScrollBrake) {
                    brakeOffsetPosition.multiplyScalar(brakingFactor);
                  }

                  clonedAutoScrollStartPosition.set(this._autoScrollBrakingStartPosition);
                  clonedAutoScrollStartPosition.add(brakeOffsetPosition);
                } else {
                  var moveDelta = clonedAutoScrollStartPosition.clone();
                  moveDelta.subtract(this.getContentPosition());

                  var outOfBoundary = this._getHowMuchOutOfBoundary(moveDelta);

                  if (!outOfBoundary.equals(Vec3.ZERO, EPSILON$2)) {
                    clonedAutoScrollStartPosition.add(outOfBoundary);
                    reachedEnd = true;
                  }
                }

                if (reachedEnd) {
                  this._autoScrolling = false;
                }

                var deltaMove = clonedAutoScrollStartPosition.clone();
                deltaMove.subtract(this._getContentPosition());

                this._clampDelta(deltaMove);

                this._moveContent(deltaMove, reachedEnd);

                this._dispatchEvent(EventType$4.SCROLLING);

                if (!this._autoScrolling) {
                  this._isBouncing = false;
                  this._scrolling = false;

                  this._dispatchEvent(EventType$4.SCROLL_ENDED);
                }
              };

              _proto._checkMouseWheel = function _checkMouseWheel(dt) {
                var currentOutOfBoundary = this._getHowMuchOutOfBoundary();

                var maxElapsedTime = 0.1;

                if (!currentOutOfBoundary.equals(Vec3.ZERO, EPSILON$2)) {
                  this._processInertiaScroll();

                  this.unschedule(this._checkMouseWheel);

                  this._dispatchEvent(EventType$4.SCROLL_ENDED);

                  this._stopMouseWheel = false;
                  return;
                }

                this._mouseWheelEventElapsedTime += dt;

                if (this._mouseWheelEventElapsedTime > maxElapsedTime) {
                  this._onScrollBarTouchEnded();

                  this.unschedule(this._checkMouseWheel);

                  this._dispatchEvent(EventType$4.SCROLL_ENDED);

                  this._stopMouseWheel = false;
                }
              };

              _proto._calculateMovePercentDelta = function _calculateMovePercentDelta(options) {
                var anchor = options.anchor;
                var applyToHorizontal = options.applyToHorizontal;
                var applyToVertical = options.applyToVertical;

                this._calculateBoundary();

                anchor.clampf(Vec2.ZERO, Vec2.ONE);

                var bottomDelta = this._getContentBottomBoundary() - this._bottomBoundary;

                bottomDelta = -bottomDelta;

                var leftDelta = this._getContentLeftBoundary() - this._leftBoundary;

                leftDelta = -leftDelta;
                var moveDelta = new Vec3();

                if (this._content && this.view) {
                  var totalScrollDelta = 0;
                  var uiTrans = this._content._uiProps.uiTransformComp;
                  var contentSize = uiTrans.contentSize;
                  var scrollSize = this.view.contentSize;

                  if (applyToHorizontal) {
                    totalScrollDelta = contentSize.width - scrollSize.width;
                    moveDelta.x = leftDelta - totalScrollDelta * anchor.x;
                  }

                  if (applyToVertical) {
                    totalScrollDelta = contentSize.height - scrollSize.height;
                    moveDelta.y = bottomDelta - totalScrollDelta * anchor.y;
                  }
                }

                return moveDelta;
              };

              _proto._moveContentToTopLeft = function _moveContentToTopLeft(scrollViewSize) {
                var bottomDelta = this._getContentBottomBoundary() - this._bottomBoundary;

                bottomDelta = -bottomDelta;
                var moveDelta = new Vec3();
                var totalScrollDelta = 0;

                var leftDelta = this._getContentLeftBoundary() - this._leftBoundary;

                leftDelta = -leftDelta;

                if (this._content) {
                  var uiTrans = this._content._uiProps.uiTransformComp;
                  var contentSize = uiTrans.contentSize;

                  if (contentSize.height < scrollViewSize.height) {
                    totalScrollDelta = contentSize.height - scrollViewSize.height;
                    moveDelta.y = bottomDelta - totalScrollDelta;
                  }

                  if (contentSize.width < scrollViewSize.width) {
                    totalScrollDelta = contentSize.width - scrollViewSize.width;
                    moveDelta.x = leftDelta;
                  }
                }

                this._updateScrollBarState();

                this._moveContent(moveDelta);

                this._adjustContentOutOfBoundary();
              };

              _proto._scaleChanged = function _scaleChanged(value) {
                if (value === TransformBit.SCALE) {
                  this._calculateBoundary();
                }
              };

              _createClass(ScrollView, [{
                key: "content",
                get: function get() {
                  return this._content;
                },
                set: function set(value) {
                  if (this._content === value) {
                    return;
                  }

                  var viewTrans = value && value.parent && value.parent._uiProps.uiTransformComp;

                  if (value && (!value || !viewTrans)) {
                    logID(4302);
                    return;
                  }

                  this._content = value;

                  this._calculateBoundary();
                }
              }, {
                key: "horizontalScrollBar",
                get: function get() {
                  return this._horizontalScrollBar;
                },
                set: function set(value) {
                  if (this._horizontalScrollBar === value) {
                    return;
                  }

                  this._horizontalScrollBar = value;

                  if (this._horizontalScrollBar) {
                    this._horizontalScrollBar.setScrollView(this);

                    this._updateScrollBar(Vec2.ZERO);
                  }
                }
              }, {
                key: "verticalScrollBar",
                get: function get() {
                  return this._verticalScrollBar;
                },
                set: function set(value) {
                  if (this._verticalScrollBar === value) {
                    return;
                  }

                  this._verticalScrollBar = value;

                  if (this._verticalScrollBar) {
                    this._verticalScrollBar.setScrollView(this);

                    this._updateScrollBar(Vec2.ZERO);
                  }
                }
              }, {
                key: "view",
                get: function get() {
                  var parent = this._content && this._content.parent;

                  if (!parent) {
                    return null;
                  }

                  return parent._uiProps.uiTransformComp;
                }
              }]);

              return ScrollView;
            }(ViewGroup), _class3$u.EventType = EventType$4, _temp$17), (_descriptor$V = _applyDecoratedDescriptor(_class2$14.prototype, "bounceDuration", [serializable, _dec6$m, _dec7$k, _dec8$j], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1;
              }
            }), _descriptor2$G = _applyDecoratedDescriptor(_class2$14.prototype, "brake", [serializable, _dec9$g, _dec10$f, _dec11$e], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0.5;
              }
            }), _descriptor3$u = _applyDecoratedDescriptor(_class2$14.prototype, "elastic", [serializable, _dec12$e, _dec13$d], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _descriptor4$q = _applyDecoratedDescriptor(_class2$14.prototype, "inertia", [serializable, _dec14$c, _dec15$c], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _applyDecoratedDescriptor(_class2$14.prototype, "content", [_dec16$b, _dec17$a, _dec18$a], Object.getOwnPropertyDescriptor(_class2$14.prototype, "content"), _class2$14.prototype), _descriptor5$m = _applyDecoratedDescriptor(_class2$14.prototype, "horizontal", [serializable, _dec19$a, _dec20$9], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _applyDecoratedDescriptor(_class2$14.prototype, "horizontalScrollBar", [_dec21$9, _dec22$9, _dec23$9], Object.getOwnPropertyDescriptor(_class2$14.prototype, "horizontalScrollBar"), _class2$14.prototype), _descriptor6$e = _applyDecoratedDescriptor(_class2$14.prototype, "vertical", [serializable, _dec24$9, _dec25$9], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _applyDecoratedDescriptor(_class2$14.prototype, "verticalScrollBar", [_dec26$8, _dec27$7, _dec28$7], Object.getOwnPropertyDescriptor(_class2$14.prototype, "verticalScrollBar"), _class2$14.prototype), _descriptor7$c = _applyDecoratedDescriptor(_class2$14.prototype, "cancelInnerEvents", [serializable, _dec29$7, _dec30$7], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _descriptor8$c = _applyDecoratedDescriptor(_class2$14.prototype, "scrollEvents", [_dec31$7, serializable, _dec32$6, _dec33$5], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor9$b = _applyDecoratedDescriptor(_class2$14.prototype, "_content", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor10$b = _applyDecoratedDescriptor(_class2$14.prototype, "_horizontalScrollBar", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor11$a = _applyDecoratedDescriptor(_class2$14.prototype, "_verticalScrollBar", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            })), _class2$14)) || _class$1d) || _class$1d) || _class$1d) || _class$1d) || _class$1d));

            var _dec$1d, _dec2$P, _dec3$G, _dec4$A, _dec5$t, _dec6$n, _dec7$l, _dec8$k, _dec9$h, _dec10$g, _dec11$f, _dec12$f, _dec13$e, _class$1e, _class2$15, _descriptor$W, _descriptor2$H, _descriptor3$v, _descriptor4$r, _class3$v, _temp$18;

            var _tempPos = new Vec3();

            var Direction$1;

            (function (Direction) {
              Direction[Direction["Horizontal"] = 0] = "Horizontal";
              Direction[Direction["Vertical"] = 1] = "Vertical";
            })(Direction$1 || (Direction$1 = {}));

            ccenum(Direction$1);
            var Slider = function (v) { return exports({ Slider: v, SliderComponent: v }), v; }((_dec$1d = ccclass('cc.Slider'), _dec2$P = help(), _dec3$G = executionOrder(110), _dec4$A = menu(), _dec5$t = requireComponent(UITransform), _dec6$n = type(Sprite), _dec7$l = tooltip(), _dec8$k = type(Direction$1), _dec9$h = tooltip(), _dec10$g = range(), _dec11$f = tooltip(), _dec12$f = type([EventHandler]), _dec13$e = tooltip(), _dec$1d(_class$1e = _dec2$P(_class$1e = _dec3$G(_class$1e = _dec4$A(_class$1e = _dec5$t(_class$1e = (_class2$15 = (_temp$18 = _class3$v = function (_Component) {
              _inheritsLoose(Slider, _Component);

              function Slider() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Component.call.apply(_Component, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "slideEvents", _descriptor$W, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_handle", _descriptor2$H, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_direction", _descriptor3$v, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_progress", _descriptor4$r, _assertThisInitialized(_this));

                _this._offset = new Vec3();
                _this._dragging = false;
                _this._touchHandle = false;
                _this._handleLocalPos = new Vec3();
                _this._touchPos = new Vec3();
                return _this;
              }

              var _proto = Slider.prototype;

              _proto.__preload = function __preload() {
                this._updateHandlePosition();
              };

              _proto.onEnable = function onEnable() {
                this._updateHandlePosition();

                this.node.on(SystemEventType.TOUCH_START, this._onTouchBegan, this);
                this.node.on(SystemEventType.TOUCH_MOVE, this._onTouchMoved, this);
                this.node.on(SystemEventType.TOUCH_END, this._onTouchEnded, this);
                this.node.on(SystemEventType.TOUCH_CANCEL, this._onTouchCancelled, this);

                if (this._handle && this._handle.isValid) {
                  this._handle.node.on(SystemEventType.TOUCH_START, this._onHandleDragStart, this);

                  this._handle.node.on(SystemEventType.TOUCH_MOVE, this._onTouchMoved, this);

                  this._handle.node.on(SystemEventType.TOUCH_END, this._onTouchEnded, this);
                }
              };

              _proto.onDisable = function onDisable() {
                this.node.off(SystemEventType.TOUCH_START, this._onTouchBegan, this);
                this.node.off(SystemEventType.TOUCH_MOVE, this._onTouchMoved, this);
                this.node.off(SystemEventType.TOUCH_END, this._onTouchEnded, this);
                this.node.off(SystemEventType.TOUCH_CANCEL, this._onTouchCancelled, this);

                if (this._handle && this._handle.isValid) {
                  this._handle.node.off(SystemEventType.TOUCH_START, this._onHandleDragStart, this);

                  this._handle.node.off(SystemEventType.TOUCH_MOVE, this._onTouchMoved, this);

                  this._handle.node.off(SystemEventType.TOUCH_END, this._onTouchEnded, this);
                }
              };

              _proto._onHandleDragStart = function _onHandleDragStart(event) {
                if (!event || !this._handle || !this._handle.node._uiProps.uiTransformComp) {
                  return;
                }

                this._dragging = true;
                this._touchHandle = true;
                var touhPos = event.touch.getUILocation();
                Vec3.set(this._touchPos, touhPos.x, touhPos.y, 0);

                this._handle.node._uiProps.uiTransformComp.convertToNodeSpaceAR(this._touchPos, this._offset);

                event.propagationStopped = true;
              };

              _proto._onTouchBegan = function _onTouchBegan(event) {
                if (!this._handle || !event) {
                  return;
                }

                this._dragging = true;

                if (!this._touchHandle) {
                  this._handleSliderLogic(event.touch);
                }

                event.propagationStopped = true;
              };

              _proto._onTouchMoved = function _onTouchMoved(event) {
                if (!this._dragging || !event) {
                  return;
                }

                this._handleSliderLogic(event.touch);

                event.propagationStopped = true;
              };

              _proto._onTouchEnded = function _onTouchEnded(event) {
                this._dragging = false;
                this._touchHandle = false;
                this._offset = new Vec3();

                if (event) {
                  event.propagationStopped = true;
                }
              };

              _proto._onTouchCancelled = function _onTouchCancelled(event) {
                this._dragging = false;

                if (event) {
                  event.propagationStopped = true;
                }
              };

              _proto._handleSliderLogic = function _handleSliderLogic(touch) {
                this._updateProgress(touch);

                this._emitSlideEvent();
              };

              _proto._emitSlideEvent = function _emitSlideEvent() {
                EventHandler.emitEvents(this.slideEvents, this);
                this.node.emit('slide', this);
              };

              _proto._updateProgress = function _updateProgress(touch) {
                if (!this._handle || !touch) {
                  return;
                }

                var touchPos = touch.getUILocation();
                Vec3.set(this._touchPos, touchPos.x, touchPos.y, 0);
                var uiTrans = this.node._uiProps.uiTransformComp;
                var localTouchPos = uiTrans.convertToNodeSpaceAR(this._touchPos, _tempPos);

                if (this.direction === Direction$1.Horizontal) {
                  this.progress = clamp01(0.5 + (localTouchPos.x - this._offset.x) / uiTrans.width);
                } else {
                  this.progress = clamp01(0.5 + (localTouchPos.y - this._offset.y) / uiTrans.height);
                }
              };

              _proto._updateHandlePosition = function _updateHandlePosition() {
                if (!this._handle) {
                  return;
                }

                this._handleLocalPos.set(this._handle.node.getPosition());

                var uiTrans = this.node._uiProps.uiTransformComp;

                if (this._direction === Direction$1.Horizontal) {
                  this._handleLocalPos.x = -uiTrans.width * uiTrans.anchorX + this.progress * uiTrans.width;
                } else {
                  this._handleLocalPos.y = -uiTrans.height * uiTrans.anchorY + this.progress * uiTrans.height;
                }

                this._handle.node.setPosition(this._handleLocalPos);
              };

              _proto._changeLayout = function _changeLayout() {
                var uiTrans = this.node._uiProps.uiTransformComp;
                var contentSize = uiTrans.contentSize;
                uiTrans.setContentSize(contentSize.height, contentSize.width);

                if (this._handle) {
                  var pos = this._handle.node.position;

                  if (this._direction === Direction$1.Horizontal) {
                    this._handle.node.setPosition(pos.x, 0, pos.z);
                  } else {
                    this._handle.node.setPosition(0, pos.y, pos.z);
                  }

                  this._updateHandlePosition();
                }
              };

              _createClass(Slider, [{
                key: "handle",
                get: function get() {
                  return this._handle;
                },
                set: function set(value) {
                  if (this._handle === value) {
                    return;
                  }

                  this._handle = value;
                }
              }, {
                key: "direction",
                get: function get() {
                  return this._direction;
                },
                set: function set(value) {
                  if (this._direction === value) {
                    return;
                  }

                  this._direction = value;

                  this._changeLayout();
                }
              }, {
                key: "progress",
                get: function get() {
                  return this._progress;
                },
                set: function set(value) {
                  if (this._progress === value) {
                    return;
                  }

                  this._progress = value;

                  this._updateHandlePosition();
                }
              }]);

              return Slider;
            }(Component), _class3$v.Direction = Direction$1, _temp$18), (_applyDecoratedDescriptor(_class2$15.prototype, "handle", [_dec6$n, _dec7$l], Object.getOwnPropertyDescriptor(_class2$15.prototype, "handle"), _class2$15.prototype), _applyDecoratedDescriptor(_class2$15.prototype, "direction", [_dec8$k, _dec9$h], Object.getOwnPropertyDescriptor(_class2$15.prototype, "direction"), _class2$15.prototype), _applyDecoratedDescriptor(_class2$15.prototype, "progress", [slide, _dec10$g, _dec11$f], Object.getOwnPropertyDescriptor(_class2$15.prototype, "progress"), _class2$15.prototype), _descriptor$W = _applyDecoratedDescriptor(_class2$15.prototype, "slideEvents", [_dec12$f, serializable, _dec13$e], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor2$H = _applyDecoratedDescriptor(_class2$15.prototype, "_handle", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor3$v = _applyDecoratedDescriptor(_class2$15.prototype, "_direction", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return Direction$1.Horizontal;
              }
            }), _descriptor4$r = _applyDecoratedDescriptor(_class2$15.prototype, "_progress", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0.1;
              }
            })), _class2$15)) || _class$1e) || _class$1e) || _class$1e) || _class$1e) || _class$1e));

            function extendsEnum() {
              for (var _len = arguments.length, enums = new Array(_len), _key = 0; _key < _len; _key++) {
                enums[_key] = arguments[_key];
              }

              return Object.assign.apply(Object, [{}].concat(enums));
            }

            var _dec$1e, _dec2$Q, _dec3$H, _dec4$B, _dec5$u, _dec6$o, _dec7$m, _dec8$l, _dec9$i, _dec10$h, _dec11$g, _dec12$g, _class$1f, _class2$16, _descriptor$X, _descriptor2$I, _descriptor3$w, _class3$w, _temp$19;
            var EventType$5;

            (function (EventType) {
              EventType["TOGGLE"] = "toggle";
            })(EventType$5 || (EventType$5 = {}));

            var Toggle = function (v) { return exports({ Toggle: v, ToggleComponent: v }), v; }((_dec$1e = ccclass('cc.Toggle'), _dec2$Q = help(), _dec3$H = executionOrder(110), _dec4$B = menu(), _dec5$u = requireComponent(UITransform), _dec6$o = displayOrder(), _dec7$m = tooltip(), _dec8$l = type(Sprite), _dec9$i = displayOrder(), _dec10$h = tooltip(), _dec11$g = type([EventHandler]), _dec12$g = tooltip(), _dec$1e(_class$1f = _dec2$Q(_class$1f = _dec3$H(_class$1f = _dec4$B(_class$1f = _dec5$u(_class$1f = (_class2$16 = (_temp$19 = _class3$w = function (_Button) {
              _inheritsLoose(Toggle, _Button);

              function Toggle() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Button.call.apply(_Button, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "checkEvents", _descriptor$X, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_isChecked", _descriptor2$I, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_checkMark", _descriptor3$w, _assertThisInitialized(_this));

                return _this;
              }

              var _proto = Toggle.prototype;

              _proto._internalToggle = function _internalToggle() {
                this.isChecked = !this.isChecked;
              };

              _proto._set = function _set(value, emitEvent) {
                if (emitEvent === void 0) {
                  emitEvent = true;
                }

                if (this._isChecked == value) return;
                this._isChecked = value;
                var group = this._toggleContainer;

                if (group && group.enabled && this.enabled) {
                  if (value || !group.anyTogglesChecked() && !group.allowSwitchOff) {
                    this._isChecked = true;
                    group.notifyToggleCheck(this, emitEvent);
                  }
                }

                this.playEffect();

                if (emitEvent) {
                  this._emitToggleEvents();
                }
              };

              _proto.playEffect = function playEffect() {
                if (this._checkMark) {
                  this._checkMark.node.active = this._isChecked;
                }
              };

              _proto.setIsCheckedWithoutNotify = function setIsCheckedWithoutNotify(value) {
                this._set(value, false);
              };

              _proto.onEnable = function onEnable() {
                _Button.prototype.onEnable.call(this);

                this.playEffect();

                {
                  this.node.on(Toggle.EventType.CLICK, this._internalToggle, this);
                }
              };

              _proto.onDisable = function onDisable() {
                _Button.prototype.onDisable.call(this);

                {
                  this.node.off(Toggle.EventType.CLICK, this._internalToggle, this);
                }
              };

              _proto.OnDestroy = function OnDestroy() {
                var group = this._toggleContainer;

                if (group) {
                  group.ensureValidState();
                }
              };

              _proto._emitToggleEvents = function _emitToggleEvents() {
                this.node.emit(Toggle.EventType.TOGGLE, this);

                if (this.checkEvents) {
                  EventHandler.emitEvents(this.checkEvents, this);
                }
              };

              _createClass(Toggle, [{
                key: "isChecked",
                get: function get() {
                  return this._isChecked;
                },
                set: function set(value) {
                  this._set(value);
                }
              }, {
                key: "checkMark",
                get: function get() {
                  return this._checkMark;
                },
                set: function set(value) {
                  if (this._checkMark === value) {
                    return;
                  }

                  this._checkMark = value;
                }
              }, {
                key: "_resizeToTarget",
                set: function set(value) {
                  if (value) {
                    this._resizeNodeToTargetNode();
                  }
                }
              }, {
                key: "_toggleContainer",
                get: function get() {
                  var parent = this.node.parent;

                  if (legacyCC.Node.isNode(parent)) {
                    return parent.getComponent('cc.ToggleContainer');
                  }

                  return null;
                }
              }]);

              return Toggle;
            }(Button), _class3$w.EventType = extendsEnum(EventType$5, EventType$2), _temp$19), (_applyDecoratedDescriptor(_class2$16.prototype, "isChecked", [_dec6$o, _dec7$m], Object.getOwnPropertyDescriptor(_class2$16.prototype, "isChecked"), _class2$16.prototype), _applyDecoratedDescriptor(_class2$16.prototype, "checkMark", [_dec8$l, _dec9$i, _dec10$h], Object.getOwnPropertyDescriptor(_class2$16.prototype, "checkMark"), _class2$16.prototype), _descriptor$X = _applyDecoratedDescriptor(_class2$16.prototype, "checkEvents", [_dec11$g, serializable, _dec12$g], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor2$I = _applyDecoratedDescriptor(_class2$16.prototype, "_isChecked", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _descriptor3$w = _applyDecoratedDescriptor(_class2$16.prototype, "_checkMark", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            })), _class2$16)) || _class$1f) || _class$1f) || _class$1f) || _class$1f) || _class$1f));

            var _dec$1f, _dec2$R, _dec3$I, _dec4$C, _dec5$v, _dec6$p, _dec7$n, _class$1g, _class2$17, _descriptor$Y, _descriptor2$J, _temp$1a;
            var ToggleContainer = function (v) { return exports({ ToggleContainer: v, ToggleContainerComponent: v }), v; }((_dec$1f = ccclass('cc.ToggleContainer'), _dec2$R = help(), _dec3$I = executionOrder(110), _dec4$C = menu(), _dec5$v = tooltip(), _dec6$p = type([EventHandler]), _dec7$n = tooltip(), _dec$1f(_class$1g = _dec2$R(_class$1g = _dec3$I(_class$1g = _dec4$C(_class$1g = executeInEditMode(_class$1g = (_class2$17 = (_temp$1a = function (_Component) {
              _inheritsLoose(ToggleContainer, _Component);

              function ToggleContainer() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Component.call.apply(_Component, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "_allowSwitchOff", _descriptor$Y, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "checkEvents", _descriptor2$J, _assertThisInitialized(_this));

                return _this;
              }

              var _proto = ToggleContainer.prototype;

              _proto.onEnable = function onEnable() {
                this.ensureValidState();
                this.node.on(SystemEventType.CHILD_ADDED, this.ensureValidState, this);
                this.node.on(SystemEventType.CHILD_REMOVED, this.ensureValidState, this);
              };

              _proto.onDisable = function onDisable() {
                this.node.off(SystemEventType.CHILD_ADDED, this.ensureValidState, this);
                this.node.off(SystemEventType.CHILD_REMOVED, this.ensureValidState, this);
              };

              _proto.activeToggles = function activeToggles() {
                return this.toggleItems.filter(function (x) {
                  return x.isChecked;
                });
              };

              _proto.anyTogglesChecked = function anyTogglesChecked() {
                return !!this.toggleItems.find(function (x) {
                  return x.isChecked;
                });
              };

              _proto.notifyToggleCheck = function notifyToggleCheck(toggle, emitEvent) {
                if (emitEvent === void 0) {
                  emitEvent = true;
                }

                if (!this.enabledInHierarchy) {
                  return;
                }

                for (var i = 0; i < this.toggleItems.length; i++) {
                  var item = this.toggleItems[i];

                  if (item === toggle) {
                    continue;
                  }

                  if (emitEvent) {
                    item.isChecked = false;
                  } else {
                    item.setIsCheckedWithoutNotify(false);
                  }
                }

                if (this.checkEvents) {
                  legacyCC.Component.EventHandler.emitEvents(this.checkEvents, toggle);
                }
              };

              _proto.ensureValidState = function ensureValidState() {
                var toggles = this.toggleItems;

                if (!this._allowSwitchOff && !this.anyTogglesChecked() && toggles.length !== 0) {
                  var toggle = toggles[0];
                  toggle.isChecked = true;
                  this.notifyToggleCheck(toggle);
                }

                var activeToggles = this.activeToggles();

                if (activeToggles.length > 1) {
                  var firstToggle = activeToggles[0];

                  for (var i = 0; i < activeToggles.length; ++i) {
                    var _toggle = activeToggles[i];

                    if (_toggle === firstToggle) {
                      continue;
                    }

                    _toggle.isChecked = false;
                  }
                }
              };

              _createClass(ToggleContainer, [{
                key: "allowSwitchOff",
                get: function get() {
                  return this._allowSwitchOff;
                },
                set: function set(value) {
                  this._allowSwitchOff = value;
                }
              }, {
                key: "toggleItems",
                get: function get() {
                  return this.node.children.map(function (item) {
                    var toggle = item.getComponent('cc.Toggle');

                    if (toggle && toggle.enabled) {
                      return toggle;
                    }

                    return null;
                  }).filter(Boolean);
                }
              }]);

              return ToggleContainer;
            }(Component), _temp$1a), (_descriptor$Y = _applyDecoratedDescriptor(_class2$17.prototype, "_allowSwitchOff", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _applyDecoratedDescriptor(_class2$17.prototype, "allowSwitchOff", [_dec5$v], Object.getOwnPropertyDescriptor(_class2$17.prototype, "allowSwitchOff"), _class2$17.prototype), _descriptor2$J = _applyDecoratedDescriptor(_class2$17.prototype, "checkEvents", [_dec6$p, serializable, _dec7$n], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            })), _class2$17)) || _class$1g) || _class$1g) || _class$1g) || _class$1g) || _class$1g));

            var _dec$1g, _dec2$S, _dec3$J, _dec4$D, _dec5$w, _dec6$q, _dec7$o, _dec8$m, _dec9$j, _dec10$i, _dec11$h, _dec12$h, _dec13$f, _dec14$d, _dec15$d, _dec16$c, _dec17$b, _dec18$b, _dec19$b, _dec20$a, _dec21$a, _dec22$a, _dec23$a, _class$1h, _class2$18, _descriptor$Z, _descriptor2$K, _descriptor3$x, _descriptor4$s, _descriptor5$n, _descriptor6$f, _descriptor7$d, _descriptor8$d, _descriptor9$c, _descriptor10$c, _descriptor11$b, _descriptor12$9, _descriptor13$8, _descriptor14$7, _descriptor15$6, _descriptor16$6, _descriptor17$4, _descriptor18$4, _class3$x, _temp$1b;

            var _tempScale = new Vec2();

            function getReadonlyNodeSize(parent) {
              if (parent instanceof Scene) {

                return visibleRect;
              } else if (parent._uiProps.uiTransformComp) {
                return parent._uiProps.uiTransformComp.contentSize;
              } else {
                return Size.ZERO;
              }
            }
            function computeInverseTransForTarget(widgetNode, target, out_inverseTranslate, out_inverseScale) {
              if (widgetNode.parent) {
                _tempScale.set(widgetNode.parent.getScale().x, widgetNode.parent.getScale().y);
              } else {
                _tempScale.set(0, 0);
              }

              var scaleX = _tempScale.x;
              var scaleY = _tempScale.y;
              var translateX = 0;
              var translateY = 0;

              for (var node = widgetNode.parent;;) {
                if (!node) {
                  out_inverseTranslate.x = out_inverseTranslate.y = 0;
                  out_inverseScale.x = out_inverseScale.y = 1;
                  return;
                }

                var pos = node.getPosition();
                translateX += pos.x;
                translateY += pos.y;
                node = node.parent;

                if (node !== target) {
                  if (node) {
                    _tempScale.set(node.getScale().x, node.getScale().y);
                  } else {
                    _tempScale.set(0, 0);
                  }

                  var sx = _tempScale.x;
                  var sy = _tempScale.y;
                  translateX *= sx;
                  translateY *= sy;
                  scaleX *= sx;
                  scaleY *= sy;
                } else {
                  break;
                }
              }

              out_inverseScale.x = scaleX !== 0 ? 1 / scaleX : 1;
              out_inverseScale.y = scaleY !== 0 ? 1 / scaleY : 1;
              out_inverseTranslate.x = -translateX;
              out_inverseTranslate.y = -translateY;
            }
            var AlignMode;

            (function (AlignMode) {
              AlignMode[AlignMode["ONCE"] = 0] = "ONCE";
              AlignMode[AlignMode["ALWAYS"] = 1] = "ALWAYS";
              AlignMode[AlignMode["ON_WINDOW_RESIZE"] = 2] = "ON_WINDOW_RESIZE";
            })(AlignMode || (AlignMode = {}));

            ccenum(AlignMode);
            var AlignFlags;

            (function (AlignFlags) {
              AlignFlags[AlignFlags["TOP"] = 1] = "TOP";
              AlignFlags[AlignFlags["MID"] = 2] = "MID";
              AlignFlags[AlignFlags["BOT"] = 4] = "BOT";
              AlignFlags[AlignFlags["LEFT"] = 8] = "LEFT";
              AlignFlags[AlignFlags["CENTER"] = 16] = "CENTER";
              AlignFlags[AlignFlags["RIGHT"] = 32] = "RIGHT";
              AlignFlags[AlignFlags["HORIZONTAL"] = 56] = "HORIZONTAL";
              AlignFlags[AlignFlags["VERTICAL"] = 7] = "VERTICAL";
            })(AlignFlags || (AlignFlags = {}));

            var TOP_BOT = AlignFlags.TOP | AlignFlags.BOT;
            var LEFT_RIGHT = AlignFlags.LEFT | AlignFlags.RIGHT;
            var Widget = function (v) { return exports({ Widget: v, WidgetComponent: v }), v; }((_dec$1g = ccclass('cc.Widget'), _dec2$S = help(), _dec3$J = executionOrder(110), _dec4$D = menu(), _dec5$w = requireComponent(UITransform), _dec6$q = type(Node$1), _dec7$o = tooltip(), _dec8$m = tooltip(), _dec9$j = tooltip(), _dec10$i = tooltip(), _dec11$h = tooltip(), _dec12$h = tooltip(), _dec13$f = tooltip(), _dec14$d = visible(), _dec15$d = visible(), _dec16$c = tooltip(), _dec17$b = tooltip(), _dec18$b = tooltip(), _dec19$b = tooltip(), _dec20$a = tooltip(), _dec21$a = tooltip(), _dec22$a = type(AlignMode), _dec23$a = tooltip(), _dec$1g(_class$1h = _dec2$S(_class$1h = _dec3$J(_class$1h = _dec4$D(_class$1h = _dec5$w(_class$1h = executeInEditMode(_class$1h = (_class2$18 = (_temp$1b = _class3$x = function (_Component) {
              _inheritsLoose(Widget, _Component);

              function Widget() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Component.call.apply(_Component, [this].concat(args)) || this;
                _this._lastPos = new Vec3();
                _this._lastSize = new Size();
                _this._dirty = true;
                _this._hadAlignOnce = false;

                _initializerDefineProperty(_this, "_alignFlags", _descriptor$Z, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_target", _descriptor2$K, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_left", _descriptor3$x, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_right", _descriptor4$s, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_top", _descriptor5$n, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_bottom", _descriptor6$f, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_horizontalCenter", _descriptor7$d, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_verticalCenter", _descriptor8$d, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_isAbsLeft", _descriptor9$c, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_isAbsRight", _descriptor10$c, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_isAbsTop", _descriptor11$b, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_isAbsBottom", _descriptor12$9, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_isAbsHorizontalCenter", _descriptor13$8, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_isAbsVerticalCenter", _descriptor14$7, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_originalWidth", _descriptor15$6, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_originalHeight", _descriptor16$6, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_alignMode", _descriptor17$4, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_lockFlags", _descriptor18$4, _assertThisInitialized(_this));

                return _this;
              }

              var _proto = Widget.prototype;

              _proto.updateAlignment = function updateAlignment() {
                legacyCC._widgetManager.updateAlignment(this.node);
              };

              _proto._validateTargetInDEV = function _validateTargetInDEV() {
                {
                  return;
                }
              };

              _proto.setDirty = function setDirty() {
                this._recursiveDirty();
              };

              _proto.onEnable = function onEnable() {
                this.node.getPosition(this._lastPos);

                this._lastSize.set(this.node._uiProps.uiTransformComp.contentSize);

                legacyCC._widgetManager.add(this);

                this._hadAlignOnce = false;

                this._registerEvent();

                this._registerTargetEvents();
              };

              _proto.onDisable = function onDisable() {
                legacyCC._widgetManager.remove(this);

                this._unregisterEvent();

                this._unregisterTargetEvents();
              };

              _proto.onDestroy = function onDestroy() {
                this._removeParentEvent();
              };

              _proto._adjustWidgetToAllowMovingInEditor = function _adjustWidgetToAllowMovingInEditor(eventType) {};

              _proto._adjustWidgetToAllowResizingInEditor = function _adjustWidgetToAllowResizingInEditor() {};

              _proto._adjustWidgetToAnchorChanged = function _adjustWidgetToAnchorChanged() {
                this.setDirty();
              };

              _proto._adjustTargetToParentChanged = function _adjustTargetToParentChanged(oldParent) {
                if (oldParent) {
                  this._unregisterOldParentEvents(oldParent);
                }

                if (this.node.getParent()) {
                  this._registerTargetEvents();
                }

                this._setDirtyByMode();
              };

              _proto._registerEvent = function _registerEvent() {
                {
                  this.node.on(SystemEventType.TRANSFORM_CHANGED, this._setDirtyByMode, this);
                  this.node.on(SystemEventType.SIZE_CHANGED, this._setDirtyByMode, this);
                }

                this.node.on(SystemEventType.ANCHOR_CHANGED, this._adjustWidgetToAnchorChanged, this);
                this.node.on(SystemEventType.PARENT_CHANGED, this._adjustTargetToParentChanged, this);
              };

              _proto._unregisterEvent = function _unregisterEvent() {
                {
                  this.node.off(SystemEventType.TRANSFORM_CHANGED, this._setDirtyByMode, this);
                  this.node.off(SystemEventType.SIZE_CHANGED, this._setDirtyByMode, this);
                }

                this.node.off(SystemEventType.ANCHOR_CHANGED, this._adjustWidgetToAnchorChanged, this);
              };

              _proto._removeParentEvent = function _removeParentEvent() {
                this.node.off(SystemEventType.PARENT_CHANGED, this._adjustTargetToParentChanged, this);
              };

              _proto._autoChangedValue = function _autoChangedValue(flag, isAbs) {
                var current = (this._alignFlags & flag) > 0;

                if (!current) {
                  return;
                }

                var parentUiProps = this.node.parent && this.node.parent._uiProps;
                var parentTrans = parentUiProps && parentUiProps.uiTransformComp;
                var size = parentTrans ? parentTrans.contentSize : visibleRect;

                if (this.isAlignLeft && flag === AlignFlags.LEFT) {
                  this._left = isAbs ? this._left * size.width : this._left / size.width;
                } else if (this.isAlignRight && flag === AlignFlags.RIGHT) {
                  this._right = isAbs ? this._right * size.width : this._right / size.width;
                } else if (this.isAlignHorizontalCenter && flag === AlignFlags.CENTER) {
                  this._horizontalCenter = isAbs ? this._horizontalCenter * size.width : this._horizontalCenter / size.width;
                } else if (this.isAlignTop && flag === AlignFlags.TOP) {
                  this._top = isAbs ? this._top * size.height : this._top / size.height;
                } else if (this.isAlignBottom && flag === AlignFlags.BOT) {
                  this._bottom = isAbs ? this._bottom * size.height : this._bottom / size.height;
                } else if (this.isAbsoluteVerticalCenter && flag === AlignFlags.MID) {
                  this._verticalCenter = isAbs ? this._verticalCenter / size.height : this._verticalCenter / size.height;
                }

                this._recursiveDirty();
              };

              _proto._registerTargetEvents = function _registerTargetEvents() {
                var target = this._target || this.node.parent;

                if (target) {
                  if (target.getComponent(UITransform)) {
                    target.on(SystemEventType.TRANSFORM_CHANGED, this._setDirtyByMode, this);
                    target.on(SystemEventType.SIZE_CHANGED, this._setDirtyByMode, this);
                  }
                }
              };

              _proto._unregisterTargetEvents = function _unregisterTargetEvents() {
                var target = this._target || this.node.parent;

                if (target) {
                  target.off(SystemEventType.TRANSFORM_CHANGED, this._setDirtyByMode, this);
                  target.off(SystemEventType.SIZE_CHANGED, this._setDirtyByMode, this);
                }
              };

              _proto._unregisterOldParentEvents = function _unregisterOldParentEvents(oldParent) {
                var target = this._target || oldParent;

                if (target) {
                  target.off(SystemEventType.TRANSFORM_CHANGED, this._setDirtyByMode, this);
                  target.off(SystemEventType.SIZE_CHANGED, this._setDirtyByMode, this);
                }
              };

              _proto._setDirtyByMode = function _setDirtyByMode() {
                if (this.alignMode === AlignMode.ALWAYS) {
                  this._recursiveDirty();
                }
              };

              _proto._setAlign = function _setAlign(flag, isAlign) {
                var current = (this._alignFlags & flag) > 0;

                if (isAlign === current) {
                  return;
                }

                var isHorizontal = (flag & LEFT_RIGHT) > 0;
                var trans = this.node._uiProps.uiTransformComp;

                if (isAlign) {
                  this._alignFlags |= flag;

                  if (isHorizontal) {
                    this.isAlignHorizontalCenter = false;

                    if (this.isStretchWidth) {
                      this._originalWidth = trans.width;
                    }
                  } else {
                    this.isAlignVerticalCenter = false;

                    if (this.isStretchHeight) {
                      this._originalHeight = trans.height;
                    }
                  }
                } else {
                  if (isHorizontal) {
                    if (this.isStretchWidth) {
                      trans.width = this._originalWidth;
                    }
                  } else if (this.isStretchHeight) {
                    trans.height = this._originalHeight;
                  }

                  this._alignFlags &= ~flag;
                }
              };

              _proto._recursiveDirty = function _recursiveDirty() {
                if (this._dirty) {
                  return;
                }

                this._dirty = true;
              };

              _createClass(Widget, [{
                key: "target",
                get: function get() {
                  return this._target;
                },
                set: function set(value) {
                  if (this._target === value) {
                    return;
                  }

                  this._unregisterTargetEvents();

                  this._target = value;

                  this._registerTargetEvents();

                  this._validateTargetInDEV();

                  this._recursiveDirty();
                }
              }, {
                key: "isAlignTop",
                get: function get() {
                  return (this._alignFlags & AlignFlags.TOP) > 0;
                },
                set: function set(value) {
                  this._setAlign(AlignFlags.TOP, value);

                  this._recursiveDirty();
                }
              }, {
                key: "isAlignBottom",
                get: function get() {
                  return (this._alignFlags & AlignFlags.BOT) > 0;
                },
                set: function set(value) {
                  this._setAlign(AlignFlags.BOT, value);

                  this._recursiveDirty();
                }
              }, {
                key: "isAlignLeft",
                get: function get() {
                  return (this._alignFlags & AlignFlags.LEFT) > 0;
                },
                set: function set(value) {
                  this._setAlign(AlignFlags.LEFT, value);

                  this._recursiveDirty();
                }
              }, {
                key: "isAlignRight",
                get: function get() {
                  return (this._alignFlags & AlignFlags.RIGHT) > 0;
                },
                set: function set(value) {
                  this._setAlign(AlignFlags.RIGHT, value);

                  this._recursiveDirty();
                }
              }, {
                key: "isAlignVerticalCenter",
                get: function get() {
                  return (this._alignFlags & AlignFlags.MID) > 0;
                },
                set: function set(value) {
                  if (value) {
                    this.isAlignTop = false;
                    this.isAlignBottom = false;
                    this._alignFlags |= AlignFlags.MID;
                  } else {
                    this._alignFlags &= ~AlignFlags.MID;
                  }

                  this._recursiveDirty();
                }
              }, {
                key: "isAlignHorizontalCenter",
                get: function get() {
                  return (this._alignFlags & AlignFlags.CENTER) > 0;
                },
                set: function set(value) {
                  if (value) {
                    this.isAlignLeft = false;
                    this.isAlignRight = false;
                    this._alignFlags |= AlignFlags.CENTER;
                  } else {
                    this._alignFlags &= ~AlignFlags.CENTER;
                  }

                  this._recursiveDirty();
                }
              }, {
                key: "isStretchWidth",
                get: function get() {
                  return (this._alignFlags & LEFT_RIGHT) === LEFT_RIGHT;
                }
              }, {
                key: "isStretchHeight",
                get: function get() {
                  return (this._alignFlags & TOP_BOT) === TOP_BOT;
                }
              }, {
                key: "top",
                get: function get() {
                  return this._top;
                },
                set: function set(value) {
                  this._top = value;

                  this._recursiveDirty();
                }
              }, {
                key: "editorTop",
                get: function get() {
                  return this._isAbsTop ? this._top : this._top * 100;
                },
                set: function set(value) {
                  this._top = this._isAbsTop ? value : value / 100;

                  this._recursiveDirty();
                }
              }, {
                key: "bottom",
                get: function get() {
                  return this._bottom;
                },
                set: function set(value) {
                  this._bottom = value;

                  this._recursiveDirty();
                }
              }, {
                key: "editorBottom",
                get: function get() {
                  return this._isAbsBottom ? this._bottom : this._bottom * 100;
                },
                set: function set(value) {
                  this._bottom = this._isAbsBottom ? value : value / 100;

                  this._recursiveDirty();
                }
              }, {
                key: "left",
                get: function get() {
                  return this._left;
                },
                set: function set(value) {
                  this._left = value;

                  this._recursiveDirty();
                }
              }, {
                key: "editorLeft",
                get: function get() {
                  return this._isAbsLeft ? this._left : this._left * 100;
                },
                set: function set(value) {
                  this._left = this._isAbsLeft ? value : value / 100;

                  this._recursiveDirty();
                }
              }, {
                key: "right",
                get: function get() {
                  return this._right;
                },
                set: function set(value) {
                  this._right = value;

                  this._recursiveDirty();
                }
              }, {
                key: "editorRight",
                get: function get() {
                  return this._isAbsRight ? this._right : this._right * 100;
                },
                set: function set(value) {
                  this._right = this._isAbsRight ? value : value / 100;

                  this._recursiveDirty();
                }
              }, {
                key: "horizontalCenter",
                get: function get() {
                  return this._horizontalCenter;
                },
                set: function set(value) {
                  this._horizontalCenter = value;

                  this._recursiveDirty();
                }
              }, {
                key: "editorHorizontalCenter",
                get: function get() {
                  return this._isAbsHorizontalCenter ? this._horizontalCenter : this._horizontalCenter * 100;
                },
                set: function set(value) {
                  this._horizontalCenter = this._isAbsHorizontalCenter ? value : value / 100;

                  this._recursiveDirty();
                }
              }, {
                key: "verticalCenter",
                get: function get() {
                  return this._verticalCenter;
                },
                set: function set(value) {
                  this._verticalCenter = value;

                  this._recursiveDirty();
                }
              }, {
                key: "editorVerticalCenter",
                get: function get() {
                  return this._isAbsVerticalCenter ? this._verticalCenter : this._verticalCenter * 100;
                },
                set: function set(value) {
                  this._verticalCenter = this._isAbsVerticalCenter ? value : value / 100;

                  this._recursiveDirty();
                }
              }, {
                key: "isAbsoluteTop",
                get: function get() {
                  return this._isAbsTop;
                },
                set: function set(value) {
                  if (this._isAbsTop === value) {
                    return;
                  }

                  this._isAbsTop = value;

                  this._autoChangedValue(AlignFlags.TOP, this._isAbsTop);
                }
              }, {
                key: "isAbsoluteBottom",
                get: function get() {
                  return this._isAbsBottom;
                },
                set: function set(value) {
                  if (this._isAbsBottom === value) {
                    return;
                  }

                  this._isAbsBottom = value;

                  this._autoChangedValue(AlignFlags.BOT, this._isAbsBottom);
                }
              }, {
                key: "isAbsoluteLeft",
                get: function get() {
                  return this._isAbsLeft;
                },
                set: function set(value) {
                  if (this._isAbsLeft === value) {
                    return;
                  }

                  this._isAbsLeft = value;

                  this._autoChangedValue(AlignFlags.LEFT, this._isAbsLeft);
                }
              }, {
                key: "isAbsoluteRight",
                get: function get() {
                  return this._isAbsRight;
                },
                set: function set(value) {
                  if (this._isAbsRight === value) {
                    return;
                  }

                  this._isAbsRight = value;

                  this._autoChangedValue(AlignFlags.RIGHT, this._isAbsRight);
                }
              }, {
                key: "isAbsoluteHorizontalCenter",
                get: function get() {
                  return this._isAbsHorizontalCenter;
                },
                set: function set(value) {
                  if (this._isAbsHorizontalCenter === value) {
                    return;
                  }

                  this._isAbsHorizontalCenter = value;

                  this._autoChangedValue(AlignFlags.CENTER, this._isAbsHorizontalCenter);
                }
              }, {
                key: "isAbsoluteVerticalCenter",
                get: function get() {
                  return this._isAbsVerticalCenter;
                },
                set: function set(value) {
                  if (this._isAbsVerticalCenter === value) {
                    return;
                  }

                  this._isAbsVerticalCenter = value;

                  this._autoChangedValue(AlignFlags.MID, this._isAbsVerticalCenter);
                }
              }, {
                key: "alignMode",
                get: function get() {
                  return this._alignMode;
                },
                set: function set(value) {
                  this._alignMode = value;

                  this._recursiveDirty();
                }
              }, {
                key: "alignFlags",
                get: function get() {
                  return this._alignFlags;
                },
                set: function set(value) {
                  if (this._alignFlags === value) {
                    return;
                  }

                  this._alignFlags = value;

                  this._recursiveDirty();
                }
              }]);

              return Widget;
            }(Component), _class3$x.AlignMode = AlignMode, _temp$1b), (_applyDecoratedDescriptor(_class2$18.prototype, "target", [_dec6$q, _dec7$o], Object.getOwnPropertyDescriptor(_class2$18.prototype, "target"), _class2$18.prototype), _applyDecoratedDescriptor(_class2$18.prototype, "isAlignTop", [_dec8$m], Object.getOwnPropertyDescriptor(_class2$18.prototype, "isAlignTop"), _class2$18.prototype), _applyDecoratedDescriptor(_class2$18.prototype, "isAlignBottom", [_dec9$j], Object.getOwnPropertyDescriptor(_class2$18.prototype, "isAlignBottom"), _class2$18.prototype), _applyDecoratedDescriptor(_class2$18.prototype, "isAlignLeft", [_dec10$i], Object.getOwnPropertyDescriptor(_class2$18.prototype, "isAlignLeft"), _class2$18.prototype), _applyDecoratedDescriptor(_class2$18.prototype, "isAlignRight", [_dec11$h], Object.getOwnPropertyDescriptor(_class2$18.prototype, "isAlignRight"), _class2$18.prototype), _applyDecoratedDescriptor(_class2$18.prototype, "isAlignVerticalCenter", [_dec12$h], Object.getOwnPropertyDescriptor(_class2$18.prototype, "isAlignVerticalCenter"), _class2$18.prototype), _applyDecoratedDescriptor(_class2$18.prototype, "isAlignHorizontalCenter", [_dec13$f], Object.getOwnPropertyDescriptor(_class2$18.prototype, "isAlignHorizontalCenter"), _class2$18.prototype), _applyDecoratedDescriptor(_class2$18.prototype, "isStretchWidth", [_dec14$d], Object.getOwnPropertyDescriptor(_class2$18.prototype, "isStretchWidth"), _class2$18.prototype), _applyDecoratedDescriptor(_class2$18.prototype, "isStretchHeight", [_dec15$d], Object.getOwnPropertyDescriptor(_class2$18.prototype, "isStretchHeight"), _class2$18.prototype), _applyDecoratedDescriptor(_class2$18.prototype, "top", [_dec16$c], Object.getOwnPropertyDescriptor(_class2$18.prototype, "top"), _class2$18.prototype), _applyDecoratedDescriptor(_class2$18.prototype, "editorTop", [editable], Object.getOwnPropertyDescriptor(_class2$18.prototype, "editorTop"), _class2$18.prototype), _applyDecoratedDescriptor(_class2$18.prototype, "bottom", [_dec17$b], Object.getOwnPropertyDescriptor(_class2$18.prototype, "bottom"), _class2$18.prototype), _applyDecoratedDescriptor(_class2$18.prototype, "editorBottom", [editable], Object.getOwnPropertyDescriptor(_class2$18.prototype, "editorBottom"), _class2$18.prototype), _applyDecoratedDescriptor(_class2$18.prototype, "left", [_dec18$b], Object.getOwnPropertyDescriptor(_class2$18.prototype, "left"), _class2$18.prototype), _applyDecoratedDescriptor(_class2$18.prototype, "editorLeft", [editable], Object.getOwnPropertyDescriptor(_class2$18.prototype, "editorLeft"), _class2$18.prototype), _applyDecoratedDescriptor(_class2$18.prototype, "right", [_dec19$b], Object.getOwnPropertyDescriptor(_class2$18.prototype, "right"), _class2$18.prototype), _applyDecoratedDescriptor(_class2$18.prototype, "editorRight", [editable], Object.getOwnPropertyDescriptor(_class2$18.prototype, "editorRight"), _class2$18.prototype), _applyDecoratedDescriptor(_class2$18.prototype, "horizontalCenter", [_dec20$a], Object.getOwnPropertyDescriptor(_class2$18.prototype, "horizontalCenter"), _class2$18.prototype), _applyDecoratedDescriptor(_class2$18.prototype, "editorHorizontalCenter", [editable], Object.getOwnPropertyDescriptor(_class2$18.prototype, "editorHorizontalCenter"), _class2$18.prototype), _applyDecoratedDescriptor(_class2$18.prototype, "verticalCenter", [_dec21$a], Object.getOwnPropertyDescriptor(_class2$18.prototype, "verticalCenter"), _class2$18.prototype), _applyDecoratedDescriptor(_class2$18.prototype, "editorVerticalCenter", [editable], Object.getOwnPropertyDescriptor(_class2$18.prototype, "editorVerticalCenter"), _class2$18.prototype), _applyDecoratedDescriptor(_class2$18.prototype, "isAbsoluteTop", [editable], Object.getOwnPropertyDescriptor(_class2$18.prototype, "isAbsoluteTop"), _class2$18.prototype), _applyDecoratedDescriptor(_class2$18.prototype, "isAbsoluteBottom", [editable], Object.getOwnPropertyDescriptor(_class2$18.prototype, "isAbsoluteBottom"), _class2$18.prototype), _applyDecoratedDescriptor(_class2$18.prototype, "isAbsoluteLeft", [editable], Object.getOwnPropertyDescriptor(_class2$18.prototype, "isAbsoluteLeft"), _class2$18.prototype), _applyDecoratedDescriptor(_class2$18.prototype, "isAbsoluteRight", [editable], Object.getOwnPropertyDescriptor(_class2$18.prototype, "isAbsoluteRight"), _class2$18.prototype), _applyDecoratedDescriptor(_class2$18.prototype, "isAbsoluteHorizontalCenter", [editable], Object.getOwnPropertyDescriptor(_class2$18.prototype, "isAbsoluteHorizontalCenter"), _class2$18.prototype), _applyDecoratedDescriptor(_class2$18.prototype, "isAbsoluteVerticalCenter", [editable], Object.getOwnPropertyDescriptor(_class2$18.prototype, "isAbsoluteVerticalCenter"), _class2$18.prototype), _applyDecoratedDescriptor(_class2$18.prototype, "alignMode", [_dec22$a, _dec23$a], Object.getOwnPropertyDescriptor(_class2$18.prototype, "alignMode"), _class2$18.prototype), _applyDecoratedDescriptor(_class2$18.prototype, "alignFlags", [editable], Object.getOwnPropertyDescriptor(_class2$18.prototype, "alignFlags"), _class2$18.prototype), _descriptor$Z = _applyDecoratedDescriptor(_class2$18.prototype, "_alignFlags", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor2$K = _applyDecoratedDescriptor(_class2$18.prototype, "_target", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor3$x = _applyDecoratedDescriptor(_class2$18.prototype, "_left", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor4$s = _applyDecoratedDescriptor(_class2$18.prototype, "_right", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor5$n = _applyDecoratedDescriptor(_class2$18.prototype, "_top", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor6$f = _applyDecoratedDescriptor(_class2$18.prototype, "_bottom", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor7$d = _applyDecoratedDescriptor(_class2$18.prototype, "_horizontalCenter", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor8$d = _applyDecoratedDescriptor(_class2$18.prototype, "_verticalCenter", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor9$c = _applyDecoratedDescriptor(_class2$18.prototype, "_isAbsLeft", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _descriptor10$c = _applyDecoratedDescriptor(_class2$18.prototype, "_isAbsRight", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _descriptor11$b = _applyDecoratedDescriptor(_class2$18.prototype, "_isAbsTop", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _descriptor12$9 = _applyDecoratedDescriptor(_class2$18.prototype, "_isAbsBottom", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _descriptor13$8 = _applyDecoratedDescriptor(_class2$18.prototype, "_isAbsHorizontalCenter", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _descriptor14$7 = _applyDecoratedDescriptor(_class2$18.prototype, "_isAbsVerticalCenter", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _descriptor15$6 = _applyDecoratedDescriptor(_class2$18.prototype, "_originalWidth", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor16$6 = _applyDecoratedDescriptor(_class2$18.prototype, "_originalHeight", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor17$4 = _applyDecoratedDescriptor(_class2$18.prototype, "_alignMode", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return AlignMode.ON_WINDOW_RESIZE;
              }
            }), _descriptor18$4 = _applyDecoratedDescriptor(_class2$18.prototype, "_lockFlags", [serializable, editorOnly], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            })), _class2$18)) || _class$1h) || _class$1h) || _class$1h) || _class$1h) || _class$1h) || _class$1h));
            legacyCC.internal.computeInverseTransForTarget = computeInverseTransForTarget;
            legacyCC.internal.getReadonlyNodeSize = getReadonlyNodeSize;

            var _dec$1h, _dec2$T, _dec3$K, _dec4$E, _dec5$x, _dec6$r, _dec7$p, _dec8$n, _dec9$k, _dec10$j, _dec11$i, _class$1i, _class2$19, _descriptor$_, _descriptor2$L, _descriptor3$y, _descriptor4$t, _class3$y, _temp$1c;

            var _color$1 = new Color();

            var Direction$2;

            (function (Direction) {
              Direction[Direction["HORIZONTAL"] = 0] = "HORIZONTAL";
              Direction[Direction["VERTICAL"] = 1] = "VERTICAL";
            })(Direction$2 || (Direction$2 = {}));

            ccenum(Direction$2);
            var PageViewIndicator = function (v) { return exports({ PageViewIndicator: v, PageViewIndicatorComponent: v }), v; }((_dec$1h = ccclass('cc.PageViewIndicator'), _dec2$T = help(), _dec3$K = executionOrder(110), _dec4$E = menu(), _dec5$x = type(SpriteFrame), _dec6$r = tooltip(), _dec7$p = type(Direction$2), _dec8$n = tooltip(), _dec9$k = type(Size), _dec10$j = tooltip(), _dec11$i = tooltip(), _dec$1h(_class$1i = _dec2$T(_class$1i = _dec3$K(_class$1i = _dec4$E(_class$1i = (_class2$19 = (_temp$1c = _class3$y = function (_Component) {
              _inheritsLoose(PageViewIndicator, _Component);

              function PageViewIndicator() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Component.call.apply(_Component, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "spacing", _descriptor$_, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_spriteFrame", _descriptor2$L, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_direction", _descriptor3$y, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_cellSize", _descriptor4$t, _assertThisInitialized(_this));

                _this._layout = null;
                _this._pageView = null;
                _this._indicators = [];
                return _this;
              }

              var _proto = PageViewIndicator.prototype;

              _proto.onLoad = function onLoad() {
                this._updateLayout();
              };

              _proto.setPageView = function setPageView(target) {
                this._pageView = target;

                this._refresh();
              };

              _proto._updateLayout = function _updateLayout() {
                this._layout = this.getComponent(Layout);

                if (!this._layout) {
                  this._layout = this.addComponent(Layout);
                }

                var layout = this._layout;

                if (this.direction === Direction$2.HORIZONTAL) {
                  layout.type = Layout.Type.HORIZONTAL;
                  layout.spacingX = this.spacing;
                } else if (this.direction === Direction$2.VERTICAL) {
                  layout.type = Layout.Type.VERTICAL;
                  layout.spacingY = this.spacing;
                }

                layout.resizeMode = Layout.ResizeMode.CONTAINER;
              };

              _proto._createIndicator = function _createIndicator() {
                var node = new Node$1();
                node.layer = this.node.layer;
                var sprite = node.addComponent(Sprite);
                sprite.spriteFrame = this.spriteFrame;
                sprite.sizeMode = Sprite.SizeMode.CUSTOM;
                node.parent = this.node;

                node._uiProps.uiTransformComp.setContentSize(this._cellSize);

                return node;
              };

              _proto._changedState = function _changedState() {
                var indicators = this._indicators;

                if (indicators.length === 0 || !this._pageView) {
                  return;
                }

                var idx = this._pageView.curPageIdx;

                if (idx >= indicators.length) {
                  return;
                }

                for (var i = 0; i < indicators.length; ++i) {
                  var node = indicators[i];

                  if (!node._uiProps.uiComp) {
                    continue;
                  }

                  var uiComp = node._uiProps.uiComp;

                  _color$1.set(uiComp.color);

                  _color$1.a = 255 / 2;
                  uiComp.color = _color$1;
                }

                if (indicators[idx]._uiProps.uiComp) {
                  var comp = indicators[idx]._uiProps.uiComp;

                  _color$1.set(comp.color);

                  _color$1.a = 255;
                  comp.color = _color$1;
                }
              };

              _proto._refresh = function _refresh() {
                if (!this._pageView) {
                  return;
                }

                var indicators = this._indicators;

                var pages = this._pageView.getPages();

                if (pages.length === indicators.length) {
                  return;
                }

                var i = 0;

                if (pages.length > indicators.length) {
                  for (i = 0; i < pages.length; ++i) {
                    if (!indicators[i]) {
                      indicators[i] = this._createIndicator();
                    }
                  }
                } else {
                  var count = indicators.length - pages.length;

                  for (i = count; i > 0; --i) {
                    var node = indicators[i - 1];
                    this.node.removeChild(node);
                    indicators.splice(i - 1, 1);
                  }
                }

                if (this._layout && this._layout.enabledInHierarchy) {
                  this._layout.updateLayout();
                }

                this._changedState();
              };

              _createClass(PageViewIndicator, [{
                key: "spriteFrame",
                get: function get() {
                  return this._spriteFrame;
                },
                set: function set(value) {
                  if (this._spriteFrame === value) {
                    return;
                  }

                  this._spriteFrame = value;
                }
              }, {
                key: "direction",
                get: function get() {
                  return this._direction;
                },
                set: function set(value) {
                  if (this._direction === value) {
                    return;
                  }

                  this._direction = value;
                }
              }, {
                key: "cellSize",
                get: function get() {
                  return this._cellSize;
                },
                set: function set(value) {
                  if (this._cellSize === value) {
                    return;
                  }

                  this._cellSize = value;
                }
              }]);

              return PageViewIndicator;
            }(Component), _class3$y.Direction = Direction$2, _temp$1c), (_applyDecoratedDescriptor(_class2$19.prototype, "spriteFrame", [_dec5$x, _dec6$r], Object.getOwnPropertyDescriptor(_class2$19.prototype, "spriteFrame"), _class2$19.prototype), _applyDecoratedDescriptor(_class2$19.prototype, "direction", [_dec7$p, _dec8$n], Object.getOwnPropertyDescriptor(_class2$19.prototype, "direction"), _class2$19.prototype), _applyDecoratedDescriptor(_class2$19.prototype, "cellSize", [_dec9$k, _dec10$j], Object.getOwnPropertyDescriptor(_class2$19.prototype, "cellSize"), _class2$19.prototype), _descriptor$_ = _applyDecoratedDescriptor(_class2$19.prototype, "spacing", [serializable, _dec11$i], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor2$L = _applyDecoratedDescriptor(_class2$19.prototype, "_spriteFrame", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor3$y = _applyDecoratedDescriptor(_class2$19.prototype, "_direction", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return Direction$2.HORIZONTAL;
              }
            }), _descriptor4$t = _applyDecoratedDescriptor(_class2$19.prototype, "_cellSize", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new Size(20, 20);
              }
            })), _class2$19)) || _class$1i) || _class$1i) || _class$1i) || _class$1i));

            var _dec$1i, _dec2$U, _dec3$L, _dec4$F, _dec5$y, _dec6$s, _dec7$q, _dec8$o, _dec9$l, _dec10$k, _dec11$j, _dec12$i, _dec13$g, _dec14$e, _dec15$e, _dec16$d, _dec17$c, _dec18$c, _dec19$c, _dec20$b, _dec21$b, _dec22$b, _dec23$b, _dec24$a, _dec25$a, _dec26$9, _class$1j, _class2$1a, _descriptor$$, _descriptor2$M, _descriptor3$z, _descriptor4$u, _descriptor5$o, _descriptor6$g, _descriptor7$e, _descriptor8$e, _descriptor9$d, _descriptor10$d, _descriptor11$c, _descriptor12$a, _class3$z, _temp$1d;

            var _tempVec2$2 = new Vec2();

            var SizeMode$1;

            (function (SizeMode) {
              SizeMode[SizeMode["Unified"] = 0] = "Unified";
              SizeMode[SizeMode["Free"] = 1] = "Free";
            })(SizeMode$1 || (SizeMode$1 = {}));

            ccenum(SizeMode$1);
            var Direction$3;

            (function (Direction) {
              Direction[Direction["Horizontal"] = 0] = "Horizontal";
              Direction[Direction["Vertical"] = 1] = "Vertical";
            })(Direction$3 || (Direction$3 = {}));

            ccenum(Direction$3);
            var EventType$6;

            (function (EventType) {
              EventType["PAGE_TURNING"] = "page-turning";
            })(EventType$6 || (EventType$6 = {}));

            var PageView = function (v) { return exports({ PageView: v, PageViewComponent: v }), v; }((_dec$1i = ccclass('cc.PageView'), _dec2$U = help(), _dec3$L = executionOrder(110), _dec4$F = menu(), _dec5$y = type(SizeMode$1), _dec6$s = tooltip(), _dec7$q = type(Direction$3), _dec8$o = tooltip(), _dec9$l = range(), _dec10$k = tooltip(), _dec11$j = range(), _dec12$i = tooltip(), _dec13$g = type(PageViewIndicator), _dec14$e = tooltip(), _dec15$e = tooltip(), _dec16$d = type(ScrollBar), _dec17$c = visible(), _dec18$c = type(ScrollBar), _dec19$c = visible(), _dec20$b = visible(), _dec21$b = visible(), _dec22$b = visible(), _dec23$b = type([EventHandler]), _dec24$a = visible(), _dec25$a = type([EventHandler]), _dec26$9 = tooltip(), _dec$1i(_class$1j = _dec2$U(_class$1j = _dec3$L(_class$1j = _dec4$F(_class$1j = (_class2$1a = (_temp$1d = _class3$z = function (_ScrollView) {
              _inheritsLoose(PageView, _ScrollView);

              function PageView() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _ScrollView.call.apply(_ScrollView, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "autoPageTurningThreshold", _descriptor$$, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "horizontal", _descriptor2$M, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "vertical", _descriptor3$z, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "cancelInnerEvents", _descriptor4$u, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "scrollEvents", _descriptor5$o, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "pageTurningSpeed", _descriptor6$g, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "pageEvents", _descriptor7$e, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_sizeMode", _descriptor8$e, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_direction", _descriptor9$d, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_scrollThreshold", _descriptor10$d, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_pageTurningEventTiming", _descriptor11$c, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_indicator", _descriptor12$a, _assertThisInitialized(_this));

                _this._curPageIdx = 0;
                _this._lastPageIdx = 0;
                _this._pages = [];
                _this._initContentPos = new Vec3();
                _this._scrollCenterOffsetX = [];
                _this._scrollCenterOffsetY = [];
                _this._touchBeganPosition = new Vec2();
                _this._touchEndPosition = new Vec2();
                return _this;
              }

              var _proto = PageView.prototype;

              _proto.onEnable = function onEnable() {
                _ScrollView.prototype.onEnable.call(this);

                this.node.on(SystemEventType.SIZE_CHANGED, this._updateAllPagesSize, this);

                {
                  this.node.on(PageView.EventType.SCROLL_ENG_WITH_THRESHOLD, this._dispatchPageTurningEvent, this);
                }
              };

              _proto.onDisable = function onDisable() {
                _ScrollView.prototype.onDisable.call(this);

                this.node.off(SystemEventType.SIZE_CHANGED, this._updateAllPagesSize, this);

                {
                  this.node.off(PageView.EventType.SCROLL_ENG_WITH_THRESHOLD, this._dispatchPageTurningEvent, this);
                }
              };

              _proto.onLoad = function onLoad() {
                this._initPages();

                if (this.indicator) {
                  this.indicator.setPageView(this);
                }
              };

              _proto.getCurrentPageIndex = function getCurrentPageIndex() {
                return this._curPageIdx;
              };

              _proto.setCurrentPageIndex = function setCurrentPageIndex(index) {
                this.scrollToPage(index, 1);
              };

              _proto.getPages = function getPages() {
                return this._pages;
              };

              _proto.addPage = function addPage(page) {
                if (!page || this._pages.indexOf(page) !== -1 || !this.content) {
                  return;
                }

                if (!page._uiProps.uiTransformComp) {
                  logID(4301);
                  return;
                }

                this.content.addChild(page);

                this._pages.push(page);

                this._updatePageView();
              };

              _proto.insertPage = function insertPage(page, index) {
                if (index < 0 || !page || this._pages.indexOf(page) !== -1 || !this.content) {
                  return;
                }

                var pageCount = this._pages.length;

                if (index >= pageCount) {
                  this.addPage(page);
                } else {
                  if (!page._uiProps.uiTransformComp) {
                    logID(4301);
                    return;
                  }

                  this._pages.splice(index, 0, page);

                  this.content.insertChild(page, index);

                  this._updatePageView();
                }
              };

              _proto.removePage = function removePage(page) {
                if (!page || !this.content) {
                  return;
                }

                var index = this._pages.indexOf(page);

                if (index === -1) {
                  warnID(4300, page.name);
                  return;
                }

                this.removePageAtIndex(index);
              };

              _proto.removePageAtIndex = function removePageAtIndex(index) {
                var pageList = this._pages;

                if (index < 0 || index >= pageList.length) {
                  return;
                }

                var page = pageList[index];

                if (!page || !this.content) {
                  return;
                }

                this.content.removeChild(page);
                pageList.splice(index, 1);

                this._updatePageView();
              };

              _proto.removeAllPages = function removeAllPages() {
                if (!this.content) {
                  return;
                }

                var locPages = this._pages;

                for (var i = 0, len = locPages.length; i < len; i++) {
                  this.content.removeChild(locPages[i]);
                }

                this._pages.length = 0;

                this._updatePageView();
              };

              _proto.scrollToPage = function scrollToPage(idx, timeInSecond) {
                if (timeInSecond === void 0) {
                  timeInSecond = 0.3;
                }

                if (idx < 0 || idx >= this._pages.length) {
                  return;
                }

                this._curPageIdx = idx;
                this.scrollToOffset(this._moveOffsetValue(idx), timeInSecond, true);

                if (this.indicator) {
                  this.indicator._changedState();
                }
              };

              _proto.getScrollEndedEventTiming = function getScrollEndedEventTiming() {
                return this.pageTurningEventTiming;
              };

              _proto._updatePageView = function _updatePageView() {
                if (!this.content) {
                  return;
                }

                var layout = this.content.getComponent(Layout);

                if (layout && layout.enabled) {
                  layout.updateLayout();
                }

                var pageCount = this._pages.length;

                if (this._curPageIdx >= pageCount) {
                  this._curPageIdx = pageCount === 0 ? 0 : pageCount - 1;
                  this._lastPageIdx = this._curPageIdx;
                }

                var contentPos = this._initContentPos;

                for (var i = 0; i < pageCount; ++i) {
                  var page = this._pages[i];
                  var pos = page.position;

                  if (this.direction === Direction$3.Horizontal) {
                    this._scrollCenterOffsetX[i] = Math.abs(contentPos.x + pos.x);
                  } else {
                    this._scrollCenterOffsetY[i] = Math.abs(contentPos.y + pos.y);
                  }
                }

                if (this.indicator) {
                  this.indicator._refresh();
                }
              };

              _proto._updateAllPagesSize = function _updateAllPagesSize() {
                var viewTrans = this.view;

                if (!this.content || !viewTrans) {
                  return;
                }

                if (this._sizeMode !== SizeMode$1.Unified) {
                  return;
                }

                var locPages =  this._pages;
                var selfSize = viewTrans.contentSize;

                for (var i = 0, len = locPages.length; i < len; i++) {
                  locPages[i]._uiProps.uiTransformComp.setContentSize(selfSize);
                }
              };

              _proto._handleReleaseLogic = function _handleReleaseLogic() {
                this._autoScrollToPage();

                if (this._scrolling) {
                  this._scrolling = false;

                  if (!this._autoScrolling) {
                    this._dispatchEvent(PageView.EventType.SCROLL_ENDED);
                  }
                }
              };

              _proto._onTouchBegan = function _onTouchBegan(event, captureListeners) {
                event.touch.getUILocation(_tempVec2$2);
                Vec2.set(this._touchBeganPosition, _tempVec2$2.x, _tempVec2$2.y);

                _ScrollView.prototype._onTouchBegan.call(this, event, captureListeners);
              };

              _proto._onTouchMoved = function _onTouchMoved(event, captureListeners) {
                _ScrollView.prototype._onTouchMoved.call(this, event, captureListeners);
              };

              _proto._onTouchEnded = function _onTouchEnded(event, captureListeners) {
                event.touch.getUILocation(_tempVec2$2);
                Vec2.set(this._touchEndPosition, _tempVec2$2.x, _tempVec2$2.y);

                _ScrollView.prototype._onTouchEnded.call(this, event, captureListeners);
              };

              _proto._onTouchCancelled = function _onTouchCancelled(event, captureListeners) {
                event.touch.getUILocation(_tempVec2$2);
                Vec2.set(this._touchEndPosition, _tempVec2$2.x, _tempVec2$2.y);

                _ScrollView.prototype._onTouchCancelled.call(this, event, captureListeners);
              };

              _proto._onMouseWheel = function _onMouseWheel() {};

              _proto._syncScrollDirection = function _syncScrollDirection() {
                this.horizontal = this.direction === Direction$3.Horizontal;
                this.vertical = this.direction === Direction$3.Vertical;
              };

              _proto._syncSizeMode = function _syncSizeMode() {
                var viewTrans = this.view;

                if (!this.content || !viewTrans) {
                  return;
                }

                var layout = this.content.getComponent(Layout);

                if (layout) {
                  if (this._sizeMode === SizeMode$1.Free && this._pages.length > 0) {
                    var firstPageTrans = this._pages[0]._uiProps.uiTransformComp;
                    var lastPageTrans = this._pages[this._pages.length - 1]._uiProps.uiTransformComp;

                    if (this.direction === Direction$3.Horizontal) {
                      layout.paddingLeft = (viewTrans.width - firstPageTrans.width) / 2;
                      layout.paddingRight = (viewTrans.width - lastPageTrans.width) / 2;
                    } else if (this.direction === Direction$3.Vertical) {
                      layout.paddingTop = (viewTrans.height - firstPageTrans.height) / 2;
                      layout.paddingBottom = (viewTrans.height - lastPageTrans.height) / 2;
                    }
                  }

                  layout.updateLayout();
                }
              };

              _proto._initPages = function _initPages() {
                if (!this.content) {
                  return;
                }

                this._initContentPos = this.content.position;
                var children = this.content.children;

                for (var i = 0; i < children.length; ++i) {
                  var page = children[i];

                  if (this._pages.indexOf(page) >= 0) {
                    continue;
                  }

                  this._pages.push(page);
                }

                this._syncScrollDirection();

                this._syncSizeMode();

                this._updatePageView();
              };

              _proto._dispatchPageTurningEvent = function _dispatchPageTurningEvent() {
                if (this._lastPageIdx === this._curPageIdx) {
                  return;
                }

                this._lastPageIdx = this._curPageIdx;
                EventHandler.emitEvents(this.pageEvents, this, EventType$6.PAGE_TURNING);
                this.node.emit(EventType$6.PAGE_TURNING, this);
              };

              _proto._isQuicklyScrollable = function _isQuicklyScrollable(touchMoveVelocity) {
                if (this.direction === Direction$3.Horizontal) {
                  if (Math.abs(touchMoveVelocity.x) > this.autoPageTurningThreshold) {
                    return true;
                  }
                } else if (this.direction === Direction$3.Vertical) {
                  if (Math.abs(touchMoveVelocity.y) > this.autoPageTurningThreshold) {
                    return true;
                  }
                }

                return false;
              };

              _proto._moveOffsetValue = function _moveOffsetValue(idx) {
                var offset = new Vec2();

                if (this._sizeMode === SizeMode$1.Free) {
                  if (this.direction === Direction$3.Horizontal) {
                    offset.x = this._scrollCenterOffsetX[idx];
                  } else if (this.direction === Direction$3.Vertical) {
                    offset.y = this._scrollCenterOffsetY[idx];
                  }
                } else {
                  var viewTrans = this.view;

                  if (!viewTrans) {
                    return offset;
                  }

                  if (this.direction === Direction$3.Horizontal) {
                    offset.x = idx * viewTrans.width;
                  } else if (this.direction === Direction$3.Vertical) {
                    offset.y = idx * viewTrans.height;
                  }
                }

                return offset;
              };

              _proto._getDragDirection = function _getDragDirection(moveOffset) {
                if (this._direction === Direction$3.Horizontal) {
                  if (moveOffset.x === 0) {
                    return 0;
                  }

                  return moveOffset.x > 0 ? 1 : -1;
                } else {
                  if (moveOffset.y === 0) {
                    return 0;
                  }

                  return moveOffset.y < 0 ? 1 : -1;
                }
              };

              _proto._isScrollable = function _isScrollable(offset, index, nextIndex) {
                if (this._sizeMode === SizeMode$1.Free) {
                  var curPageCenter = 0;
                  var nextPageCenter = 0;

                  if (this.direction === Direction$3.Horizontal) {
                    curPageCenter = this._scrollCenterOffsetX[index];
                    nextPageCenter = this._scrollCenterOffsetX[nextIndex];
                    return Math.abs(offset.x) >= Math.abs(curPageCenter - nextPageCenter) * this.scrollThreshold;
                  } else if (this.direction === Direction$3.Vertical) {
                    curPageCenter = this._scrollCenterOffsetY[index];
                    nextPageCenter = this._scrollCenterOffsetY[nextIndex];
                    return Math.abs(offset.y) >= Math.abs(curPageCenter - nextPageCenter) * this.scrollThreshold;
                  }
                } else {
                  var viewTrans = this.view;

                  if (!viewTrans) {
                    return false;
                  }

                  if (this.direction === Direction$3.Horizontal) {
                    return Math.abs(offset.x) >= viewTrans.width * this.scrollThreshold;
                  } else if (this.direction === Direction$3.Vertical) {
                    return Math.abs(offset.y) >= viewTrans.height * this.scrollThreshold;
                  }
                }

                return false;
              };

              _proto._autoScrollToPage = function _autoScrollToPage() {
                var bounceBackStarted = this._startBounceBackIfNeeded();

                if (bounceBackStarted) {
                  var bounceBackAmount = this._getHowMuchOutOfBoundary();

                  this._clampDelta(bounceBackAmount);

                  if (bounceBackAmount.x > 0 || bounceBackAmount.y < 0) {
                    this._curPageIdx = this._pages.length === 0 ? 0 : this._pages.length - 1;
                  }

                  if (bounceBackAmount.x < 0 || bounceBackAmount.y > 0) {
                    this._curPageIdx = 0;
                  }

                  if (this.indicator) {
                    this.indicator._changedState();
                  }
                } else {
                  var moveOffset = new Vec2();
                  Vec2.subtract(moveOffset, this._touchBeganPosition, this._touchEndPosition);
                  var index = this._curPageIdx;

                  var nextIndex = index + this._getDragDirection(moveOffset);

                  var timeInSecond = this.pageTurningSpeed * Math.abs(index - nextIndex);

                  if (nextIndex < this._pages.length) {
                    if (this._isScrollable(moveOffset, index, nextIndex)) {
                      this.scrollToPage(nextIndex, timeInSecond);
                      return;
                    } else {
                      var touchMoveVelocity = this._calculateTouchMoveVelocity();

                      if (this._isQuicklyScrollable(touchMoveVelocity)) {
                        this.scrollToPage(nextIndex, timeInSecond);
                        return;
                      }
                    }
                  }

                  this.scrollToPage(index, timeInSecond);
                }
              };

              _createClass(PageView, [{
                key: "sizeMode",
                get: function get() {
                  return this._sizeMode;
                },
                set: function set(value) {
                  if (this._sizeMode === value) {
                    return;
                  }

                  this._sizeMode = value;

                  this._syncSizeMode();
                }
              }, {
                key: "direction",
                get: function get() {
                  return this._direction;
                },
                set: function set(value) {
                  if (this._direction === value) {
                    return;
                  }

                  this._direction = value;

                  this._syncScrollDirection();
                }
              }, {
                key: "scrollThreshold",
                get: function get() {
                  return this._scrollThreshold;
                },
                set: function set(value) {
                  if (this._scrollThreshold === value) {
                    return;
                  }

                  this._scrollThreshold = value;
                }
              }, {
                key: "pageTurningEventTiming",
                get: function get() {
                  return this._pageTurningEventTiming;
                },
                set: function set(value) {
                  if (this._pageTurningEventTiming === value) {
                    return;
                  }

                  this._pageTurningEventTiming = value;
                }
              }, {
                key: "indicator",
                get: function get() {
                  return this._indicator;
                },
                set: function set(value) {
                  if (this._indicator === value) {
                    return;
                  }

                  this._indicator = value;

                  if (this.indicator) {
                    this.indicator.setPageView(this);
                  }
                }
              }, {
                key: "curPageIdx",
                get: function get() {
                  return this._curPageIdx;
                }
              }, {
                key: "verticalScrollBar",
                get: function get() {
                  return _ScrollView.prototype.verticalScrollBar;
                },
                set: function set(value) {
                  this.verticalScrollBar = value;
                }
              }, {
                key: "horizontalScrollBar",
                get: function get() {
                  return _ScrollView.prototype.horizontalScrollBar;
                },
                set: function set(value) {
                  this.horizontalScrollBar = value;
                }
              }]);

              return PageView;
            }(ScrollView), _class3$z.SizeMode = SizeMode$1, _class3$z.Direction = Direction$3, _class3$z.EventType = extendsEnum(EventType$6, EventType$4), _temp$1d), (_applyDecoratedDescriptor(_class2$1a.prototype, "sizeMode", [_dec5$y, _dec6$s], Object.getOwnPropertyDescriptor(_class2$1a.prototype, "sizeMode"), _class2$1a.prototype), _applyDecoratedDescriptor(_class2$1a.prototype, "direction", [_dec7$q, _dec8$o], Object.getOwnPropertyDescriptor(_class2$1a.prototype, "direction"), _class2$1a.prototype), _applyDecoratedDescriptor(_class2$1a.prototype, "scrollThreshold", [slide, _dec9$l, _dec10$k], Object.getOwnPropertyDescriptor(_class2$1a.prototype, "scrollThreshold"), _class2$1a.prototype), _applyDecoratedDescriptor(_class2$1a.prototype, "pageTurningEventTiming", [slide, _dec11$j, _dec12$i], Object.getOwnPropertyDescriptor(_class2$1a.prototype, "pageTurningEventTiming"), _class2$1a.prototype), _applyDecoratedDescriptor(_class2$1a.prototype, "indicator", [_dec13$g, _dec14$e], Object.getOwnPropertyDescriptor(_class2$1a.prototype, "indicator"), _class2$1a.prototype), _descriptor$$ = _applyDecoratedDescriptor(_class2$1a.prototype, "autoPageTurningThreshold", [serializable, _dec15$e], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 100;
              }
            }), _applyDecoratedDescriptor(_class2$1a.prototype, "verticalScrollBar", [_dec16$d, override, _dec17$c], Object.getOwnPropertyDescriptor(_class2$1a.prototype, "verticalScrollBar"), _class2$1a.prototype), _applyDecoratedDescriptor(_class2$1a.prototype, "horizontalScrollBar", [_dec18$c, override, _dec19$c], Object.getOwnPropertyDescriptor(_class2$1a.prototype, "horizontalScrollBar"), _class2$1a.prototype), _descriptor2$M = _applyDecoratedDescriptor(_class2$1a.prototype, "horizontal", [override, serializable, _dec20$b], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _descriptor3$z = _applyDecoratedDescriptor(_class2$1a.prototype, "vertical", [override, serializable, _dec21$b], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _descriptor4$u = _applyDecoratedDescriptor(_class2$1a.prototype, "cancelInnerEvents", [override, serializable, _dec22$b], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _descriptor5$o = _applyDecoratedDescriptor(_class2$1a.prototype, "scrollEvents", [_dec23$b, serializable, override, _dec24$a], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor6$g = _applyDecoratedDescriptor(_class2$1a.prototype, "pageTurningSpeed", [serializable, editable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0.3;
              }
            }), _descriptor7$e = _applyDecoratedDescriptor(_class2$1a.prototype, "pageEvents", [_dec25$a, serializable, _dec26$9], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor8$e = _applyDecoratedDescriptor(_class2$1a.prototype, "_sizeMode", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return SizeMode$1.Unified;
              }
            }), _descriptor9$d = _applyDecoratedDescriptor(_class2$1a.prototype, "_direction", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return Direction$3.Horizontal;
              }
            }), _descriptor10$d = _applyDecoratedDescriptor(_class2$1a.prototype, "_scrollThreshold", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0.5;
              }
            }), _descriptor11$c = _applyDecoratedDescriptor(_class2$1a.prototype, "_pageTurningEventTiming", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0.1;
              }
            }), _descriptor12$a = _applyDecoratedDescriptor(_class2$1a.prototype, "_indicator", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            })), _class2$1a)) || _class$1j) || _class$1j) || _class$1j) || _class$1j));

            var _tempPos$1 = new Vec3();

            var _defaultAnchor = new Vec2();

            var tInverseTranslate = new Vec2();
            var tInverseScale = new Vec2(1, 1);

            var _tempVec2_1$1 = new Vec2();

            var _tempVec2_2 = new Vec2();

            function align(node, widget) {
              if (widget._hadAlignOnce) return;

              if ( widget.alignMode === AlignMode.ONCE) {
                widget._hadAlignOnce = true;
              }

              var hasTarget = widget.target;
              var target;
              var inverseTranslate = tInverseTranslate;
              var inverseScale = tInverseScale;

              if (hasTarget) {
                target = hasTarget;
                computeInverseTransForTarget(node, target, inverseTranslate, inverseScale);
              } else {
                target = node.parent;
              }

              var targetSize = getReadonlyNodeSize(target);
              var useGlobal = target instanceof Scene || !target.getComponent(UITransform);
              var targetAnchor = useGlobal ? _defaultAnchor : target.getComponent(UITransform).anchorPoint;
              var isRoot =  useGlobal;
              node.getPosition(_tempPos$1);
              var uiTrans = node._uiProps.uiTransformComp;
              var x = _tempPos$1.x;
              var y = _tempPos$1.y;
              var anchor = uiTrans.anchorPoint;
              var scale = node.getScale();

              if (widget.alignFlags & AlignFlags.HORIZONTAL) {
                var localLeft = 0;
                var localRight = 0;
                var targetWidth = targetSize.width;

                if (isRoot) {
                  localLeft = visibleRect.left.x;
                  localRight = visibleRect.right.x;
                } else {
                  localLeft = -targetAnchor.x * targetWidth;
                  localRight = localLeft + targetWidth;
                }

                localLeft += widget.isAbsoluteLeft ? widget.left : widget.left * targetWidth;
                localRight -= widget.isAbsoluteRight ? widget.right : widget.right * targetWidth;

                if (hasTarget) {
                  localLeft += inverseTranslate.x;
                  localLeft *= inverseScale.x;
                  localRight += inverseTranslate.x;
                  localRight *= inverseScale.x;
                }

                var width = 0;
                var anchorX = anchor.x;
                var scaleX = scale.x;

                if (scaleX < 0) {
                  anchorX = 1.0 - anchorX;
                  scaleX = -scaleX;
                }

                if (widget.isStretchWidth) {
                  width = localRight - localLeft;

                  if (scaleX !== 0) {
                    uiTrans.width = width / scaleX;
                  }

                  x = localLeft + anchorX * width;
                } else {
                  width = uiTrans.width * scaleX;

                  if (widget.isAlignHorizontalCenter) {
                    var localHorizontalCenter = widget.isAbsoluteHorizontalCenter ? widget.horizontalCenter : widget.horizontalCenter * targetWidth;
                    var targetCenter = (0.5 - targetAnchor.x) * targetSize.width;

                    if (hasTarget) {
                      localHorizontalCenter *= inverseScale.x;
                      targetCenter += inverseTranslate.x;
                      targetCenter *= inverseScale.x;
                    }

                    x = targetCenter + (anchorX - 0.5) * width + localHorizontalCenter;
                  } else if (widget.isAlignLeft) {
                    x = localLeft + anchorX * width;
                  } else {
                    x = localRight + (anchorX - 1) * width;
                  }
                }

                widget._lastSize.width = width;
              }

              if (widget.alignFlags & AlignFlags.VERTICAL) {
                var localTop = 0;
                var localBottom = 0;
                var targetHeight = targetSize.height;

                if (isRoot) {
                  localBottom = visibleRect.bottom.y;
                  localTop = visibleRect.top.y;
                } else {
                  localBottom = -targetAnchor.y * targetHeight;
                  localTop = localBottom + targetHeight;
                }

                localBottom += widget.isAbsoluteBottom ? widget.bottom : widget.bottom * targetHeight;
                localTop -= widget.isAbsoluteTop ? widget.top : widget.top * targetHeight;

                if (hasTarget) {
                  localBottom += inverseTranslate.y;
                  localBottom *= inverseScale.y;
                  localTop += inverseTranslate.y;
                  localTop *= inverseScale.y;
                }

                var height = 0;
                var anchorY = anchor.y;
                var scaleY = scale.y;

                if (scaleY < 0) {
                  anchorY = 1.0 - anchorY;
                  scaleY = -scaleY;
                }

                if (widget.isStretchHeight) {
                  height = localTop - localBottom;

                  if (scaleY !== 0) {
                    uiTrans.height = height / scaleY;
                  }

                  y = localBottom + anchorY * height;
                } else {
                  height = uiTrans.height * scaleY;

                  if (widget.isAlignVerticalCenter) {
                    var localVerticalCenter = widget.isAbsoluteVerticalCenter ? widget.verticalCenter : widget.verticalCenter * targetHeight;
                    var targetMiddle = (0.5 - targetAnchor.y) * targetSize.height;

                    if (hasTarget) {
                      localVerticalCenter *= inverseScale.y;
                      targetMiddle += inverseTranslate.y;
                      targetMiddle *= inverseScale.y;
                    }

                    y = targetMiddle + (anchorY - 0.5) * height + localVerticalCenter;
                  } else if (widget.isAlignBottom) {
                    y = localBottom + anchorY * height;
                  } else {
                    y = localTop + (anchorY - 1) * height;
                  }
                }

                widget._lastSize.height = height;
              }

              node.setPosition(x, y, _tempPos$1.z);
              Vec3.set(widget._lastPos, x, y, _tempPos$1.z);
            }

            function visitNode$1(node) {
              var widget = node.getComponent(Widget);

              if (widget && widget.enabled) {

                if (!legacyCC.isValid(node, true)) {
                  return;
                }

                activeWidgets.push(widget);
              }

              var children = node.children;

              for (var _iterator = _createForOfIteratorHelperLoose(children), _step; !(_step = _iterator()).done;) {
                var child = _step.value;

                if (child.active) {
                  visitNode$1(child);
                }
              }
            }

            function refreshScene() {
              var scene = director.getScene();

              if (scene) {
                widgetManager.isAligning = true;

                if (widgetManager._nodesOrderDirty) {
                  activeWidgets.length = 0;
                  visitNode$1(scene);
                  widgetManager._nodesOrderDirty = false;
                }
                var widget = null;
                var iterator = widgetManager._activeWidgetsIterator;

                for (iterator.i = 0; iterator.i < activeWidgets.length; ++iterator.i) {
                  widget = activeWidgets[iterator.i];

                  if (widget._dirty) {
                    align(widget.node, widget);
                    widget._dirty = false;
                  }
                }

                widgetManager.isAligning = false;
              }
            }

            var activeWidgets = [];

            function updateAlignment(node) {
              var parent = node.parent;

              if (parent && Node$1.isNode(parent)) {
                updateAlignment(parent);
              }

              var widget = node.getComponent(Widget);

              if (widget && parent) {
                align(node, widget);
              }
            }

            var widgetManager = exports('widgetManager', legacyCC._widgetManager = {
              isAligning: false,
              _nodesOrderDirty: false,
              _activeWidgetsIterator: new array.MutableForwardIterator(activeWidgets),
              animationState:  null,
              init: function init() {
                director.on(Director.EVENT_AFTER_UPDATE, refreshScene);
                View.instance.on('design-resolution-changed', this.onResized, this);

                {
                  var thisOnResized = this.onResized.bind(this);
                  View.instance.on('canvas-resize', thisOnResized);
                  system.onOrientationChange(thisOnResized);
                }
              },
              add: function add(widget) {
                this._nodesOrderDirty = true;
              },
              remove: function remove(widget) {
                this._activeWidgetsIterator.remove(widget);
              },
              onResized: function onResized() {
                var scene = director.getScene();

                if (scene) {
                  this.refreshWidgetOnResized(scene);
                }
              },
              refreshWidgetOnResized: function refreshWidgetOnResized(node) {
                var widget = Node$1.isNode(node) && node.getComponent(Widget);

                if (widget && widget.enabled && (widget.alignMode === AlignMode.ON_WINDOW_RESIZE || widget.alignMode === AlignMode.ALWAYS)) {
                  widget.setDirty();
                }

                var children = node.children;

                for (var _iterator2 = _createForOfIteratorHelperLoose(children), _step2; !(_step2 = _iterator2()).done;) {
                  var child = _step2.value;
                  this.refreshWidgetOnResized(child);
                }
              },
              updateOffsetsToStayPut: function updateOffsetsToStayPut(widget, e) {
                function i(t, c) {
                  return Math.abs(t - c) > 1e-10 ? c : t;
                }

                var widgetNode = widget.node;
                var widgetParent = widgetNode.parent;

                if (widgetParent) {
                  var zero = _tempVec2_1$1;
                  zero.set(0, 0);
                  var one = _tempVec2_2;
                  one.set(1, 1);

                  if (widget.target) {
                    widgetParent = widget.target;
                    computeInverseTransForTarget(widgetNode, widgetParent, zero, one);
                  }

                  if (!e) {
                    return;
                  }

                  var parentTrans = widgetParent._uiProps && widgetParent._uiProps.uiTransformComp;
                  var parentAP = parentTrans ? parentTrans.anchorPoint : _defaultAnchor;
                  var trans = widgetNode._uiProps.uiTransformComp;
                  var matchSize = getReadonlyNodeSize(widgetParent);
                  var myAP = trans.anchorPoint;
                  var pos = widgetNode.getPosition();
                  var alignFlags = AlignFlags;
                  var widgetNodeScale = widgetNode.getScale();
                  var temp = 0;

                  if (e & alignFlags.LEFT) {
                    var l = -parentAP.x * matchSize.width;
                    l += zero.x;
                    l *= one.x;
                    temp = pos.x - myAP.x * trans.width * widgetNodeScale.x - l;

                    if (!widget.isAbsoluteLeft) {
                      temp /= matchSize.width;
                    }

                    temp /= one.x;
                    widget.left = i(widget.left, temp);
                  }

                  if (e & alignFlags.RIGHT) {
                    var r = (1 - parentAP.x) * matchSize.width;
                    r += zero.x;
                    temp = (r *= one.x) - (pos.x + (1 - myAP.x) * trans.width * widgetNodeScale.x);

                    if (!widget.isAbsoluteRight) {
                      temp /= matchSize.width;
                    }

                    temp /= one.x;
                    widget.right = i(widget.right, temp);
                  }

                  if (e & alignFlags.TOP) {
                    var t = (1 - parentAP.y) * matchSize.height;
                    t += zero.y;
                    temp = (t *= one.y) - (pos.y + (1 - myAP.y) * trans.height * widgetNodeScale.y);

                    if (!widget.isAbsoluteTop) {
                      temp /= matchSize.height;
                    }

                    temp /= one.y;
                    widget.top = i(widget.top, temp);
                  }

                  if (e & alignFlags.BOT) {
                    var b = -parentAP.y * matchSize.height;
                    b += zero.y;
                    b *= one.y;
                    temp = pos.y - myAP.y * trans.height * widgetNodeScale.y - b;

                    if (!widget.isAbsoluteBottom) {
                      temp /= matchSize.height;
                    }

                    temp /= one.y;
                    widget.bottom = i(widget.bottom, temp);
                  }
                }
              },
              updateAlignment: updateAlignment,
              AlignMode: AlignMode,
              AlignFlags: AlignFlags
            });
            director.on(Director.EVENT_INIT, function () {
              widgetManager.init();
            });

            var _dec$1j, _dec2$V, _dec3$M, _dec4$G, _dec5$z, _class$1k;
            var SafeArea = function (v) { return exports({ SafeArea: v, SafeAreaComponent: v }), v; }((_dec$1j = ccclass('cc.SafeArea'), _dec2$V = help(), _dec3$M = executionOrder(110), _dec4$G = menu(), _dec5$z = requireComponent(Widget), _dec$1j(_class$1k = _dec2$V(_class$1k = _dec3$M(_class$1k = executeInEditMode(_class$1k = _dec4$G(_class$1k = _dec5$z(_class$1k = function (_Component) {
              _inheritsLoose(SafeArea, _Component);

              function SafeArea() {
                return _Component.apply(this, arguments) || this;
              }

              var _proto = SafeArea.prototype;

              _proto.onLoad = function onLoad() {
                this._boundUpdateArea = this.updateArea.bind(this);
              };

              _proto.onEnable = function onEnable() {
                this.updateArea();
                system.onViewResize(this._boundUpdateArea);
                system.onOrientationChange(this._boundUpdateArea);
              };

              _proto.onDisable = function onDisable() {
                system.offViewResize(this._boundUpdateArea);
                system.offOrientationChange(this._boundUpdateArea);
              };

              _proto.updateArea = function updateArea() {
                var widget = this.node.getComponent(Widget);
                var uiTransComp = this.node.getComponent(UITransform);

                if (!widget || !uiTransComp) {
                  return;
                }

                widget.updateAlignment();
                var lastPos = this.node.position.clone();
                var lastAnchorPoint = uiTransComp.anchorPoint.clone();
                widget.isAlignTop = widget.isAlignBottom = widget.isAlignLeft = widget.isAlignRight = true;
                var screenWidth = legacyCC.winSize.width;
                var screenHeight = legacyCC.winSize.height;
                var safeArea = sys.getSafeAreaRect();
                widget.top = screenHeight - safeArea.y - safeArea.height;
                widget.bottom = safeArea.y;
                widget.left = safeArea.x;
                widget.right = screenWidth - safeArea.x - safeArea.width;
                widget.updateAlignment();
                var curPos = this.node.position.clone();
                var anchorX = lastAnchorPoint.x - (curPos.x - lastPos.x) / uiTransComp.width;
                var anchorY = lastAnchorPoint.y - (curPos.y - lastPos.y) / uiTransComp.height;
                uiTransComp.setAnchorPoint(anchorX, anchorY);
                widgetManager.add(widget);
              };

              return SafeArea;
            }(Component)) || _class$1k) || _class$1k) || _class$1k) || _class$1k) || _class$1k) || _class$1k));

            var _dec$1k, _dec2$W, _dec3$N, _dec4$H, _dec5$A, _dec6$t, _dec7$r, _dec8$p, _dec9$m, _dec10$l, _dec11$k, _dec12$j, _class$1l, _class2$1b, _descriptor$10, _descriptor2$N, _descriptor3$A, _descriptor4$v, _descriptor5$p, _temp$1e;
            var UICoordinateTracker = function (v) { return exports({ UICoordinateTracker: v, UICoordinateTrackerComponent: v }), v; }((_dec$1k = ccclass('cc.UICoordinateTracker'), _dec2$W = help(), _dec3$N = menu(), _dec4$H = executionOrder(110), _dec5$A = type(Node$1), _dec6$t = tooltip(), _dec7$r = type(Camera$1), _dec8$p = tooltip(), _dec9$m = tooltip(), _dec10$l = tooltip(), _dec11$k = type([EventHandler]), _dec12$j = tooltip(), _dec$1k(_class$1l = _dec2$W(_class$1l = _dec3$N(_class$1l = _dec4$H(_class$1l = (_class2$1b = (_temp$1e = function (_Component) {
              _inheritsLoose(UICoordinateTracker, _Component);

              function UICoordinateTracker() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Component.call.apply(_Component, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "syncEvents", _descriptor$10, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_target", _descriptor2$N, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_camera", _descriptor3$A, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_useScale", _descriptor4$v, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_distance", _descriptor5$p, _assertThisInitialized(_this));

                _this._transformPos = new Vec3();
                _this._viewPos = new Vec3();
                _this._canMove = true;
                _this._lastWPos = new Vec3();
                _this._lastCameraPos = new Vec3();
                return _this;
              }

              var _proto = UICoordinateTracker.prototype;

              _proto.onEnable = function onEnable() {
                this._checkCanMove();
              };

              _proto.update = function update() {
                var wPos = this.node.worldPosition;
                var camera = this._camera;

                if (!this._canMove || !camera || !camera.camera || this._lastWPos.equals(wPos) && this._lastCameraPos.equals(camera.node.worldPosition)) {
                  return;
                }

                this._lastWPos.set(wPos);

                this._lastCameraPos.set(camera.node.worldPosition);

                camera.camera.update();
                camera.convertToUINode(wPos, this._target, this._transformPos);

                if (this._useScale) {
                  Vec3.transformMat4(this._viewPos, this.node.worldPosition, camera.camera.matView);
                }

                if (this.syncEvents.length > 0) {
                  var data = this._distance / Math.abs(this._viewPos.z);
                  EventHandler.emitEvents(this.syncEvents, this._transformPos, data);
                }
              };

              _proto._checkCanMove = function _checkCanMove() {
                this._canMove = !!(this._camera && this._target);
              };

              _createClass(UICoordinateTracker, [{
                key: "target",
                get: function get() {
                  return this._target;
                },
                set: function set(value) {
                  if (this._target === value) {
                    return;
                  }

                  this._target = value;

                  this._checkCanMove();
                }
              }, {
                key: "camera",
                get: function get() {
                  return this._camera;
                },
                set: function set(value) {
                  if (this._camera === value) {
                    return;
                  }

                  this._camera = value;

                  this._checkCanMove();
                }
              }, {
                key: "useScale",
                get: function get() {
                  return this._useScale;
                },
                set: function set(value) {
                  if (this._useScale === value) {
                    return;
                  }

                  this._useScale = value;
                }
              }, {
                key: "distance",
                get: function get() {
                  return this._distance;
                },
                set: function set(value) {
                  if (this._distance === value) {
                    return;
                  }

                  this._distance = value;
                }
              }]);

              return UICoordinateTracker;
            }(Component), _temp$1e), (_applyDecoratedDescriptor(_class2$1b.prototype, "target", [_dec5$A, _dec6$t], Object.getOwnPropertyDescriptor(_class2$1b.prototype, "target"), _class2$1b.prototype), _applyDecoratedDescriptor(_class2$1b.prototype, "camera", [_dec7$r, _dec8$p], Object.getOwnPropertyDescriptor(_class2$1b.prototype, "camera"), _class2$1b.prototype), _applyDecoratedDescriptor(_class2$1b.prototype, "useScale", [_dec9$m], Object.getOwnPropertyDescriptor(_class2$1b.prototype, "useScale"), _class2$1b.prototype), _applyDecoratedDescriptor(_class2$1b.prototype, "distance", [_dec10$l], Object.getOwnPropertyDescriptor(_class2$1b.prototype, "distance"), _class2$1b.prototype), _descriptor$10 = _applyDecoratedDescriptor(_class2$1b.prototype, "syncEvents", [_dec11$k, serializable, _dec12$j], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor2$N = _applyDecoratedDescriptor(_class2$1b.prototype, "_target", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor3$A = _applyDecoratedDescriptor(_class2$1b.prototype, "_camera", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor4$v = _applyDecoratedDescriptor(_class2$1b.prototype, "_useScale", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _descriptor5$p = _applyDecoratedDescriptor(_class2$1b.prototype, "_distance", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1;
              }
            })), _class2$1b)) || _class$1l) || _class$1l) || _class$1l) || _class$1l));

            var _dec$1l, _dec2$X, _dec3$O, _class$1m;
            var BlockEvents = [SystemEventType.TOUCH_START, SystemEventType.TOUCH_END, SystemEventType.TOUCH_MOVE, SystemEventType.MOUSE_DOWN, SystemEventType.MOUSE_MOVE, SystemEventType.MOUSE_UP, SystemEventType.MOUSE_ENTER, SystemEventType.MOUSE_LEAVE, SystemEventType.MOUSE_WHEEL];

            function stopPropagation(event) {
              event.propagationStopped = true;
            }

            var BlockInputEvents = function (v) { return exports({ BlockInputEvents: v, BlockInputEventsComponent: v }), v; }((_dec$1l = ccclass('cc.BlockInputEvents'), _dec2$X = help(), _dec3$O = menu(), _dec$1l(_class$1m = _dec2$X(_class$1m = _dec3$O(_class$1m = function (_Component) {
              _inheritsLoose(BlockInputEvents, _Component);

              function BlockInputEvents() {
                return _Component.apply(this, arguments) || this;
              }

              var _proto = BlockInputEvents.prototype;

              _proto.onEnable = function onEnable() {
                for (var i = 0; i < BlockEvents.length; i++) {
                  this.node.on(BlockEvents[i], stopPropagation, this);
                }
              };

              _proto.onDisable = function onDisable() {
                for (var i = 0; i < BlockEvents.length; i++) {
                  this.node.off(BlockEvents[i], stopPropagation, this);
                }
              };

              return BlockInputEvents;
            }(Component)) || _class$1m) || _class$1m) || _class$1m));

            var minigame = {};

            var _dec$1m, _dec2$Y, _dec3$P, _dec4$I, _dec5$B, _dec6$u, _dec7$s, _class$1n, _class2$1c, _descriptor$11, _descriptor2$O, _temp$1f;
            var SubContextView = exports('SubContextView', (_dec$1m = ccclass('cc.SubContextView'), _dec2$Y = help(), _dec3$P = executionOrder(110), _dec4$I = requireComponent(UITransform), _dec5$B = menu(), _dec6$u = tooltip(), _dec7$s = tooltip(), _dec$1m(_class$1n = _dec2$Y(_class$1n = _dec3$P(_class$1n = _dec4$I(_class$1n = _dec5$B(_class$1n = (_class2$1c = (_temp$1f = function (_Component) {
              _inheritsLoose(SubContextView, _Component);

              function SubContextView() {
                var _this;

                _this = _Component.call(this) || this;

                _initializerDefineProperty(_this, "_fps", _descriptor$11, _assertThisInitialized(_this));

                _this._sprite = void 0;
                _this._imageAsset = void 0;
                _this._updatedTime = 0;
                _this._updateInterval = 0;
                _this._openDataContext = void 0;
                _this._content = void 0;

                _initializerDefineProperty(_this, "_designResolutionSize", _descriptor2$O, _assertThisInitialized(_this));

                _this._content = new Node$1('content');
                _this._content.hideFlags |= CCObject.Flags.DontSave | CCObject.Flags.HideInHierarchy;
                _this._sprite = null;
                _this._imageAsset = new ImageAsset();
                _this._openDataContext = null;
                _this._updatedTime = performance.now();
                return _this;
              }

              var _proto = SubContextView.prototype;

              _proto.onLoad = function onLoad() {
                if (minigame.getOpenDataContext) {
                  this._updateInterval = 1000 / this._fps;
                  this._openDataContext = minigame.getOpenDataContext();

                  this._initSharedCanvas();

                  this._initContentNode();

                  this._updateSubContextView();

                  this._updateContentLayer();
                } else {
                  this.enabled = false;
                }
              };

              _proto.onEnable = function onEnable() {
                this._registerNodeEvent();
              };

              _proto.onDisable = function onDisable() {
                this._unregisterNodeEvent();
              };

              _proto._initSharedCanvas = function _initSharedCanvas() {
                if (this._openDataContext) {
                  var sharedCanvas = this._openDataContext.canvas;
                  sharedCanvas.width = this._designResolutionSize.width;
                  sharedCanvas.height = this._designResolutionSize.height;
                }
              };

              _proto._initContentNode = function _initContentNode() {
                if (this._openDataContext) {
                  var sharedCanvas = this._openDataContext.canvas;
                  var image = this._imageAsset;
                  image.reset(sharedCanvas);

                  image._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._imageAsset._texture;
                  } else {
                    var sp = new SpriteFrame();
                    sp.texture = this._imageAsset._texture;
                    this._sprite.spriteFrame = sp;
                  }

                  this._content.parent = this.node;
                }
              };

              _proto._updateSubContextView = function _updateSubContextView() {
                if (!(this._openDataContext && minigame.getSystemInfoSync)) {
                  return;
                }

                var nodeTrans = this.node.getComponent(UITransform);

                var contentTrans = this._content.getComponent(UITransform);

                var scaleX = nodeTrans.width / contentTrans.width;
                var scaleY = nodeTrans.height / contentTrans.height;
                var scale = scaleX > scaleY ? scaleY : scaleX;
                contentTrans.width *= scale;
                contentTrans.height *= scale;
                var systemInfo = minigame.getSystemInfoSync();
                var box = contentTrans.getBoundingBoxToWorld();
                var visibleSize = view.getVisibleSize();
                var x = systemInfo.screenWidth * (box.x / visibleSize.width);
                var y = systemInfo.screenHeight * (box.y / visibleSize.height);
                var width = systemInfo.screenWidth * (box.width / visibleSize.width);
                var height = systemInfo.screenHeight * (box.height / visibleSize.height);

                this._openDataContext.postMessage({
                  fromEngine: true,
                  type: 'engine',
                  event: 'viewport',
                  x: x,
                  y: y,
                  width: width,
                  height: height
                });
              };

              _proto._updateSubContextTexture = function _updateSubContextTexture() {
                var img = this._imageAsset;

                if (!img || !this._openDataContext) {
                  return;
                }

                if (img.width <= 0 || img.height <= 0) {
                  return;
                }

                var sharedCanvas = this._openDataContext.canvas;
                img.reset(sharedCanvas);

                if (sharedCanvas.width > img.width || sharedCanvas.height > img.height) {
                  this._imageAsset._texture.create(sharedCanvas.width, sharedCanvas.height);
                }

                this._imageAsset._texture.uploadData(sharedCanvas);
              };

              _proto._registerNodeEvent = function _registerNodeEvent() {
                this.node.on(Node$1.EventType.TRANSFORM_CHANGED, this._updateSubContextView, this);
                this.node.on(Node$1.EventType.SIZE_CHANGED, this._updateSubContextView, this);
                this.node.on(SystemEventType.LAYER_CHANGED, this._updateContentLayer, this);
              };

              _proto._unregisterNodeEvent = function _unregisterNodeEvent() {
                this.node.off(Node$1.EventType.TRANSFORM_CHANGED, this._updateSubContextView, this);
                this.node.off(Node$1.EventType.SIZE_CHANGED, this._updateSubContextView, this);
                this.node.off(SystemEventType.LAYER_CHANGED, this._updateContentLayer, this);
              };

              _proto._updateContentLayer = function _updateContentLayer() {
                this._content.layer = this.node.layer;
              };

              _proto.update = function update(dt) {
                var calledUpdateManually = dt === undefined;

                if (calledUpdateManually) {
                  this._updateSubContextTexture();

                  return;
                }

                var now = performance.now();
                var deltaTime = now - this._updatedTime;

                if (deltaTime >= this._updateInterval) {
                  this._updatedTime += this._updateInterval;

                  this._updateSubContextTexture();
                }
              };

              _createClass(SubContextView, [{
                key: "designResolutionSize",
                get: function get() {
                  return this._designResolutionSize;
                },
                set: function set(value) {
                  {
                    return;
                  }
                }
              }, {
                key: "fps",
                get: function get() {
                  return this._fps;
                },
                set: function set(value) {
                  if (this._fps === value) {
                    return;
                  }

                  this._fps = value;
                  this._updateInterval = 1000 / value;
                }
              }]);

              return SubContextView;
            }(Component), _temp$1f), (_applyDecoratedDescriptor(_class2$1c.prototype, "designResolutionSize", [_dec6$u], Object.getOwnPropertyDescriptor(_class2$1c.prototype, "designResolutionSize"), _class2$1c.prototype), _applyDecoratedDescriptor(_class2$1c.prototype, "fps", [_dec7$s], Object.getOwnPropertyDescriptor(_class2$1c.prototype, "fps"), _class2$1c.prototype), _descriptor$11 = _applyDecoratedDescriptor(_class2$1c.prototype, "_fps", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 60;
              }
            }), _descriptor2$O = _applyDecoratedDescriptor(_class2$1c.prototype, "_designResolutionSize", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new Size(640, 960);
              }
            })), _class2$1c)) || _class$1n) || _class$1n) || _class$1n) || _class$1n) || _class$1n));
            legacyCC.SubContextView = SubContextView;

            var _dec$1n, _class$1o;
            var UIReorderComponent = exports('UIReorderComponent', (_dec$1n = ccclass('cc.UIReorderComponent'), _dec$1n(_class$1o = function UIReorderComponent() {
              warnID(1408, 'UIReorderComponent');
            }) || _class$1o));
            legacyCC.UIReorderComponent = UIReorderComponent;
            legacyCC.ButtonComponent = Button;
            js.setClassAlias(Button, 'cc.ButtonComponent');
            legacyCC.EditBoxComponent = EditBox;
            js.setClassAlias(EditBox, 'cc.EditBoxComponent');
            legacyCC.LayoutComponent = Layout;
            js.setClassAlias(Layout, 'cc.LayoutComponent');
            legacyCC.ProgressBarComponent = ProgressBar;
            js.setClassAlias(ProgressBar, 'cc.ProgressBarComponent');
            legacyCC.ScrollViewComponent = ScrollView;
            js.setClassAlias(ScrollView, 'cc.ScrollViewComponent');
            legacyCC.ScrollBarComponent = ScrollBar;
            js.setClassAlias(ScrollBar, 'cc.ScrollBarComponent');
            legacyCC.SliderComponent = Slider;
            js.setClassAlias(Slider, 'cc.SliderComponent');
            legacyCC.ToggleComponent = Toggle;
            js.setClassAlias(Toggle, 'cc.ToggleComponent');
            legacyCC.ToggleContainerComponent = ToggleContainer;
            js.setClassAlias(ToggleContainer, 'cc.ToggleContainerComponent');
            legacyCC.WidgetComponent = Widget;
            js.setClassAlias(Widget, 'cc.WidgetComponent');
            legacyCC.PageViewComponent = PageView;
            js.setClassAlias(PageView, 'cc.PageViewComponent');
            legacyCC.PageViewIndicatorComponent = PageViewIndicator;
            js.setClassAlias(PageViewIndicator, 'cc.PageViewIndicatorComponent');
            legacyCC.SafeAreaComponent = SafeArea;
            js.setClassAlias(SafeArea, 'cc.SafeAreaComponent');
            js.setClassAlias(UICoordinateTracker, 'cc.UICoordinateTrackerComponent');
            legacyCC.BlockInputEventsComponent = BlockInputEvents;
            js.setClassAlias(BlockInputEvents, 'cc.BlockInputEventsComponent');

            var WRAPPER;
            var physicsEngineId;
            function select(id, wrapper) {
              physicsEngineId = id;
              legacyCC._global.CC_PHYSICS_2D_BUILTIN = id == 'builtin';
              legacyCC._global.CC_PHYSICS_2D_BOX2D = id == 'box2d';
              WRAPPER = wrapper;
            }

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

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

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

            var box2d_umd=createCommonjsModule(function(module,exports){(function(global,factory){factory(exports);})(commonjsGlobal,function(exports){function b2Assert(condition){if(!condition){for(var _len=arguments.length,args=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++){args[_key-1]=arguments[_key];}throw _construct(Error,args);}}function b2Maybe(value,def){return value!==undefined?value:def;}var b2_maxFloat=1E+37;var b2_epsilon=1E-5;var b2_epsilon_sq=b2_epsilon*b2_epsilon;var b2_pi=3.14159265359;var b2_maxManifoldPoints=2;var b2_maxPolygonVertices=8;var b2_aabbExtension=0.1;var b2_aabbMultiplier=2;var b2_linearSlop=0.008;var b2_angularSlop=2/180*b2_pi;var b2_polygonRadius=2*b2_linearSlop;var b2_maxSubSteps=8;var b2_maxTOIContacts=32;var b2_velocityThreshold=1;var b2_maxLinearCorrection=0.2;var b2_maxAngularCorrection=8/180*b2_pi;var b2_maxTranslation=2;var b2_maxTranslationSquared=b2_maxTranslation*b2_maxTranslation;var b2_maxRotation=0.5*b2_pi;var b2_maxRotationSquared=b2_maxRotation*b2_maxRotation;var b2_baumgarte=0.2;var b2_toiBaumgarte=0.75;var b2_invalidParticleIndex=-1;var b2_maxParticleIndex=0x7FFFFFFF;var b2_particleStride=0.75;var b2_minParticleWeight=1.0;var b2_maxParticlePressure=0.25;var b2_maxParticleForce=0.5;var b2_maxTriadDistance=2.0;var b2_maxTriadDistanceSquared=b2_maxTriadDistance*b2_maxTriadDistance;var b2_minParticleSystemBufferCapacity=256;var b2_barrierCollisionTime=2.5;var b2_timeToSleep=0.5;var b2_linearSleepTolerance=0.01;var b2_angularSleepTolerance=2/180*b2_pi;function b2Alloc(size){return null;}function b2Free(mem){}function b2Log(message){}var b2Version=function(){function b2Version(major,minor,revision){if(major===void 0){major=0;}if(minor===void 0){minor=0;}if(revision===void 0){revision=0;}this.major=0;this.minor=0;this.revision=0;this.major=major;this.minor=minor;this.revision=revision;}var _proto=b2Version.prototype;_proto.toString=function toString(){return this.major+"."+this.minor+"."+this.revision;};return b2Version;}();var b2_version=new b2Version(2,3,2);var b2_branch="master";var b2_commit="fbf51801d80fc389d43dc46524520e89043b6faf";function b2ParseInt(v){return parseInt(v,10);}function b2ParseUInt(v){return Math.abs(parseInt(v,10));}function b2MakeArray(length,init){var a=new Array(length);for(var i=0;i<length;++i){a[i]=init(i);}return a;}function b2MakeNullArray(length){var a=new Array(length);for(var i=0;i<length;++i){a[i]=null;}return a;}function b2MakeNumberArray(length,init){if(init===void 0){init=0;}var a=new Array(length);for(var i=0;i<length;++i){a[i]=init;}return a;}var b2_pi_over_180=b2_pi/180;var b2_180_over_pi=180/b2_pi;var b2_two_pi=2*b2_pi;var 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){var tmp=a[0];a[0]=b[0];b[0]=tmp;}var b2IsValid=isFinite;function b2Sq(n){return n*n;}function b2InvSqrt(n){return 1/Math.sqrt(n);}var b2Sqrt=Math.sqrt;var b2Pow=Math.pow;function b2DegToRad(degrees){return degrees*b2_pi_over_180;}function b2RadToDeg(radians){return radians*b2_180_over_pi;}var b2Cos=Math.cos;var b2Sin=Math.sin;var b2Acos=Math.acos;var b2Asin=Math.asin;var 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;}var b2Vec2=function(){function b2Vec2(){for(var _len2=arguments.length,args=new Array(_len2),_key2=0;_key2<_len2;_key2++){args[_key2]=arguments[_key2];}if(args[0]instanceof Float32Array){if(args[0].length!==2){throw new Error();}this.data=args[0];}else {var x=typeof args[0]==="number"?args[0]:0;var y=typeof args[1]==="number"?args[1]:0;this.data=new Float32Array([x,y]);}}var _proto2=b2Vec2.prototype;_proto2.Clone=function Clone(){return new b2Vec2(this.x,this.y);};_proto2.SetZero=function SetZero(){this.x=0;this.y=0;return this;};_proto2.Set=function Set(x,y){this.x=x;this.y=y;return this;};_proto2.Copy=function Copy(other){this.x=other.x;this.y=other.y;return this;};_proto2.SelfAdd=function SelfAdd(v){this.x+=v.x;this.y+=v.y;return this;};_proto2.SelfAddXY=function SelfAddXY(x,y){this.x+=x;this.y+=y;return this;};_proto2.SelfSub=function SelfSub(v){this.x-=v.x;this.y-=v.y;return this;};_proto2.SelfSubXY=function SelfSubXY(x,y){this.x-=x;this.y-=y;return this;};_proto2.SelfMul=function SelfMul(s){this.x*=s;this.y*=s;return this;};_proto2.SelfMulAdd=function SelfMulAdd(s,v){this.x+=s*v.x;this.y+=s*v.y;return this;};_proto2.SelfMulSub=function SelfMulSub(s,v){this.x-=s*v.x;this.y-=s*v.y;return this;};_proto2.Dot=function Dot(v){return this.x*v.x+this.y*v.y;};_proto2.Cross=function Cross(v){return this.x*v.y-this.y*v.x;};_proto2.Length=function Length(){var x=this.x,y=this.y;return Math.sqrt(x*x+y*y);};_proto2.LengthSquared=function LengthSquared(){var x=this.x,y=this.y;return x*x+y*y;};_proto2.Normalize=function Normalize(){var length=this.Length();if(length>=b2_epsilon){var inv_length=1/length;this.x*=inv_length;this.y*=inv_length;}return length;};_proto2.SelfNormalize=function SelfNormalize(){var length=this.Length();if(length>=b2_epsilon){var inv_length=1/length;this.x*=inv_length;this.y*=inv_length;}return this;};_proto2.SelfRotate=function SelfRotate(radians){var c=Math.cos(radians);var s=Math.sin(radians);var x=this.x;this.x=c*x-s*this.y;this.y=s*x+c*this.y;return this;};_proto2.SelfRotateCosSin=function SelfRotateCosSin(c,s){var x=this.x;this.x=c*x-s*this.y;this.y=s*x+c*this.y;return this;};_proto2.IsValid=function IsValid(){return isFinite(this.x)&&isFinite(this.y);};_proto2.SelfCrossVS=function SelfCrossVS(s){var x=this.x;this.x=s*this.y;this.y=-s*x;return this;};_proto2.SelfCrossSV=function SelfCrossSV(s){var x=this.x;this.x=-s*this.y;this.y=s*x;return this;};_proto2.SelfMinV=function SelfMinV(v){this.x=b2Min(this.x,v.x);this.y=b2Min(this.y,v.y);return this;};_proto2.SelfMaxV=function SelfMaxV(v){this.x=b2Max(this.x,v.x);this.y=b2Max(this.y,v.y);return this;};_proto2.SelfAbs=function SelfAbs(){this.x=b2Abs(this.x);this.y=b2Abs(this.y);return this;};_proto2.SelfNeg=function SelfNeg(){this.x=-this.x;this.y=-this.y;return this;};_proto2.SelfSkew=function SelfSkew(){var x=this.x;this.x=-this.y;this.y=x;return this;};b2Vec2.MakeArray=function MakeArray(length){return b2MakeArray(length,function(i){return new b2Vec2();});};b2Vec2.AbsV=function AbsV(v,out){out.x=b2Abs(v.x);out.y=b2Abs(v.y);return out;};b2Vec2.MinV=function MinV(a,b,out){out.x=b2Min(a.x,b.x);out.y=b2Min(a.y,b.y);return out;};b2Vec2.MaxV=function MaxV(a,b,out){out.x=b2Max(a.x,b.x);out.y=b2Max(a.y,b.y);return out;};b2Vec2.ClampV=function 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;};b2Vec2.RotateV=function RotateV(v,radians,out){var v_x=v.x,v_y=v.y;var c=Math.cos(radians);var s=Math.sin(radians);out.x=c*v_x-s*v_y;out.y=s*v_x+c*v_y;return out;};b2Vec2.DotVV=function DotVV(a,b){return a.x*b.x+a.y*b.y;};b2Vec2.CrossVV=function CrossVV(a,b){return a.x*b.y-a.y*b.x;};b2Vec2.CrossVS=function CrossVS(v,s,out){var v_x=v.x;out.x=s*v.y;out.y=-s*v_x;return out;};b2Vec2.CrossVOne=function CrossVOne(v,out){var v_x=v.x;out.x=v.y;out.y=-v_x;return out;};b2Vec2.CrossSV=function CrossSV(s,v,out){var v_x=v.x;out.x=-s*v.y;out.y=s*v_x;return out;};b2Vec2.CrossOneV=function CrossOneV(v,out){var v_x=v.x;out.x=-v.y;out.y=v_x;return out;};b2Vec2.AddVV=function AddVV(a,b,out){out.x=a.x+b.x;out.y=a.y+b.y;return out;};b2Vec2.SubVV=function SubVV(a,b,out){out.x=a.x-b.x;out.y=a.y-b.y;return out;};b2Vec2.MulSV=function MulSV(s,v,out){out.x=v.x*s;out.y=v.y*s;return out;};b2Vec2.MulVS=function MulVS(v,s,out){out.x=v.x*s;out.y=v.y*s;return out;};b2Vec2.AddVMulSV=function AddVMulSV(a,s,b,out){out.x=a.x+s*b.x;out.y=a.y+s*b.y;return out;};b2Vec2.SubVMulSV=function SubVMulSV(a,s,b,out){out.x=a.x-s*b.x;out.y=a.y-s*b.y;return out;};b2Vec2.AddVCrossSV=function AddVCrossSV(a,s,v,out){var v_x=v.x;out.x=a.x-s*v.y;out.y=a.y+s*v_x;return out;};b2Vec2.MidVV=function MidVV(a,b,out){out.x=(a.x+b.x)*0.5;out.y=(a.y+b.y)*0.5;return out;};b2Vec2.ExtVV=function ExtVV(a,b,out){out.x=(b.x-a.x)*0.5;out.y=(b.y-a.y)*0.5;return out;};b2Vec2.IsEqualToV=function IsEqualToV(a,b){return a.x===b.x&&a.y===b.y;};b2Vec2.DistanceVV=function DistanceVV(a,b){var c_x=a.x-b.x;var c_y=a.y-b.y;return Math.sqrt(c_x*c_x+c_y*c_y);};b2Vec2.DistanceSquaredVV=function DistanceSquaredVV(a,b){var c_x=a.x-b.x;var c_y=a.y-b.y;return c_x*c_x+c_y*c_y;};b2Vec2.NegV=function NegV(v,out){out.x=-v.x;out.y=-v.y;return out;};_createClass(b2Vec2,[{key:"x",get:function get(){return this.data[0];},set:function set(value){this.data[0]=value;}},{key:"y",get:function get(){return this.data[1];},set:function set(value){this.data[1]=value;}}]);return b2Vec2;}();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();var b2Vec2_zero=new b2Vec2(0,0);var b2Vec3=function(){function b2Vec3(){for(var _len3=arguments.length,args=new Array(_len3),_key3=0;_key3<_len3;_key3++){args[_key3]=arguments[_key3];}if(args[0]instanceof Float32Array){if(args[0].length!==3){throw new Error();}this.data=args[0];}else {var x=typeof args[0]==="number"?args[0]:0;var y=typeof args[1]==="number"?args[1]:0;var z=typeof args[2]==="number"?args[2]:0;this.data=new Float32Array([x,y,z]);}}var _proto3=b2Vec3.prototype;_proto3.Clone=function Clone(){return new b2Vec3(this.x,this.y,this.z);};_proto3.SetZero=function SetZero(){this.x=0;this.y=0;this.z=0;return this;};_proto3.SetXYZ=function SetXYZ(x,y,z){this.x=x;this.y=y;this.z=z;return this;};_proto3.Copy=function Copy(other){this.x=other.x;this.y=other.y;this.z=other.z;return this;};_proto3.SelfNeg=function SelfNeg(){this.x=-this.x;this.y=-this.y;this.z=-this.z;return this;};_proto3.SelfAdd=function SelfAdd(v){this.x+=v.x;this.y+=v.y;this.z+=v.z;return this;};_proto3.SelfAddXYZ=function SelfAddXYZ(x,y,z){this.x+=x;this.y+=y;this.z+=z;return this;};_proto3.SelfSub=function SelfSub(v){this.x-=v.x;this.y-=v.y;this.z-=v.z;return this;};_proto3.SelfSubXYZ=function SelfSubXYZ(x,y,z){this.x-=x;this.y-=y;this.z-=z;return this;};_proto3.SelfMul=function SelfMul(s){this.x*=s;this.y*=s;this.z*=s;return this;};b2Vec3.DotV3V3=function DotV3V3(a,b){return a.x*b.x+a.y*b.y+a.z*b.z;};b2Vec3.CrossV3V3=function CrossV3V3(a,b,out){var a_x=a.x,a_y=a.y,a_z=a.z;var 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;};_createClass(b2Vec3,[{key:"x",get:function get(){return this.data[0];},set:function set(value){this.data[0]=value;}},{key:"y",get:function get(){return this.data[1];},set:function set(value){this.data[1]=value;}},{key:"z",get:function get(){return this.data[2];},set:function set(value){this.data[2]=value;}}]);return b2Vec3;}();b2Vec3.ZERO=new b2Vec3(0,0,0);b2Vec3.s_t0=new b2Vec3();var b2Mat22=function(){function b2Mat22(){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));}var _proto4=b2Mat22.prototype;_proto4.Clone=function Clone(){return new b2Mat22().Copy(this);};b2Mat22.FromVV=function FromVV(c1,c2){return new b2Mat22().SetVV(c1,c2);};b2Mat22.FromSSSS=function FromSSSS(r1c1,r1c2,r2c1,r2c2){return new b2Mat22().SetSSSS(r1c1,r1c2,r2c1,r2c2);};b2Mat22.FromAngle=function FromAngle(radians){return new b2Mat22().SetAngle(radians);};_proto4.SetSSSS=function SetSSSS(r1c1,r1c2,r2c1,r2c2){this.ex.Set(r1c1,r2c1);this.ey.Set(r1c2,r2c2);return this;};_proto4.SetVV=function SetVV(c1,c2){this.ex.Copy(c1);this.ey.Copy(c2);return this;};_proto4.SetAngle=function SetAngle(radians){var c=Math.cos(radians);var s=Math.sin(radians);this.ex.Set(c,s);this.ey.Set(-s,c);return this;};_proto4.Copy=function Copy(other){this.ex.Copy(other.ex);this.ey.Copy(other.ey);return this;};_proto4.SetIdentity=function SetIdentity(){this.ex.Set(1,0);this.ey.Set(0,1);return this;};_proto4.SetZero=function SetZero(){this.ex.SetZero();this.ey.SetZero();return this;};_proto4.GetAngle=function GetAngle(){return Math.atan2(this.ex.y,this.ex.x);};_proto4.GetInverse=function GetInverse(out){var a=this.ex.x;var b=this.ey.x;var c=this.ex.y;var d=this.ey.y;var 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;};_proto4.Solve=function Solve(b_x,b_y,out){var a11=this.ex.x,a12=this.ey.x;var a21=this.ex.y,a22=this.ey.y;var 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;};_proto4.SelfAbs=function SelfAbs(){this.ex.SelfAbs();this.ey.SelfAbs();return this;};_proto4.SelfInv=function SelfInv(){this.GetInverse(this);return this;};_proto4.SelfAddM=function SelfAddM(M){this.ex.SelfAdd(M.ex);this.ey.SelfAdd(M.ey);return this;};_proto4.SelfSubM=function SelfSubM(M){this.ex.SelfSub(M.ex);this.ey.SelfSub(M.ey);return this;};b2Mat22.AbsM=function AbsM(M,out){var 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;};b2Mat22.MulMV=function MulMV(M,v,out){var M_ex=M.ex,M_ey=M.ey;var 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;};b2Mat22.MulTMV=function MulTMV(M,v,out){var M_ex=M.ex,M_ey=M.ey;var 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;};b2Mat22.AddMM=function AddMM(A,B,out){var A_ex=A.ex,A_ey=A.ey;var 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;};b2Mat22.MulMM=function MulMM(A,B,out){var A_ex_x=A.ex.x,A_ex_y=A.ex.y;var A_ey_x=A.ey.x,A_ey_y=A.ey.y;var B_ex_x=B.ex.x,B_ex_y=B.ex.y;var 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;};b2Mat22.MulTMM=function MulTMM(A,B,out){var A_ex_x=A.ex.x,A_ex_y=A.ex.y;var A_ey_x=A.ey.x,A_ey_y=A.ey.y;var B_ex_x=B.ex.x,B_ex_y=B.ex.y;var 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;};return b2Mat22;}();b2Mat22.IDENTITY=new b2Mat22();var b2Mat33=function(){function b2Mat33(){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));}var _proto5=b2Mat33.prototype;_proto5.Clone=function Clone(){return new b2Mat33().Copy(this);};_proto5.SetVVV=function SetVVV(c1,c2,c3){this.ex.Copy(c1);this.ey.Copy(c2);this.ez.Copy(c3);return this;};_proto5.Copy=function Copy(other){this.ex.Copy(other.ex);this.ey.Copy(other.ey);this.ez.Copy(other.ez);return this;};_proto5.SetIdentity=function SetIdentity(){this.ex.SetXYZ(1,0,0);this.ey.SetXYZ(0,1,0);this.ez.SetXYZ(0,0,1);return this;};_proto5.SetZero=function SetZero(){this.ex.SetZero();this.ey.SetZero();this.ez.SetZero();return this;};_proto5.SelfAddM=function SelfAddM(M){this.ex.SelfAdd(M.ex);this.ey.SelfAdd(M.ey);this.ez.SelfAdd(M.ez);return this;};_proto5.Solve33=function Solve33(b_x,b_y,b_z,out){var a11=this.ex.x,a21=this.ex.y,a31=this.ex.z;var a12=this.ey.x,a22=this.ey.y,a32=this.ey.z;var a13=this.ez.x,a23=this.ez.y,a33=this.ez.z;var 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;};_proto5.Solve22=function Solve22(b_x,b_y,out){var a11=this.ex.x,a12=this.ey.x;var a21=this.ex.y,a22=this.ey.y;var 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;};_proto5.GetInverse22=function GetInverse22(M){var a=this.ex.x,b=this.ey.x,c=this.ex.y,d=this.ey.y;var 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;};_proto5.GetSymInverse33=function GetSymInverse33(M){var det=b2Vec3.DotV3V3(this.ex,b2Vec3.CrossV3V3(this.ey,this.ez,b2Vec3.s_t0));if(det!==0){det=1/det;}var a11=this.ex.x,a12=this.ey.x,a13=this.ez.x;var a22=this.ey.y,a23=this.ez.y;var 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);};b2Mat33.MulM33V3=function MulM33V3(A,v,out){var 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;};b2Mat33.MulM33XYZ=function 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;};b2Mat33.MulM33V2=function MulM33V2(A,v,out){var 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;};b2Mat33.MulM33XY=function 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;};return b2Mat33;}();b2Mat33.IDENTITY=new b2Mat33();var b2Rot=function(){function b2Rot(angle){if(angle===void 0){angle=0;}this.s=0;this.c=1;if(angle){this.s=Math.sin(angle);this.c=Math.cos(angle);}}var _proto6=b2Rot.prototype;_proto6.Clone=function Clone(){return new b2Rot().Copy(this);};_proto6.Copy=function Copy(other){this.s=other.s;this.c=other.c;return this;};_proto6.SetAngle=function SetAngle(angle){this.s=Math.sin(angle);this.c=Math.cos(angle);return this;};_proto6.SetIdentity=function SetIdentity(){this.s=0;this.c=1;return this;};_proto6.GetAngle=function GetAngle(){return Math.atan2(this.s,this.c);};_proto6.GetXAxis=function GetXAxis(out){out.x=this.c;out.y=this.s;return out;};_proto6.GetYAxis=function GetYAxis(out){out.x=-this.s;out.y=this.c;return out;};b2Rot.MulRR=function MulRR(q,r,out){var q_c=q.c,q_s=q.s;var 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;};b2Rot.MulTRR=function MulTRR(q,r,out){var q_c=q.c,q_s=q.s;var 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;};b2Rot.MulRV=function MulRV(q,v,out){var q_c=q.c,q_s=q.s;var 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.MulTRV=function MulTRV(q,v,out){var q_c=q.c,q_s=q.s;var 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;};return b2Rot;}();b2Rot.IDENTITY=new b2Rot();var b2Transform=function(){function b2Transform(){this.p=new b2Vec2();this.q=new b2Rot();}var _proto7=b2Transform.prototype;_proto7.Clone=function Clone(){return new b2Transform().Copy(this);};_proto7.Copy=function Copy(other){this.p.Copy(other.p);this.q.Copy(other.q);return this;};_proto7.SetIdentity=function SetIdentity(){this.p.SetZero();this.q.SetIdentity();return this;};_proto7.SetPositionRotation=function SetPositionRotation(position,q){this.p.Copy(position);this.q.Copy(q);return this;};_proto7.SetPositionAngle=function SetPositionAngle(pos,a){this.p.Copy(pos);this.q.SetAngle(a);return this;};_proto7.SetPosition=function SetPosition(position){this.p.Copy(position);return this;};_proto7.SetPositionXY=function SetPositionXY(x,y){this.p.Set(x,y);return this;};_proto7.SetRotation=function SetRotation(rotation){this.q.Copy(rotation);return this;};_proto7.SetRotationAngle=function SetRotationAngle(radians){this.q.SetAngle(radians);return this;};_proto7.GetPosition=function GetPosition(){return this.p;};_proto7.GetRotation=function GetRotation(){return this.q;};_proto7.GetRotationAngle=function GetRotationAngle(){return this.q.GetAngle();};_proto7.GetAngle=function GetAngle(){return this.q.GetAngle();};b2Transform.MulXV=function MulXV(T,v,out){var T_q_c=T.q.c,T_q_s=T.q.s;var 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;};b2Transform.MulTXV=function MulTXV(T,v,out){var T_q_c=T.q.c,T_q_s=T.q.s;var p_x=v.x-T.p.x;var 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;};b2Transform.MulXX=function 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;};b2Transform.MulTXX=function 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;};return b2Transform;}();b2Transform.IDENTITY=new b2Transform();var b2Sweep=function(){function b2Sweep(){this.localCenter=new b2Vec2();this.c0=new b2Vec2();this.c=new b2Vec2();this.a0=0;this.a=0;this.alpha0=0;}var _proto8=b2Sweep.prototype;_proto8.Clone=function Clone(){return new b2Sweep().Copy(this);};_proto8.Copy=function 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;};_proto8.GetTransform=function GetTransform(xf,beta){var 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;var 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;};_proto8.Advance=function Advance(alpha){var beta=(alpha-this.alpha0)/(1-this.alpha0);var 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;};_proto8.Normalize=function Normalize(){var d=b2_two_pi*Math.floor(this.a0/b2_two_pi);this.a0-=d;this.a-=d;};return b2Sweep;}();var b2Color=function(){function b2Color(){for(var _len4=arguments.length,args=new Array(_len4),_key4=0;_key4<_len4;_key4++){args[_key4]=arguments[_key4];}if(args[0]instanceof Float32Array){if(args[0].length!==4){throw new Error();}this.data=args[0];}else {var rr=typeof args[0]==="number"?args[0]:0.5;var gg=typeof args[1]==="number"?args[1]:0.5;var bb=typeof args[2]==="number"?args[2]:0.5;var aa=typeof args[3]==="number"?args[3]:1.0;this.data=new Float32Array([rr,gg,bb,aa]);}}var _proto9=b2Color.prototype;_proto9.Clone=function Clone(){return new b2Color().Copy(this);};_proto9.Copy=function Copy(other){this.r=other.r;this.g=other.g;this.b=other.b;this.a=other.a;return this;};_proto9.IsEqual=function IsEqual(color){return this.r===color.r&&this.g===color.g&&this.b===color.b&&this.a===color.a;};_proto9.IsZero=function IsZero(){return this.r===0&&this.g===0&&this.b===0&&this.a===0;};_proto9.Set=function Set(r,g,b,a){if(a===void 0){a=this.a;}this.SetRGBA(r,g,b,a);};_proto9.SetByteRGB=function SetByteRGB(r,g,b){this.r=r/0xff;this.g=g/0xff;this.b=b/0xff;return this;};_proto9.SetByteRGBA=function SetByteRGBA(r,g,b,a){this.r=r/0xff;this.g=g/0xff;this.b=b/0xff;this.a=a/0xff;return this;};_proto9.SetRGB=function SetRGB(rr,gg,bb){this.r=rr;this.g=gg;this.b=bb;return this;};_proto9.SetRGBA=function SetRGBA(rr,gg,bb,aa){this.r=rr;this.g=gg;this.b=bb;this.a=aa;return this;};_proto9.SelfAdd=function SelfAdd(color){this.r+=color.r;this.g+=color.g;this.b+=color.b;this.a+=color.a;return this;};_proto9.Add=function 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;};_proto9.SelfSub=function SelfSub(color){this.r-=color.r;this.g-=color.g;this.b-=color.b;this.a-=color.a;return this;};_proto9.Sub=function 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;};_proto9.SelfMul=function SelfMul(s){this.r*=s;this.g*=s;this.b*=s;this.a*=s;return this;};_proto9.Mul=function 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;};_proto9.Mix=function Mix(mixColor,strength){b2Color.MixColors(this,mixColor,strength);};b2Color.MixColors=function MixColors(colorA,colorB,strength){var dr=strength*(colorB.r-colorA.r);var dg=strength*(colorB.g-colorA.g);var db=strength*(colorB.b-colorA.b);var 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;};_proto9.MakeStyleString=function MakeStyleString(alpha){if(alpha===void 0){alpha=this.a;}return b2Color.MakeStyleString(this.r,this.g,this.b,alpha);};b2Color.MakeStyleString=function MakeStyleString(r,g,b,a){if(a===void 0){a=1.0;}r*=255;g*=255;b*=255;if(a<1){return "rgba("+r+","+g+","+b+","+a+")";}else {return "rgb("+r+","+g+","+b+")";}};_createClass(b2Color,[{key:"r",get:function get(){return this.data[0];},set:function set(value){this.data[0]=value;}},{key:"g",get:function get(){return this.data[1];},set:function set(value){this.data[1]=value;}},{key:"b",get:function get(){return this.data[2];},set:function set(value){this.data[2]=value;}},{key:"a",get:function get(){return this.data[3];},set:function set(value){this.data[3]=value;}}]);return b2Color;}();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={}));var b2Draw=function(){function b2Draw(){this.m_drawFlags=0;}var _proto10=b2Draw.prototype;_proto10.SetFlags=function SetFlags(flags){this.m_drawFlags=flags;};_proto10.GetFlags=function GetFlags(){return this.m_drawFlags;};_proto10.AppendFlags=function AppendFlags(flags){this.m_drawFlags|=flags;};_proto10.ClearFlags=function ClearFlags(flags){this.m_drawFlags&=~flags;};return b2Draw;}();var b2Timer=function(){function b2Timer(){this.m_start=Date.now();}var _proto11=b2Timer.prototype;_proto11.Reset=function Reset(){this.m_start=Date.now();return this;};_proto11.GetMilliseconds=function GetMilliseconds(){return Date.now()-this.m_start;};return b2Timer;}();var b2Counter=function(){function b2Counter(){this.m_count=0;this.m_min_count=0;this.m_max_count=0;}var _proto12=b2Counter.prototype;_proto12.GetCount=function GetCount(){return this.m_count;};_proto12.GetMinCount=function GetMinCount(){return this.m_min_count;};_proto12.GetMaxCount=function GetMaxCount(){return this.m_max_count;};_proto12.ResetCount=function ResetCount(){var count=this.m_count;this.m_count=0;return count;};_proto12.ResetMinCount=function ResetMinCount(){this.m_min_count=0;};_proto12.ResetMaxCount=function ResetMaxCount(){this.m_max_count=0;};_proto12.Increment=function Increment(){this.m_count++;if(this.m_max_count<this.m_count){this.m_max_count=this.m_count;}};_proto12.Decrement=function Decrement(){this.m_count--;if(this.m_min_count>this.m_count){this.m_min_count=this.m_count;}};return b2Counter;}();var b2GrowableStack=function(){function b2GrowableStack(N){this.m_stack=[];this.m_count=0;this.m_stack=b2MakeArray(N,function(index){return null;});this.m_count=0;}var _proto13=b2GrowableStack.prototype;_proto13.Reset=function Reset(){this.m_count=0;return this;};_proto13.Push=function Push(element){this.m_stack[this.m_count]=element;this.m_count++;};_proto13.Pop=function Pop(){this.m_count--;var element=this.m_stack[this.m_count];this.m_stack[this.m_count]=null;if(element===null){throw new Error();}return element;};_proto13.GetCount=function GetCount(){return this.m_count;};return b2GrowableStack;}();var b2BlockAllocator=function b2BlockAllocator(){};var b2StackAllocator=function b2StackAllocator(){};var b2DistanceProxy=function(){function b2DistanceProxy(){this.m_buffer=b2Vec2.MakeArray(2);this.m_vertices=this.m_buffer;this.m_count=0;this.m_radius=0;}var _proto14=b2DistanceProxy.prototype;_proto14.Copy=function 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;};_proto14.Reset=function Reset(){this.m_vertices=this.m_buffer;this.m_count=0;this.m_radius=0;return this;};_proto14.SetShape=function SetShape(shape,index){shape.SetupDistanceProxy(this,index);};_proto14.SetVerticesRadius=function SetVerticesRadius(vertices,count,radius){this.m_vertices=vertices;this.m_count=count;this.m_radius=radius;};_proto14.GetSupport=function GetSupport(d){var bestIndex=0;var bestValue=b2Vec2.DotVV(this.m_vertices[0],d);for(var i=1;i<this.m_count;++i){var value=b2Vec2.DotVV(this.m_vertices[i],d);if(value>bestValue){bestIndex=i;bestValue=value;}}return bestIndex;};_proto14.GetSupportVertex=function GetSupportVertex(d){var bestIndex=0;var bestValue=b2Vec2.DotVV(this.m_vertices[0],d);for(var i=1;i<this.m_count;++i){var value=b2Vec2.DotVV(this.m_vertices[i],d);if(value>bestValue){bestIndex=i;bestValue=value;}}return this.m_vertices[bestIndex];};_proto14.GetVertexCount=function GetVertexCount(){return this.m_count;};_proto14.GetVertex=function GetVertex(index){return this.m_vertices[index];};return b2DistanceProxy;}();var b2SimplexCache=function(){function b2SimplexCache(){this.metric=0;this.count=0;this.indexA=[0,0,0];this.indexB=[0,0,0];}var _proto15=b2SimplexCache.prototype;_proto15.Reset=function Reset(){this.metric=0;this.count=0;return this;};return b2SimplexCache;}();var b2DistanceInput=function(){function b2DistanceInput(){this.proxyA=new b2DistanceProxy();this.proxyB=new b2DistanceProxy();this.transformA=new b2Transform();this.transformB=new b2Transform();this.useRadii=false;}var _proto16=b2DistanceInput.prototype;_proto16.Reset=function Reset(){this.proxyA.Reset();this.proxyB.Reset();this.transformA.SetIdentity();this.transformB.SetIdentity();this.useRadii=false;return this;};return b2DistanceInput;}();var b2DistanceOutput=function(){function b2DistanceOutput(){this.pointA=new b2Vec2();this.pointB=new b2Vec2();this.distance=0;this.iterations=0;}var _proto17=b2DistanceOutput.prototype;_proto17.Reset=function Reset(){this.pointA.SetZero();this.pointB.SetZero();this.distance=0;this.iterations=0;return this;};return b2DistanceOutput;}();var b2ShapeCastInput=function b2ShapeCastInput(){this.proxyA=new b2DistanceProxy();this.proxyB=new b2DistanceProxy();this.transformA=new b2Transform();this.transformB=new b2Transform();this.translationB=new b2Vec2();};var b2ShapeCastOutput=function b2ShapeCastOutput(){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;}var b2SimplexVertex=function(){function b2SimplexVertex(){this.wA=new b2Vec2();this.wB=new b2Vec2();this.w=new b2Vec2();this.a=0;this.indexA=0;this.indexB=0;}var _proto18=b2SimplexVertex.prototype;_proto18.Copy=function 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;};return b2SimplexVertex;}();var b2Simplex=function(){function b2Simplex(){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;}var _proto19=b2Simplex.prototype;_proto19.ReadCache=function ReadCache(cache,proxyA,transformA,proxyB,transformB){this.m_count=cache.count;var vertices=this.m_vertices;for(var i=0;i<this.m_count;++i){var v=vertices[i];v.indexA=cache.indexA[i];v.indexB=cache.indexB[i];var wALocal=proxyA.GetVertex(v.indexA);var 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){var metric1=cache.metric;var metric2=this.GetMetric();if(metric2<0.5*metric1||2*metric1<metric2||metric2<b2_epsilon){this.m_count=0;}}if(this.m_count===0){var _v=vertices[0];_v.indexA=0;_v.indexB=0;var _wALocal=proxyA.GetVertex(0);var _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;}};_proto19.WriteCache=function WriteCache(cache){cache.metric=this.GetMetric();cache.count=this.m_count;var vertices=this.m_vertices;for(var i=0;i<this.m_count;++i){cache.indexA[i]=vertices[i].indexA;cache.indexB[i]=vertices[i].indexB;}};_proto19.GetSearchDirection=function GetSearchDirection(out){switch(this.m_count){case 1:return b2Vec2.NegV(this.m_v1.w,out);case 2:{var e12=b2Vec2.SubVV(this.m_v2.w,this.m_v1.w,out);var 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();}};_proto19.GetClosestPoint=function 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();}};_proto19.GetWitnessPoints=function 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;}};_proto19.GetMetric=function 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;}};_proto19.Solve2=function Solve2(){var w1=this.m_v1.w;var w2=this.m_v2.w;var e12=b2Vec2.SubVV(w2,w1,b2Simplex.s_e12);var d12_2=-b2Vec2.DotVV(w1,e12);if(d12_2<=0){this.m_v1.a=1;this.m_count=1;return;}var 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;}var 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;};_proto19.Solve3=function Solve3(){var w1=this.m_v1.w;var w2=this.m_v2.w;var w3=this.m_v3.w;var e12=b2Vec2.SubVV(w2,w1,b2Simplex.s_e12);var w1e12=b2Vec2.DotVV(w1,e12);var w2e12=b2Vec2.DotVV(w2,e12);var d12_1=w2e12;var d12_2=-w1e12;var e13=b2Vec2.SubVV(w3,w1,b2Simplex.s_e13);var w1e13=b2Vec2.DotVV(w1,e13);var w3e13=b2Vec2.DotVV(w3,e13);var d13_1=w3e13;var d13_2=-w1e13;var e23=b2Vec2.SubVV(w3,w2,b2Simplex.s_e23);var w2e23=b2Vec2.DotVV(w2,e23);var w3e23=b2Vec2.DotVV(w3,e23);var d23_1=w3e23;var d23_2=-w2e23;var n123=b2Vec2.CrossVV(e12,e13);var d123_1=n123*b2Vec2.CrossVV(w2,w3);var d123_2=n123*b2Vec2.CrossVV(w3,w1);var 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){var 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){var 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){var 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;}var 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;};return b2Simplex;}();b2Simplex.s_e12=new b2Vec2();b2Simplex.s_e13=new b2Vec2();b2Simplex.s_e23=new b2Vec2();var b2Distance_s_simplex=new b2Simplex();var b2Distance_s_saveA=[0,0,0];var b2Distance_s_saveB=[0,0,0];var b2Distance_s_p=new b2Vec2();var b2Distance_s_d=new b2Vec2();var b2Distance_s_normal=new b2Vec2();var b2Distance_s_supportA=new b2Vec2();var b2Distance_s_supportB=new b2Vec2();function b2Distance(output,cache,input){++exports.b2_gjkCalls;var proxyA=input.proxyA;var proxyB=input.proxyB;var transformA=input.transformA;var transformB=input.transformB;var simplex=b2Distance_s_simplex;simplex.ReadCache(cache,proxyA,transformA,proxyB,transformB);var vertices=simplex.m_vertices;var k_maxIters=20;var saveA=b2Distance_s_saveA;var saveB=b2Distance_s_saveB;var saveCount=0;var iter=0;while(iter<k_maxIters){saveCount=simplex.m_count;for(var 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;}var d=simplex.GetSearchDirection(b2Distance_s_d);if(d.LengthSquared()<b2_epsilon_sq){break;}var 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;var duplicate=false;for(var _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){var rA=proxyA.m_radius;var rB=proxyB.m_radius;if(output.distance>rA+rB&&output.distance>b2_epsilon){output.distance-=rA+rB;var normal=b2Vec2.SubVV(output.pointB,output.pointA,b2Distance_s_normal);normal.Normalize();output.pointA.SelfMulAdd(rA,normal);output.pointB.SelfMulSub(rB,normal);}else {var p=b2Vec2.MidVV(output.pointA,output.pointB,b2Distance_s_p);output.pointA.Copy(p);output.pointB.Copy(p);output.distance=0;}}}var b2ShapeCast_s_n=new b2Vec2();var b2ShapeCast_s_simplex=new b2Simplex();var b2ShapeCast_s_wA=new b2Vec2();var b2ShapeCast_s_wB=new b2Vec2();var b2ShapeCast_s_v=new b2Vec2();var b2ShapeCast_s_p=new b2Vec2();var b2ShapeCast_s_pointA=new b2Vec2();var b2ShapeCast_s_pointB=new b2Vec2();function b2ShapeCast(output,input){output.iterations=0;output.lambda=1.0;output.normal.SetZero();output.point.SetZero();var proxyA=input.proxyA;var proxyB=input.proxyB;var radiusA=b2Max(proxyA.m_radius,b2_polygonRadius);var radiusB=b2Max(proxyB.m_radius,b2_polygonRadius);var radius=radiusA+radiusB;var xfA=input.transformA;var xfB=input.transformB;var r=input.translationB;var n=b2ShapeCast_s_n.Set(0.0,0.0);var lambda=0.0;var simplex=b2ShapeCast_s_simplex;simplex.m_count=0;var vertices=simplex.m_vertices;var indexA=proxyA.GetSupport(b2Rot.MulTRV(xfA.q,b2Vec2.NegV(r,b2Vec2.s_t1),b2Vec2.s_t0));var wA=b2Transform.MulXV(xfA,proxyA.GetVertex(indexA),b2ShapeCast_s_wA);var indexB=proxyB.GetSupport(b2Rot.MulTRV(xfB.q,r,b2Vec2.s_t0));var wB=b2Transform.MulXV(xfB,proxyB.GetVertex(indexB),b2ShapeCast_s_wB);var v=b2Vec2.SubVV(wA,wB,b2ShapeCast_s_v);var sigma=b2Max(b2_polygonRadius,radius-b2_polygonRadius);var tolerance=0.5*b2_linearSlop;var k_maxIters=20;var 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);var p=b2Vec2.SubVV(wA,wB,b2ShapeCast_s_p);v.Normalize();var vp=b2Vec2.DotVV(v,p);var 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;}var 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;}var pointA=b2ShapeCast_s_pointA;var 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={}));var b2ContactFeature=function(){function b2ContactFeature(){this._key=0;this._key_invalid=false;this._indexA=0;this._indexB=0;this._typeA=0;this._typeB=0;}_createClass(b2ContactFeature,[{key:"key",get:function get(){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:function set(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;}},{key:"indexA",get:function get(){return this._indexA;},set:function set(value){this._indexA=value;this._key_invalid=true;}},{key:"indexB",get:function get(){return this._indexB;},set:function set(value){this._indexB=value;this._key_invalid=true;}},{key:"typeA",get:function get(){return this._typeA;},set:function set(value){this._typeA=value;this._key_invalid=true;}},{key:"typeB",get:function get(){return this._typeB;},set:function set(value){this._typeB=value;this._key_invalid=true;}}]);return b2ContactFeature;}();var b2ContactID=function(){function b2ContactID(){this.cf=new b2ContactFeature();}var _proto20=b2ContactID.prototype;_proto20.Copy=function Copy(o){this.key=o.key;return this;};_proto20.Clone=function Clone(){return new b2ContactID().Copy(this);};_createClass(b2ContactID,[{key:"key",get:function get(){return this.cf.key;},set:function set(value){this.cf.key=value;}}]);return b2ContactID;}();var b2ManifoldPoint=function(){function b2ManifoldPoint(){this.localPoint=new b2Vec2();this.normalImpulse=0;this.tangentImpulse=0;this.id=new b2ContactID();}b2ManifoldPoint.MakeArray=function MakeArray(length){return b2MakeArray(length,function(i){return new b2ManifoldPoint();});};var _proto21=b2ManifoldPoint.prototype;_proto21.Reset=function Reset(){this.localPoint.SetZero();this.normalImpulse=0;this.tangentImpulse=0;this.id.key=0;};_proto21.Copy=function Copy(o){this.localPoint.Copy(o.localPoint);this.normalImpulse=o.normalImpulse;this.tangentImpulse=o.tangentImpulse;this.id.Copy(o.id);return this;};return b2ManifoldPoint;}();(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={}));var b2Manifold=function(){function b2Manifold(){this.points=b2ManifoldPoint.MakeArray(b2_maxManifoldPoints);this.localNormal=new b2Vec2();this.localPoint=new b2Vec2();this.type=exports.b2ManifoldType.e_unknown;this.pointCount=0;}var _proto22=b2Manifold.prototype;_proto22.Reset=function Reset(){for(var 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;};_proto22.Copy=function Copy(o){this.pointCount=o.pointCount;for(var 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;};_proto22.Clone=function Clone(){return new b2Manifold().Copy(this);};return b2Manifold;}();var b2WorldManifold=function(){function b2WorldManifold(){this.normal=new b2Vec2();this.points=b2Vec2.MakeArray(b2_maxManifoldPoints);this.separations=b2MakeNumberArray(b2_maxManifoldPoints);}var _proto23=b2WorldManifold.prototype;_proto23.Initialize=function Initialize(manifold,xfA,radiusA,xfB,radiusB){if(manifold.pointCount===0){return;}switch(manifold.type){case exports.b2ManifoldType.e_circles:{this.normal.Set(1,0);var pointA=b2Transform.MulXV(xfA,manifold.localPoint,b2WorldManifold.Initialize_s_pointA);var 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();}var cA=b2Vec2.AddVMulSV(pointA,radiusA,this.normal,b2WorldManifold.Initialize_s_cA);var 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);var planePoint=b2Transform.MulXV(xfA,manifold.localPoint,b2WorldManifold.Initialize_s_planePoint);for(var i=0;i<manifold.pointCount;++i){var clipPoint=b2Transform.MulXV(xfB,manifold.points[i].localPoint,b2WorldManifold.Initialize_s_clipPoint);var s=radiusA-b2Vec2.DotVV(b2Vec2.SubVV(clipPoint,planePoint,b2Vec2.s_t0),this.normal);var _cA=b2Vec2.AddVMulSV(clipPoint,s,this.normal,b2WorldManifold.Initialize_s_cA);var _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);var _planePoint=b2Transform.MulXV(xfB,manifold.localPoint,b2WorldManifold.Initialize_s_planePoint);for(var _i2=0;_i2<manifold.pointCount;++_i2){var _clipPoint=b2Transform.MulXV(xfA,manifold.points[_i2].localPoint,b2WorldManifold.Initialize_s_clipPoint);var _s=radiusB-b2Vec2.DotVV(b2Vec2.SubVV(_clipPoint,_planePoint,b2Vec2.s_t0),this.normal);var _cB2=b2Vec2.AddVMulSV(_clipPoint,_s,this.normal,b2WorldManifold.Initialize_s_cB);var _cA2=b2Vec2.SubVMulSV(_clipPoint,radiusA,this.normal,b2WorldManifold.Initialize_s_cA);b2Vec2.MidVV(_cA2,_cB2,this.points[_i2]);this.separations[_i2]=b2Vec2.DotVV(b2Vec2.SubVV(_cA2,_cB2,b2Vec2.s_t0),this.normal);}this.normal.SelfNeg();break;}}};return b2WorldManifold;}();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){var i;for(i=0;i<manifold1.pointCount;++i){var id=manifold1.points[i].id;var key=id.key;state1[i]=exports.b2PointState.b2_removeState;for(var 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){var _id=manifold2.points[i].id;var _key5=_id.key;state2[i]=exports.b2PointState.b2_addState;for(var _j=0,_jct=manifold1.pointCount;_j<_jct;++_j){if(manifold1.points[_j].id.key===_key5){state2[i]=exports.b2PointState.b2_persistState;break;}}}for(;i<b2_maxManifoldPoints;++i){state2[i]=exports.b2PointState.b2_nullState;}}var b2ClipVertex=function(){function b2ClipVertex(){this.v=new b2Vec2();this.id=new b2ContactID();}b2ClipVertex.MakeArray=function MakeArray(length){return b2MakeArray(length,function(i){return new b2ClipVertex();});};var _proto24=b2ClipVertex.prototype;_proto24.Copy=function Copy(other){this.v.Copy(other.v);this.id.Copy(other.id);return this;};return b2ClipVertex;}();var b2RayCastInput=function(){function b2RayCastInput(){this.p1=new b2Vec2();this.p2=new b2Vec2();this.maxFraction=1;}var _proto25=b2RayCastInput.prototype;_proto25.Copy=function Copy(o){this.p1.Copy(o.p1);this.p2.Copy(o.p2);this.maxFraction=o.maxFraction;return this;};return b2RayCastInput;}();var b2RayCastOutput=function(){function b2RayCastOutput(){this.normal=new b2Vec2();this.fraction=0;}var _proto26=b2RayCastOutput.prototype;_proto26.Copy=function Copy(o){this.normal.Copy(o.normal);this.fraction=o.fraction;return this;};return b2RayCastOutput;}();var b2AABB=function(){function b2AABB(){this.lowerBound=new b2Vec2();this.upperBound=new b2Vec2();this.m_cache_center=new b2Vec2();this.m_cache_extent=new b2Vec2();}var _proto27=b2AABB.prototype;_proto27.Copy=function Copy(o){this.lowerBound.Copy(o.lowerBound);this.upperBound.Copy(o.upperBound);return this;};_proto27.IsValid=function 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;};_proto27.GetCenter=function GetCenter(){return b2Vec2.MidVV(this.lowerBound,this.upperBound,this.m_cache_center);};_proto27.GetExtents=function GetExtents(){return b2Vec2.ExtVV(this.lowerBound,this.upperBound,this.m_cache_extent);};_proto27.GetPerimeter=function GetPerimeter(){var wx=this.upperBound.x-this.lowerBound.x;var wy=this.upperBound.y-this.lowerBound.y;return 2*(wx+wy);};_proto27.Combine1=function 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;};_proto27.Combine2=function 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;};b2AABB.Combine=function Combine(aabb1,aabb2,out){out.Combine2(aabb1,aabb2);return out;};_proto27.Contains=function 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;};_proto27.RayCast=function RayCast(output,input){var tmin=-b2_maxFloat;var tmax=b2_maxFloat;var p_x=input.p1.x;var p_y=input.p1.y;var d_x=input.p2.x-input.p1.x;var d_y=input.p2.y-input.p1.y;var absD_x=b2Abs(d_x);var absD_y=b2Abs(d_y);var normal=output.normal;if(absD_x<b2_epsilon){if(p_x<this.lowerBound.x||this.upperBound.x<p_x){return false;}}else {var inv_d=1/d_x;var t1=(this.lowerBound.x-p_x)*inv_d;var t2=(this.upperBound.x-p_x)*inv_d;var s=-1;if(t1>t2){var 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 {var _inv_d=1/d_y;var _t=(this.lowerBound.y-p_y)*_inv_d;var _t2=(this.upperBound.y-p_y)*_inv_d;var _s2=-1;if(_t>_t2){var _t3=_t;_t=_t2;_t2=_t3;_s2=1;}if(_t>tmin){normal.x=0;normal.y=_s2;tmin=_t;}tmax=b2Min(tmax,_t2);if(tmin>tmax){return false;}}if(tmin<0||input.maxFraction<tmin){return false;}output.fraction=tmin;return true;};_proto27.TestContain=function 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;};_proto27.TestOverlap=function 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;};return b2AABB;}();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){var numOut=0;var vIn0=vIn[0];var vIn1=vIn[1];var distance0=b2Vec2.DotVV(normal,vIn0.v)-offset;var 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){var interp=distance0/(distance0-distance1);var 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);var 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;}var b2TestOverlapShape_s_input=new b2DistanceInput();var b2TestOverlapShape_s_simplexCache=new b2SimplexCache();var b2TestOverlapShape_s_output=new b2DistanceOutput();function b2TestOverlapShape(shapeA,indexA,shapeB,indexB,xfA,xfB){var 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;var simplexCache=b2TestOverlapShape_s_simplexCache.Reset();simplexCache.count=0;var 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;}var b2TreeNode=function(){function b2TreeNode(id){if(id===void 0){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;}var _proto28=b2TreeNode.prototype;_proto28.Reset=function Reset(){this._userData=null;};_proto28.IsLeaf=function IsLeaf(){return this.child1===null;};_createClass(b2TreeNode,[{key:"userData",get:function get(){if(this._userData===null){throw new Error();}return this._userData;},set:function set(value){if(this._userData!==null){throw new Error();}this._userData=value;}}]);return b2TreeNode;}();var b2DynamicTree=function(){function b2DynamicTree(){this.m_root=null;this.m_freeList=null;this.m_path=0;this.m_insertionCount=0;this.m_stack=new b2GrowableStack(256);}var _proto29=b2DynamicTree.prototype;_proto29.Query=function Query(aabb,callback){var stack=this.m_stack.Reset();stack.Push(this.m_root);while(stack.GetCount()>0){var node=stack.Pop();if(node===null){continue;}if(node.aabb.TestOverlap(aabb)){if(node.IsLeaf()){var proceed=callback(node);if(!proceed){return;}}else {stack.Push(node.child1);stack.Push(node.child2);}}}};_proto29.QueryPoint=function QueryPoint(point,callback){var stack=this.m_stack.Reset();stack.Push(this.m_root);while(stack.GetCount()>0){var node=stack.Pop();if(node===null){continue;}if(node.aabb.TestContain(point)){if(node.IsLeaf()){var proceed=callback(node);if(!proceed){return;}}else {stack.Push(node.child1);stack.Push(node.child2);}}}};_proto29.RayCast=function RayCast(input,callback){var p1=input.p1;var p2=input.p2;var r=b2Vec2.SubVV(p2,p1,b2DynamicTree.s_r);r.Normalize();var v=b2Vec2.CrossOneV(r,b2DynamicTree.s_v);var abs_v=b2Vec2.AbsV(v,b2DynamicTree.s_abs_v);var maxFraction=input.maxFraction;var segmentAABB=b2DynamicTree.s_segmentAABB;var t_x=p1.x+maxFraction*(p2.x-p1.x);var 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);var stack=this.m_stack.Reset();stack.Push(this.m_root);while(stack.GetCount()>0){var node=stack.Pop();if(node===null){continue;}if(!b2TestOverlapAABB(node.aabb,segmentAABB)){continue;}var c=node.aabb.GetCenter();var h=node.aabb.GetExtents();var separation=b2Abs(b2Vec2.DotVV(v,b2Vec2.SubVV(p1,c,b2Vec2.s_t0)))-b2Vec2.DotVV(abs_v,h);if(separation>0){continue;}if(node.IsLeaf()){var subInput=b2DynamicTree.s_subInput;subInput.p1.Copy(input.p1);subInput.p2.Copy(input.p2);subInput.maxFraction=maxFraction;var 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);}}};_proto29.AllocateNode=function AllocateNode(){if(this.m_freeList!==null){var 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++);};_proto29.FreeNode=function FreeNode(node){node.parent=this.m_freeList;node.child1=null;node.child2=null;node.height=-1;node.Reset();this.m_freeList=node;};_proto29.CreateProxy=function CreateProxy(aabb,userData){var node=this.AllocateNode();var r_x=b2_aabbExtension;var 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;};_proto29.DestroyProxy=function DestroyProxy(node){this.RemoveLeaf(node);this.FreeNode(node);};_proto29.MoveProxy=function MoveProxy(node,aabb,displacement){if(node.aabb.Contains(aabb)){return false;}this.RemoveLeaf(node);var r_x=b2_aabbExtension;var 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;var d_x=b2_aabbMultiplier*displacement.x;var 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;};_proto29.InsertLeaf=function InsertLeaf(leaf){++this.m_insertionCount;if(this.m_root===null){this.m_root=leaf;this.m_root.parent=null;return;}var leafAABB=leaf.aabb;var sibling=this.m_root;while(!sibling.IsLeaf()){var child1=verify(sibling.child1);var child2=verify(sibling.child2);var area=sibling.aabb.GetPerimeter();var combinedAABB=b2DynamicTree.s_combinedAABB;combinedAABB.Combine2(sibling.aabb,leafAABB);var combinedArea=combinedAABB.GetPerimeter();var cost=2*combinedArea;var inheritanceCost=2*(combinedArea-area);var cost1=void 0;var aabb=b2DynamicTree.s_aabb;var oldArea=void 0;var newArea=void 0;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;}var cost2=void 0;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;}}var oldParent=sibling.parent;var 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;}var node=leaf.parent;while(node!==null){node=this.Balance(node);var _child=verify(node.child1);var _child2=verify(node.child2);node.height=1+b2Max(_child.height,_child2.height);node.aabb.Combine2(_child.aabb,_child2.aabb);node=node.parent;}};_proto29.RemoveLeaf=function RemoveLeaf(leaf){if(leaf===this.m_root){this.m_root=null;return;}var parent=verify(leaf.parent);var grandParent=parent&&parent.parent;var 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);var index=grandParent;while(index!==null){index=this.Balance(index);var child1=verify(index.child1);var 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);}};_proto29.Balance=function Balance(A){if(A.IsLeaf()||A.height<2){return A;}var B=verify(A.child1);var C=verify(A.child2);var balance=C.height-B.height;if(balance>1){var F=verify(C.child1);var 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){var D=verify(B.child1);var 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;};_proto29.GetHeight=function GetHeight(){if(this.m_root===null){return 0;}return this.m_root.height;};b2DynamicTree.GetAreaNode=function GetAreaNode(node){if(node===null){return 0;}if(node.IsLeaf()){return 0;}var area=node.aabb.GetPerimeter();area+=b2DynamicTree.GetAreaNode(node.child1);area+=b2DynamicTree.GetAreaNode(node.child2);return area;};_proto29.GetAreaRatio=function GetAreaRatio(){if(this.m_root===null){return 0;}var root=this.m_root;var rootArea=root.aabb.GetPerimeter();var totalArea=b2DynamicTree.GetAreaNode(this.m_root);return totalArea/rootArea;};b2DynamicTree.ComputeHeightNode=function ComputeHeightNode(node){if(node===null){return 0;}if(node.IsLeaf()){return 0;}var height1=b2DynamicTree.ComputeHeightNode(node.child1);var height2=b2DynamicTree.ComputeHeightNode(node.child2);return 1+b2Max(height1,height2);};_proto29.ComputeHeight=function ComputeHeight(){var height=b2DynamicTree.ComputeHeightNode(this.m_root);return height;};_proto29.ValidateStructure=function ValidateStructure(node){if(node===null){return;}if(node===this.m_root);if(node.IsLeaf()){return;}var child1=verify(node.child1);var child2=verify(node.child2);this.ValidateStructure(child1);this.ValidateStructure(child2);};_proto29.ValidateMetrics=function ValidateMetrics(node){if(node===null){return;}if(node.IsLeaf()){return;}var child1=verify(node.child1);var child2=verify(node.child2);var aabb=b2DynamicTree.s_aabb;aabb.Combine2(child1.aabb,child2.aabb);this.ValidateMetrics(child1);this.ValidateMetrics(child2);};_proto29.Validate=function Validate(){};b2DynamicTree.GetMaxBalanceNode=function GetMaxBalanceNode(node,maxBalance){if(node===null){return maxBalance;}if(node.height<=1){return maxBalance;}var child1=verify(node.child1);var child2=verify(node.child2);var balance=b2Abs(child2.height-child1.height);return b2Max(maxBalance,balance);};_proto29.GetMaxBalance=function GetMaxBalance(){var maxBalance=b2DynamicTree.GetMaxBalanceNode(this.m_root,0);return maxBalance;};_proto29.RebuildBottomUp=function RebuildBottomUp(){this.Validate();};b2DynamicTree.ShiftOriginNode=function ShiftOriginNode(node,newOrigin){if(node===null){return;}if(node.height<=1){return;}var child1=node.child1;var child2=node.child2;b2DynamicTree.ShiftOriginNode(child1,newOrigin);b2DynamicTree.ShiftOriginNode(child2,newOrigin);node.aabb.lowerBound.SelfSub(newOrigin);node.aabb.upperBound.SelfSub(newOrigin);};_proto29.ShiftOrigin=function ShiftOrigin(newOrigin){b2DynamicTree.ShiftOriginNode(this.m_root,newOrigin);};return b2DynamicTree;}();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){var tmp=array[a];array[a]=array[b];array[b]=tmp;}function default_compare(a,b){return a<b;}function std_sort(array,first,len,cmp){if(first===void 0){first=0;}if(len===void 0){len=array.length-first;}if(cmp===void 0){cmp=default_compare;}var left=first;var stack=[];var pos=0;for(;;){for(;left+1<len;len++){var pivot=array[left+Math.floor(Math.random()*(len-left))];stack[pos++]=len;for(var 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;}var b2Pair=function b2Pair(proxyA,proxyB){this.proxyA=proxyA;this.proxyB=proxyB;};var b2BroadPhase=function(){function b2BroadPhase(){this.m_tree=new b2DynamicTree();this.m_proxyCount=0;this.m_moveCount=0;this.m_moveBuffer=[];this.m_pairCount=0;this.m_pairBuffer=[];}var _proto30=b2BroadPhase.prototype;_proto30.CreateProxy=function CreateProxy(aabb,userData){var proxy=this.m_tree.CreateProxy(aabb,userData);++this.m_proxyCount;this.BufferMove(proxy);return proxy;};_proto30.DestroyProxy=function DestroyProxy(proxy){this.UnBufferMove(proxy);--this.m_proxyCount;this.m_tree.DestroyProxy(proxy);};_proto30.MoveProxy=function MoveProxy(proxy,aabb,displacement){var buffer=this.m_tree.MoveProxy(proxy,aabb,displacement);if(buffer){this.BufferMove(proxy);}};_proto30.TouchProxy=function TouchProxy(proxy){this.BufferMove(proxy);};_proto30.GetProxyCount=function GetProxyCount(){return this.m_proxyCount;};_proto30.UpdatePairs=function UpdatePairs(callback){var _this=this;this.m_pairCount=0;var _loop=function _loop(_i3){var queryProxy=_this.m_moveBuffer[_i3];if(queryProxy===null){return "continue";}var fatAABB=queryProxy.aabb;_this.m_tree.Query(fatAABB,function(proxy){if(proxy.m_id===queryProxy.m_id){return true;}var proxyA;var 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 {var _pair=_this.m_pairBuffer[_this.m_pairCount];_pair.proxyA=proxyA;_pair.proxyB=proxyB;}++_this.m_pairCount;return true;});};for(var _i3=0;_i3<this.m_moveCount;++_i3){var _ret=_loop(_i3);if(_ret==="continue")continue;}this.m_moveCount=0;std_sort(this.m_pairBuffer,0,this.m_pairCount,b2PairLessThan);var i=0;while(i<this.m_pairCount){var primaryPair=this.m_pairBuffer[i];var userDataA=primaryPair.proxyA.userData;var userDataB=primaryPair.proxyB.userData;callback(userDataA,userDataB);++i;while(i<this.m_pairCount){var pair=this.m_pairBuffer[i];if(pair.proxyA.m_id!==primaryPair.proxyA.m_id||pair.proxyB.m_id!==primaryPair.proxyB.m_id){break;}++i;}}};_proto30.Query=function Query(aabb,callback){this.m_tree.Query(aabb,callback);};_proto30.QueryPoint=function QueryPoint(point,callback){this.m_tree.QueryPoint(point,callback);};_proto30.RayCast=function RayCast(input,callback){this.m_tree.RayCast(input,callback);};_proto30.GetTreeHeight=function GetTreeHeight(){return this.m_tree.GetHeight();};_proto30.GetTreeBalance=function GetTreeBalance(){return this.m_tree.GetMaxBalance();};_proto30.GetTreeQuality=function GetTreeQuality(){return this.m_tree.GetAreaRatio();};_proto30.ShiftOrigin=function ShiftOrigin(newOrigin){this.m_tree.ShiftOrigin(newOrigin);};_proto30.BufferMove=function BufferMove(proxy){this.m_moveBuffer[this.m_moveCount]=proxy;++this.m_moveCount;};_proto30.UnBufferMove=function UnBufferMove(proxy){var i=this.m_moveBuffer.indexOf(proxy);this.m_moveBuffer[i]=null;};return b2BroadPhase;}();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;}var b2TimeOfImpact_s_xfA=new b2Transform();var b2TimeOfImpact_s_xfB=new b2Transform();var b2TimeOfImpact_s_pointA=new b2Vec2();var b2TimeOfImpact_s_pointB=new b2Vec2();var b2TimeOfImpact_s_normal=new b2Vec2();var b2TimeOfImpact_s_axisA=new b2Vec2();var b2TimeOfImpact_s_axisB=new b2Vec2();var b2TOIInput=function b2TOIInput(){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={}));var b2TOIOutput=function b2TOIOutput(){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={}));var b2SeparationFunction=function(){function b2SeparationFunction(){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();}var _proto31=b2SeparationFunction.prototype;_proto31.Initialize=function Initialize(cache,proxyA,sweepA,proxyB,sweepB,t1){this.m_proxyA=proxyA;this.m_proxyB=proxyB;var count=cache.count;this.m_sweepA.Copy(sweepA);this.m_sweepB.Copy(sweepB);var xfA=b2TimeOfImpact_s_xfA;var 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;var localPointA=this.m_proxyA.GetVertex(cache.indexA[0]);var localPointB=this.m_proxyB.GetVertex(cache.indexB[0]);var pointA=b2Transform.MulXV(xfA,localPointA,b2TimeOfImpact_s_pointA);var pointB=b2Transform.MulXV(xfB,localPointB,b2TimeOfImpact_s_pointB);b2Vec2.SubVV(pointB,pointA,this.m_axis);var 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;var localPointB1=this.m_proxyB.GetVertex(cache.indexB[0]);var localPointB2=this.m_proxyB.GetVertex(cache.indexB[1]);b2Vec2.CrossVOne(b2Vec2.SubVV(localPointB2,localPointB1,b2Vec2.s_t0),this.m_axis).SelfNormalize();var normal=b2Rot.MulRV(xfB.q,this.m_axis,b2TimeOfImpact_s_normal);b2Vec2.MidVV(localPointB1,localPointB2,this.m_localPoint);var _pointB=b2Transform.MulXV(xfB,this.m_localPoint,b2TimeOfImpact_s_pointB);var _localPointA=this.m_proxyA.GetVertex(cache.indexA[0]);var _pointA=b2Transform.MulXV(xfA,_localPointA,b2TimeOfImpact_s_pointA);var _s3=b2Vec2.DotVV(b2Vec2.SubVV(_pointA,_pointB,b2Vec2.s_t0),normal);if(_s3<0){this.m_axis.SelfNeg();_s3=-_s3;}return _s3;}else {this.m_type=exports.b2SeparationFunctionType.e_faceA;var localPointA1=this.m_proxyA.GetVertex(cache.indexA[0]);var localPointA2=this.m_proxyA.GetVertex(cache.indexA[1]);b2Vec2.CrossVOne(b2Vec2.SubVV(localPointA2,localPointA1,b2Vec2.s_t0),this.m_axis).SelfNormalize();var _normal=b2Rot.MulRV(xfA.q,this.m_axis,b2TimeOfImpact_s_normal);b2Vec2.MidVV(localPointA1,localPointA2,this.m_localPoint);var _pointA2=b2Transform.MulXV(xfA,this.m_localPoint,b2TimeOfImpact_s_pointA);var _localPointB=this.m_proxyB.GetVertex(cache.indexB[0]);var _pointB2=b2Transform.MulXV(xfB,_localPointB,b2TimeOfImpact_s_pointB);var _s4=b2Vec2.DotVV(b2Vec2.SubVV(_pointB2,_pointA2,b2Vec2.s_t0),_normal);if(_s4<0){this.m_axis.SelfNeg();_s4=-_s4;}return _s4;}};_proto31.FindMinSeparation=function FindMinSeparation(indexA,indexB,t){var xfA=b2TimeOfImpact_s_xfA;var 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:{var axisA=b2Rot.MulTRV(xfA.q,this.m_axis,b2TimeOfImpact_s_axisA);var 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);var localPointA=this.m_proxyA.GetVertex(indexA[0]);var localPointB=this.m_proxyB.GetVertex(indexB[0]);var pointA=b2Transform.MulXV(xfA,localPointA,b2TimeOfImpact_s_pointA);var pointB=b2Transform.MulXV(xfB,localPointB,b2TimeOfImpact_s_pointB);var separation=b2Vec2.DotVV(b2Vec2.SubVV(pointB,pointA,b2Vec2.s_t0),this.m_axis);return separation;}case exports.b2SeparationFunctionType.e_faceA:{var normal=b2Rot.MulRV(xfA.q,this.m_axis,b2TimeOfImpact_s_normal);var _pointA3=b2Transform.MulXV(xfA,this.m_localPoint,b2TimeOfImpact_s_pointA);var _axisB=b2Rot.MulTRV(xfB.q,b2Vec2.NegV(normal,b2Vec2.s_t0),b2TimeOfImpact_s_axisB);indexA[0]=-1;indexB[0]=this.m_proxyB.GetSupport(_axisB);var _localPointB2=this.m_proxyB.GetVertex(indexB[0]);var _pointB3=b2Transform.MulXV(xfB,_localPointB2,b2TimeOfImpact_s_pointB);var _separation=b2Vec2.DotVV(b2Vec2.SubVV(_pointB3,_pointA3,b2Vec2.s_t0),normal);return _separation;}case exports.b2SeparationFunctionType.e_faceB:{var _normal2=b2Rot.MulRV(xfB.q,this.m_axis,b2TimeOfImpact_s_normal);var _pointB4=b2Transform.MulXV(xfB,this.m_localPoint,b2TimeOfImpact_s_pointB);var _axisA=b2Rot.MulTRV(xfA.q,b2Vec2.NegV(_normal2,b2Vec2.s_t0),b2TimeOfImpact_s_axisA);indexB[0]=-1;indexA[0]=this.m_proxyA.GetSupport(_axisA);var _localPointA2=this.m_proxyA.GetVertex(indexA[0]);var _pointA4=b2Transform.MulXV(xfA,_localPointA2,b2TimeOfImpact_s_pointA);var _separation2=b2Vec2.DotVV(b2Vec2.SubVV(_pointA4,_pointB4,b2Vec2.s_t0),_normal2);return _separation2;}default:indexA[0]=-1;indexB[0]=-1;return 0;}};_proto31.Evaluate=function Evaluate(indexA,indexB,t){var xfA=b2TimeOfImpact_s_xfA;var 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:{var localPointA=this.m_proxyA.GetVertex(indexA);var localPointB=this.m_proxyB.GetVertex(indexB);var pointA=b2Transform.MulXV(xfA,localPointA,b2TimeOfImpact_s_pointA);var pointB=b2Transform.MulXV(xfB,localPointB,b2TimeOfImpact_s_pointB);var separation=b2Vec2.DotVV(b2Vec2.SubVV(pointB,pointA,b2Vec2.s_t0),this.m_axis);return separation;}case exports.b2SeparationFunctionType.e_faceA:{var normal=b2Rot.MulRV(xfA.q,this.m_axis,b2TimeOfImpact_s_normal);var _pointA5=b2Transform.MulXV(xfA,this.m_localPoint,b2TimeOfImpact_s_pointA);var _localPointB3=this.m_proxyB.GetVertex(indexB);var _pointB5=b2Transform.MulXV(xfB,_localPointB3,b2TimeOfImpact_s_pointB);var _separation3=b2Vec2.DotVV(b2Vec2.SubVV(_pointB5,_pointA5,b2Vec2.s_t0),normal);return _separation3;}case exports.b2SeparationFunctionType.e_faceB:{var _normal3=b2Rot.MulRV(xfB.q,this.m_axis,b2TimeOfImpact_s_normal);var _pointB6=b2Transform.MulXV(xfB,this.m_localPoint,b2TimeOfImpact_s_pointB);var _localPointA3=this.m_proxyA.GetVertex(indexA);var _pointA6=b2Transform.MulXV(xfA,_localPointA3,b2TimeOfImpact_s_pointA);var _separation4=b2Vec2.DotVV(b2Vec2.SubVV(_pointA6,_pointB6,b2Vec2.s_t0),_normal3);return _separation4;}default:return 0;}};return b2SeparationFunction;}();var b2TimeOfImpact_s_timer=new b2Timer();var b2TimeOfImpact_s_cache=new b2SimplexCache();var b2TimeOfImpact_s_distanceInput=new b2DistanceInput();var b2TimeOfImpact_s_distanceOutput=new b2DistanceOutput();var b2TimeOfImpact_s_fcn=new b2SeparationFunction();var b2TimeOfImpact_s_indexA=[0];var b2TimeOfImpact_s_indexB=[0];var b2TimeOfImpact_s_sweepA=new b2Sweep();var b2TimeOfImpact_s_sweepB=new b2Sweep();function b2TimeOfImpact(output,input){var timer=b2TimeOfImpact_s_timer.Reset();++exports.b2_toiCalls;output.state=exports.b2TOIOutputState.e_unknown;output.t=input.tMax;var proxyA=input.proxyA;var proxyB=input.proxyB;var maxVertices=b2Max(b2_maxPolygonVertices,b2Max(proxyA.m_count,proxyB.m_count));var sweepA=b2TimeOfImpact_s_sweepA.Copy(input.sweepA);var sweepB=b2TimeOfImpact_s_sweepB.Copy(input.sweepB);sweepA.Normalize();sweepB.Normalize();var tMax=input.tMax;var totalRadius=proxyA.m_radius+proxyB.m_radius;var target=b2Max(b2_linearSlop,totalRadius-3*b2_linearSlop);var tolerance=0.25*b2_linearSlop;var t1=0;var k_maxIterations=20;var iter=0;var cache=b2TimeOfImpact_s_cache;cache.count=0;var distanceInput=b2TimeOfImpact_s_distanceInput;distanceInput.proxyA.Copy(input.proxyA);distanceInput.proxyB.Copy(input.proxyB);distanceInput.useRadii=false;for(;;){var xfA=b2TimeOfImpact_s_xfA;var xfB=b2TimeOfImpact_s_xfB;sweepA.GetTransform(xfA,t1);sweepB.GetTransform(xfB,t1);distanceInput.transformA.Copy(xfA);distanceInput.transformB.Copy(xfB);var 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;}var fcn=b2TimeOfImpact_s_fcn;fcn.Initialize(cache,proxyA,sweepA,proxyB,sweepB,t1);var done=false;var t2=tMax;var pushBackIter=0;for(;;){var indexA=b2TimeOfImpact_s_indexA;var indexB=b2TimeOfImpact_s_indexB;var 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;}var 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;}var rootIterCount=0;var a1=t1;var a2=t2;for(;;){var t=0;if(rootIterCount&1){t=a1+(target-s1)*(a2-a1)/(s2-s1);}else {t=0.5*(a1+a2);}++rootIterCount;++exports.b2_toiRootIters;var 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);var time=timer.GetMilliseconds();exports.b2_toiMaxTime=b2Max(exports.b2_toiMaxTime,time);exports.b2_toiTime+=time;}var b2CollideCircles_s_pA=new b2Vec2();var b2CollideCircles_s_pB=new b2Vec2();function b2CollideCircles(manifold,circleA,xfA,circleB,xfB){manifold.pointCount=0;var pA=b2Transform.MulXV(xfA,circleA.m_p,b2CollideCircles_s_pA);var pB=b2Transform.MulXV(xfB,circleB.m_p,b2CollideCircles_s_pB);var distSqr=b2Vec2.DistanceSquaredVV(pA,pB);var 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;}var b2CollidePolygonAndCircle_s_c=new b2Vec2();var b2CollidePolygonAndCircle_s_cLocal=new b2Vec2();var b2CollidePolygonAndCircle_s_faceCenter=new b2Vec2();function b2CollidePolygonAndCircle(manifold,polygonA,xfA,circleB,xfB){manifold.pointCount=0;var c=b2Transform.MulXV(xfB,circleB.m_p,b2CollidePolygonAndCircle_s_c);var cLocal=b2Transform.MulTXV(xfA,c,b2CollidePolygonAndCircle_s_cLocal);var normalIndex=0;var separation=-b2_maxFloat;var radius=polygonA.m_radius+circleB.m_radius;var vertexCount=polygonA.m_count;var vertices=polygonA.m_vertices;var normals=polygonA.m_normals;for(var i=0;i<vertexCount;++i){var s=b2Vec2.DotVV(normals[i],b2Vec2.SubVV(cLocal,vertices[i],b2Vec2.s_t0));if(s>radius){return;}if(s>separation){separation=s;normalIndex=i;}}var vertIndex1=normalIndex;var vertIndex2=(vertIndex1+1)%vertexCount;var v1=vertices[vertIndex1];var 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;}var u1=b2Vec2.DotVV(b2Vec2.SubVV(cLocal,v1,b2Vec2.s_t0),b2Vec2.SubVV(v2,v1,b2Vec2.s_t1));var 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 {var faceCenter=b2Vec2.MidVV(v1,v2,b2CollidePolygonAndCircle_s_faceCenter);var _separation5=b2Vec2.DotVV(b2Vec2.SubVV(cLocal,faceCenter,b2Vec2.s_t1),normals[vertIndex1]);if(_separation5>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;}}var b2EdgeSeparation_s_normal1World=new b2Vec2();var b2EdgeSeparation_s_normal1=new b2Vec2();var b2EdgeSeparation_s_v1=new b2Vec2();var b2EdgeSeparation_s_v2=new b2Vec2();function b2EdgeSeparation(poly1,xf1,edge1,poly2,xf2){var vertices1=poly1.m_vertices;var normals1=poly1.m_normals;var count2=poly2.m_count;var vertices2=poly2.m_vertices;var normal1World=b2Rot.MulRV(xf1.q,normals1[edge1],b2EdgeSeparation_s_normal1World);var normal1=b2Rot.MulTRV(xf2.q,normal1World,b2EdgeSeparation_s_normal1);var index=0;var minDot=b2_maxFloat;for(var i=0;i<count2;++i){var dot=b2Vec2.DotVV(vertices2[i],normal1);if(dot<minDot){minDot=dot;index=i;}}var v1=b2Transform.MulXV(xf1,vertices1[edge1],b2EdgeSeparation_s_v1);var v2=b2Transform.MulXV(xf2,vertices2[index],b2EdgeSeparation_s_v2);var separation=b2Vec2.DotVV(b2Vec2.SubVV(v2,v1,b2Vec2.s_t0),normal1World);return separation;}var b2FindMaxSeparation_s_d=new b2Vec2();var b2FindMaxSeparation_s_dLocal1=new b2Vec2();function b2FindMaxSeparation(edgeIndex,poly1,xf1,poly2,xf2){var count1=poly1.m_count;var normals1=poly1.m_normals;var d=b2Vec2.SubVV(b2Transform.MulXV(xf2,poly2.m_centroid,b2Vec2.s_t0),b2Transform.MulXV(xf1,poly1.m_centroid,b2Vec2.s_t1),b2FindMaxSeparation_s_d);var dLocal1=b2Rot.MulTRV(xf1.q,d,b2FindMaxSeparation_s_dLocal1);var edge=0;var maxDot=-b2_maxFloat;for(var i=0;i<count1;++i){var dot=b2Vec2.DotVV(normals1[i],dLocal1);if(dot>maxDot){maxDot=dot;edge=i;}}var s=b2EdgeSeparation(poly1,xf1,edge,poly2,xf2);var prevEdge=(edge+count1-1)%count1;var sPrev=b2EdgeSeparation(poly1,xf1,prevEdge,poly2,xf2);var nextEdge=(edge+1)%count1;var sNext=b2EdgeSeparation(poly1,xf1,nextEdge,poly2,xf2);var bestEdge=0;var bestSeparation=0;var 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;}var b2FindIncidentEdge_s_normal1=new b2Vec2();function b2FindIncidentEdge(c,poly1,xf1,edge1,poly2,xf2){var normals1=poly1.m_normals;var count2=poly2.m_count;var vertices2=poly2.m_vertices;var normals2=poly2.m_normals;var normal1=b2Rot.MulTRV(xf2.q,b2Rot.MulRV(xf1.q,normals1[edge1],b2Vec2.s_t0),b2FindIncidentEdge_s_normal1);var index=0;var minDot=b2_maxFloat;for(var i=0;i<count2;++i){var dot=b2Vec2.DotVV(normal1,normals2[i]);if(dot<minDot){minDot=dot;index=i;}}var i1=index;var i2=(i1+1)%count2;var c0=c[0];b2Transform.MulXV(xf2,vertices2[i1],c0.v);var cf0=c0.id.cf;cf0.indexA=edge1;cf0.indexB=i1;cf0.typeA=exports.b2ContactFeatureType.e_face;cf0.typeB=exports.b2ContactFeatureType.e_vertex;var c1=c[1];b2Transform.MulXV(xf2,vertices2[i2],c1.v);var cf1=c1.id.cf;cf1.indexA=edge1;cf1.indexB=i2;cf1.typeA=exports.b2ContactFeatureType.e_face;cf1.typeB=exports.b2ContactFeatureType.e_vertex;}var b2CollidePolygons_s_incidentEdge=b2ClipVertex.MakeArray(2);var b2CollidePolygons_s_clipPoints1=b2ClipVertex.MakeArray(2);var b2CollidePolygons_s_clipPoints2=b2ClipVertex.MakeArray(2);var b2CollidePolygons_s_edgeA=[0];var b2CollidePolygons_s_edgeB=[0];var b2CollidePolygons_s_localTangent=new b2Vec2();var b2CollidePolygons_s_localNormal=new b2Vec2();var b2CollidePolygons_s_planePoint=new b2Vec2();var b2CollidePolygons_s_normal=new b2Vec2();var b2CollidePolygons_s_tangent=new b2Vec2();var b2CollidePolygons_s_ntangent=new b2Vec2();var b2CollidePolygons_s_v11=new b2Vec2();var b2CollidePolygons_s_v12=new b2Vec2();function b2CollidePolygons(manifold,polyA,xfA,polyB,xfB){manifold.pointCount=0;var totalRadius=polyA.m_radius+polyB.m_radius;var edgeA=b2CollidePolygons_s_edgeA;edgeA[0]=0;var separationA=b2FindMaxSeparation(edgeA,polyA,xfA,polyB,xfB);if(separationA>totalRadius){return;}var edgeB=b2CollidePolygons_s_edgeB;edgeB[0]=0;var separationB=b2FindMaxSeparation(edgeB,polyB,xfB,polyA,xfA);if(separationB>totalRadius){return;}var poly1;var poly2;var xf1,xf2;var edge1=0;var flip=0;var k_relativeTol=0.98;var 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;}var incidentEdge=b2CollidePolygons_s_incidentEdge;b2FindIncidentEdge(incidentEdge,poly1,xf1,edge1,poly2,xf2);var count1=poly1.m_count;var vertices1=poly1.m_vertices;var iv1=edge1;var iv2=(edge1+1)%count1;var local_v11=vertices1[iv1];var local_v12=vertices1[iv2];var localTangent=b2Vec2.SubVV(local_v12,local_v11,b2CollidePolygons_s_localTangent);localTangent.Normalize();var localNormal=b2Vec2.CrossVOne(localTangent,b2CollidePolygons_s_localNormal);var planePoint=b2Vec2.MidVV(local_v11,local_v12,b2CollidePolygons_s_planePoint);var tangent=b2Rot.MulRV(xf1.q,localTangent,b2CollidePolygons_s_tangent);var normal=b2Vec2.CrossVOne(tangent,b2CollidePolygons_s_normal);var v11=b2Transform.MulXV(xf1,local_v11,b2CollidePolygons_s_v11);var v12=b2Transform.MulXV(xf1,local_v12,b2CollidePolygons_s_v12);var frontOffset=b2Vec2.DotVV(normal,v11);var sideOffset1=-b2Vec2.DotVV(tangent,v11)+totalRadius;var sideOffset2=b2Vec2.DotVV(tangent,v12)+totalRadius;var clipPoints1=b2CollidePolygons_s_clipPoints1;var clipPoints2=b2CollidePolygons_s_clipPoints2;var np;var 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);var pointCount=0;for(var i=0;i<b2_maxManifoldPoints;++i){var cv=clipPoints2[i];var separation=b2Vec2.DotVV(normal,cv.v)-frontOffset;if(separation<=totalRadius){var cp=manifold.points[pointCount];b2Transform.MulTXV(xf2,cv.v,cp.localPoint);cp.id.Copy(cv.id);if(flip){var 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;}var b2CollideEdgeAndCircle_s_Q=new b2Vec2();var b2CollideEdgeAndCircle_s_e=new b2Vec2();var b2CollideEdgeAndCircle_s_d=new b2Vec2();var b2CollideEdgeAndCircle_s_e1=new b2Vec2();var b2CollideEdgeAndCircle_s_e2=new b2Vec2();var b2CollideEdgeAndCircle_s_P=new b2Vec2();var b2CollideEdgeAndCircle_s_n=new b2Vec2();var b2CollideEdgeAndCircle_s_id=new b2ContactID();function b2CollideEdgeAndCircle(manifold,edgeA,xfA,circleB,xfB){manifold.pointCount=0;var Q=b2Transform.MulTXV(xfA,b2Transform.MulXV(xfB,circleB.m_p,b2Vec2.s_t0),b2CollideEdgeAndCircle_s_Q);var A=edgeA.m_vertex1;var B=edgeA.m_vertex2;var e=b2Vec2.SubVV(B,A,b2CollideEdgeAndCircle_s_e);var u=b2Vec2.DotVV(e,b2Vec2.SubVV(B,Q,b2Vec2.s_t0));var v=b2Vec2.DotVV(e,b2Vec2.SubVV(Q,A,b2Vec2.s_t0));var radius=edgeA.m_radius+circleB.m_radius;var id=b2CollideEdgeAndCircle_s_id;id.cf.indexB=0;id.cf.typeB=exports.b2ContactFeatureType.e_vertex;if(v<=0){var _P=A;var _d=b2Vec2.SubVV(Q,_P,b2CollideEdgeAndCircle_s_d);var _dd=b2Vec2.DotVV(_d,_d);if(_dd>radius*radius){return;}if(edgeA.m_hasVertex0){var A1=edgeA.m_vertex0;var B1=A;var e1=b2Vec2.SubVV(B1,A1,b2CollideEdgeAndCircle_s_e1);var 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){var _P2=B;var _d2=b2Vec2.SubVV(Q,_P2,b2CollideEdgeAndCircle_s_d);var _dd2=b2Vec2.DotVV(_d2,_d2);if(_dd2>radius*radius){return;}if(edgeA.m_hasVertex3){var B2=edgeA.m_vertex3;var A2=B;var e2=b2Vec2.SubVV(B2,A2,b2CollideEdgeAndCircle_s_e2);var 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(_P2);manifold.points[0].id.Copy(id);manifold.points[0].localPoint.Copy(circleB.m_p);return;}var den=b2Vec2.DotVV(e,e);var P=b2CollideEdgeAndCircle_s_P;P.x=1/den*(u*A.x+v*B.x);P.y=1/den*(u*A.y+v*B.y);var d=b2Vec2.SubVV(Q,P,b2CollideEdgeAndCircle_s_d);var dd=b2Vec2.DotVV(d,d);if(dd>radius*radius){return;}var 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={}));var b2EPAxis=function b2EPAxis(){this.type=b2EPAxisType.e_unknown;this.index=0;this.separation=0;};var b2TempPolygon=function b2TempPolygon(){this.vertices=[];this.normals=[];this.count=0;};var b2ReferenceFace=function b2ReferenceFace(){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={}));var b2EPCollider=function(){function b2EPCollider(){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;}var _proto32=b2EPCollider.prototype;_proto32.Collide=function 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);var hasVertex0=edgeA.m_hasVertex0;var hasVertex3=edgeA.m_hasVertex3;var edge1=b2Vec2.SubVV(this.m_v2,this.m_v1,b2EPCollider.s_edge1);edge1.Normalize();this.m_normal1.Set(edge1.y,-edge1.x);var offset1=b2Vec2.DotVV(this.m_normal1,b2Vec2.SubVV(this.m_centroidB,this.m_v1,b2Vec2.s_t0));var offset0=0;var offset2=0;var convex1=false;var convex2=false;if(hasVertex0){var 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){var 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(var 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;var edgeAxis=this.ComputeEdgeSeparation(b2EPCollider.s_edgeAxis);if(edgeAxis.type===b2EPAxisType.e_unknown){return;}if(edgeAxis.separation>this.m_radius){return;}var polygonAxis=this.ComputePolygonSeparation(b2EPCollider.s_polygonAxis);if(polygonAxis.type!==b2EPAxisType.e_unknown&&polygonAxis.separation>this.m_radius){return;}var k_relativeTol=0.98;var k_absoluteTol=0.001;var primaryAxis;if(polygonAxis.type===b2EPAxisType.e_unknown){primaryAxis=edgeAxis;}else if(polygonAxis.separation>k_relativeTol*edgeAxis.separation+k_absoluteTol){primaryAxis=polygonAxis;}else {primaryAxis=edgeAxis;}var ie=b2EPCollider.s_ie;var rf=b2EPCollider.s_rf;if(primaryAxis.type===b2EPAxisType.e_edgeA){manifold.type=exports.b2ManifoldType.e_faceA;var bestIndex=0;var bestValue=b2Vec2.DotVV(this.m_normal,this.m_polygonB.normals[0]);for(var _i4=1;_i4<this.m_polygonB.count;++_i4){var value=b2Vec2.DotVV(this.m_normal,this.m_polygonB.normals[_i4]);if(value<bestValue){bestValue=value;bestIndex=_i4;}}var i1=bestIndex;var i2=(i1+1)%this.m_polygonB.count;var 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;var 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;var _ie=ie[0];_ie.v.Copy(this.m_v1);_ie.id.cf.indexA=0;_ie.id.cf.indexB=primaryAxis.index;_ie.id.cf.typeA=exports.b2ContactFeatureType.e_vertex;_ie.id.cf.typeB=exports.b2ContactFeatureType.e_face;var _ie2=ie[1];_ie2.v.Copy(this.m_v2);_ie2.id.cf.indexA=0;_ie2.id.cf.indexB=primaryAxis.index;_ie2.id.cf.typeA=exports.b2ContactFeatureType.e_vertex;_ie2.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);var clipPoints1=b2EPCollider.s_clipPoints1;var clipPoints2=b2EPCollider.s_clipPoints2;var 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]);}var pointCount=0;for(var _i5=0;_i5<b2_maxManifoldPoints;++_i5){var separation=void 0;separation=b2Vec2.DotVV(rf.normal,b2Vec2.SubVV(clipPoints2[_i5].v,rf.v1,b2Vec2.s_t0));if(separation<=this.m_radius){var cp=manifold.points[pointCount];if(primaryAxis.type===b2EPAxisType.e_edgeA){b2Transform.MulTXV(this.m_xf,clipPoints2[_i5].v,cp.localPoint);cp.id.Copy(clipPoints2[_i5].id);}else {cp.localPoint.Copy(clipPoints2[_i5].v);cp.id.cf.typeA=clipPoints2[_i5].id.cf.typeB;cp.id.cf.typeB=clipPoints2[_i5].id.cf.typeA;cp.id.cf.indexA=clipPoints2[_i5].id.cf.indexB;cp.id.cf.indexB=clipPoints2[_i5].id.cf.indexA;}++pointCount;}}manifold.pointCount=pointCount;};_proto32.ComputeEdgeSeparation=function ComputeEdgeSeparation(out){var axis=out;axis.type=b2EPAxisType.e_edgeA;axis.index=this.m_front?0:1;axis.separation=b2_maxFloat;for(var i=0;i<this.m_polygonB.count;++i){var 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;};_proto32.ComputePolygonSeparation=function ComputePolygonSeparation(out){var axis=out;axis.type=b2EPAxisType.e_unknown;axis.index=-1;axis.separation=-b2_maxFloat;var perp=b2EPCollider.s_perp.Set(-this.m_normal.y,this.m_normal.x);for(var i=0;i<this.m_polygonB.count;++i){var n=b2Vec2.NegV(this.m_polygonB.normals[i],b2EPCollider.s_n);var s1=b2Vec2.DotVV(n,b2Vec2.SubVV(this.m_polygonB.vertices[i],this.m_v1,b2Vec2.s_t0));var s2=b2Vec2.DotVV(n,b2Vec2.SubVV(this.m_polygonB.vertices[i],this.m_v2,b2Vec2.s_t0));var 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;};return b2EPCollider;}();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();var b2CollideEdgeAndPolygon_s_collider=new b2EPCollider();function b2CollideEdgeAndPolygon(manifold,edgeA,xfA,polygonB,xfB){var collider=b2CollideEdgeAndPolygon_s_collider;collider.Collide(manifold,edgeA,xfA,polygonB,xfB);}var b2MassData=function b2MassData(){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={}));var b2Shape=function(){function b2Shape(type,radius){this.m_type=exports.b2ShapeType.e_unknown;this.m_radius=0;this.m_type=type;this.m_radius=radius;}var _proto33=b2Shape.prototype;_proto33.Copy=function Copy(other){this.m_radius=other.m_radius;return this;};_proto33.GetType=function GetType(){return this.m_type;};return b2Shape;}();var b2CircleShape=function(_b2Shape){_inheritsLoose(b2CircleShape,_b2Shape);function b2CircleShape(radius){var _this2;if(radius===void 0){radius=0;}_this2=_b2Shape.call(this,exports.b2ShapeType.e_circleShape,radius)||this;_this2.m_p=new b2Vec2();return _this2;}var _proto34=b2CircleShape.prototype;_proto34.Set=function Set(position,radius){if(radius===void 0){radius=this.m_radius;}this.m_p.Copy(position);this.m_radius=radius;return this;};_proto34.Clone=function Clone(){return new b2CircleShape().Copy(this);};_proto34.Copy=function Copy(other){_b2Shape.prototype.Copy.call(this,other);this.m_p.Copy(other.m_p);return this;};_proto34.GetChildCount=function GetChildCount(){return 1;};_proto34.TestPoint=function TestPoint(transform,p){var center=b2Transform.MulXV(transform,this.m_p,b2CircleShape.TestPoint_s_center);var d=b2Vec2.SubVV(p,center,b2CircleShape.TestPoint_s_d);return b2Vec2.DotVV(d,d)<=b2Sq(this.m_radius);};_proto34.ComputeDistance=function ComputeDistance(xf,p,normal,childIndex){var center=b2Transform.MulXV(xf,this.m_p,b2CircleShape.ComputeDistance_s_center);b2Vec2.SubVV(p,center,normal);return normal.Normalize()-this.m_radius;};_proto34.RayCast=function RayCast(output,input,transform,childIndex){var position=b2Transform.MulXV(transform,this.m_p,b2CircleShape.RayCast_s_position);var s=b2Vec2.SubVV(input.p1,position,b2CircleShape.RayCast_s_s);var b=b2Vec2.DotVV(s,s)-b2Sq(this.m_radius);var r=b2Vec2.SubVV(input.p2,input.p1,b2CircleShape.RayCast_s_r);var c=b2Vec2.DotVV(s,r);var rr=b2Vec2.DotVV(r,r);var sigma=c*c-rr*b;if(sigma<0||rr<b2_epsilon){return false;}var 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;};_proto34.ComputeAABB=function ComputeAABB(aabb,transform,childIndex){var 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);};_proto34.ComputeMass=function ComputeMass(massData,density){var 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));};_proto34.SetupDistanceProxy=function 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;};_proto34.ComputeSubmergedArea=function ComputeSubmergedArea(normal,offset,xf,c){var p=b2Transform.MulXV(xf,this.m_p,new b2Vec2());var 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;}var r2=this.m_radius*this.m_radius;var l2=l*l;var area=r2*(b2Asin(l/this.m_radius)+b2_pi/2)+l*b2Sqrt(r2-l2);var 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;};_proto34.Dump=function 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);};return b2CircleShape;}(b2Shape);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();var b2PolygonShape=function(_b2Shape2){_inheritsLoose(b2PolygonShape,_b2Shape2);function b2PolygonShape(){var _this3;_this3=_b2Shape2.call(this,exports.b2ShapeType.e_polygonShape,b2_polygonRadius)||this;_this3.m_centroid=new b2Vec2(0,0);_this3.m_vertices=[];_this3.m_normals=[];_this3.m_count=0;return _this3;}var _proto35=b2PolygonShape.prototype;_proto35.Clone=function Clone(){return new b2PolygonShape().Copy(this);};_proto35.Copy=function Copy(other){_b2Shape2.prototype.Copy.call(this,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(var 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;};_proto35.GetChildCount=function GetChildCount(){return 1;};_proto35.Set=function Set(){for(var _len5=arguments.length,args=new Array(_len5),_key6=0;_key6<_len5;_key6++){args[_key6]=arguments[_key6];}if(typeof args[0][0]==="number"){var vertices=args[0];if(vertices.length%2!==0){throw new Error();}return this._Set(function(index){return {x:vertices[index*2],y:vertices[index*2+1]};},vertices.length/2);}else {var _vertices=args[0];var count=args[1]||_vertices.length;return this._Set(function(index){return _vertices[index];},count);}};_proto35._Set=function _Set(vertices,count){if(count<3){return this.SetAsBox(1,1);}var n=count;var ps=[];for(var i=0;i<n;++i){var v=vertices(i);var unique=true;for(var 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);}var i0=0;var x0=ps[0].x;for(var _i6=1;_i6<n;++_i6){var x=ps[_i6].x;if(x>x0||x===x0&&ps[_i6].y<ps[i0].y){i0=_i6;x0=x;}}var hull=[];var m=0;var ih=i0;for(;;){hull[m]=ih;var ie=0;for(var _j2=1;_j2<n;++_j2){if(ie===ih){ie=_j2;continue;}var r=b2Vec2.SubVV(ps[ie],ps[hull[m]],b2PolygonShape.Set_s_r);var _v2=b2Vec2.SubVV(ps[_j2],ps[hull[m]],b2PolygonShape.Set_s_v);var c=b2Vec2.CrossVV(r,_v2);if(c<0){ie=_j2;}if(c===0&&_v2.LengthSquared()>r.LengthSquared()){ie=_j2;}}++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(var _i7=0;_i7<m;++_i7){this.m_vertices[_i7].Copy(ps[hull[_i7]]);}for(var _i8=0;_i8<m;++_i8){var vertexi1=this.m_vertices[_i8];var vertexi2=this.m_vertices[(_i8+1)%m];var edge=b2Vec2.SubVV(vertexi2,vertexi1,b2Vec2.s_t0);b2Vec2.CrossVOne(edge,this.m_normals[_i8]).SelfNormalize();}b2PolygonShape.ComputeCentroid(this.m_vertices,m,this.m_centroid);return this;};_proto35.SetAsBox=function SetAsBox(hx,hy,center,angle){if(angle===void 0){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);var xf=new b2Transform();xf.SetPosition(center);xf.SetRotationAngle(angle);for(var 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;};_proto35.TestPoint=function TestPoint(xf,p){var pLocal=b2Transform.MulTXV(xf,p,b2PolygonShape.TestPoint_s_pLocal);for(var i=0;i<this.m_count;++i){var dot=b2Vec2.DotVV(this.m_normals[i],b2Vec2.SubVV(pLocal,this.m_vertices[i],b2Vec2.s_t0));if(dot>0){return false;}}return true;};_proto35.ComputeDistance=function ComputeDistance(xf,p,normal,childIndex){var pLocal=b2Transform.MulTXV(xf,p,b2PolygonShape.ComputeDistance_s_pLocal);var maxDistance=-b2_maxFloat;var normalForMaxDistance=b2PolygonShape.ComputeDistance_s_normalForMaxDistance.Copy(pLocal);for(var i=0;i<this.m_count;++i){var 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){var minDistance=b2PolygonShape.ComputeDistance_s_minDistance.Copy(normalForMaxDistance);var minDistance2=maxDistance*maxDistance;for(var _i9=0;_i9<this.m_count;++_i9){var distance=b2Vec2.SubVV(pLocal,this.m_vertices[_i9],b2PolygonShape.ComputeDistance_s_distance);var 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;}};_proto35.RayCast=function RayCast(output,input,xf,childIndex){var p1=b2Transform.MulTXV(xf,input.p1,b2PolygonShape.RayCast_s_p1);var p2=b2Transform.MulTXV(xf,input.p2,b2PolygonShape.RayCast_s_p2);var d=b2Vec2.SubVV(p2,p1,b2PolygonShape.RayCast_s_d);var lower=0,upper=input.maxFraction;var index=-1;for(var i=0;i<this.m_count;++i){var numerator=b2Vec2.DotVV(this.m_normals[i],b2Vec2.SubVV(this.m_vertices[i],p1,b2Vec2.s_t0));var 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;};_proto35.ComputeAABB=function ComputeAABB(aabb,xf,childIndex){var lower=b2Transform.MulXV(xf,this.m_vertices[0],aabb.lowerBound);var upper=aabb.upperBound.Copy(lower);for(var i=0;i<this.m_count;++i){var v=b2Transform.MulXV(xf,this.m_vertices[i],b2PolygonShape.ComputeAABB_s_v);b2Vec2.MinV(v,lower,lower);b2Vec2.MaxV(v,upper,upper);}var r=this.m_radius;lower.SelfSubXY(r,r);upper.SelfAddXY(r,r);};_proto35.ComputeMass=function ComputeMass(massData,density){var center=b2PolygonShape.ComputeMass_s_center.SetZero();var area=0;var I=0;var s=b2PolygonShape.ComputeMass_s_s.SetZero();for(var i=0;i<this.m_count;++i){s.SelfAdd(this.m_vertices[i]);}s.SelfMul(1/this.m_count);var k_inv3=1/3;for(var _i10=0;_i10<this.m_count;++_i10){var e1=b2Vec2.SubVV(this.m_vertices[_i10],s,b2PolygonShape.ComputeMass_s_e1);var e2=b2Vec2.SubVV(this.m_vertices[(_i10+1)%this.m_count],s,b2PolygonShape.ComputeMass_s_e2);var D=b2Vec2.CrossVV(e1,e2);var triangleArea=0.5*D;area+=triangleArea;center.SelfAdd(b2Vec2.MulSV(triangleArea*k_inv3,b2Vec2.AddVV(e1,e2,b2Vec2.s_t0),b2Vec2.s_t1));var ex1=e1.x;var ey1=e1.y;var ex2=e2.x;var ey2=e2.y;var intx2=ex1*ex1+ex2*ex1+ex2*ex2;var 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));};_proto35.Validate=function Validate(){for(var i=0;i<this.m_count;++i){var i1=i;var i2=(i+1)%this.m_count;var p=this.m_vertices[i1];var e=b2Vec2.SubVV(this.m_vertices[i2],p,b2PolygonShape.Validate_s_e);for(var j=0;j<this.m_count;++j){if(j===i1||j===i2){continue;}var v=b2Vec2.SubVV(this.m_vertices[j],p,b2PolygonShape.Validate_s_v);var c=b2Vec2.CrossVV(e,v);if(c<0){return false;}}}return true;};_proto35.SetupDistanceProxy=function SetupDistanceProxy(proxy,index){proxy.m_vertices=this.m_vertices;proxy.m_count=this.m_count;proxy.m_radius=this.m_radius;};_proto35.ComputeSubmergedArea=function ComputeSubmergedArea(normal,offset,xf,c){var normalL=b2Rot.MulTRV(xf.q,normal,b2PolygonShape.ComputeSubmergedArea_s_normalL);var offsetL=offset-b2Vec2.DotVV(normal,xf.p);var depths=[];var diveCount=0;var intoIndex=-1;var outoIndex=-1;var lastSubmerged=false;for(var _i11=0;_i11<this.m_count;++_i11){depths[_i11]=b2Vec2.DotVV(normalL,this.m_vertices[_i11])-offsetL;var isSubmerged=depths[_i11]<-b2_epsilon;if(_i11>0){if(isSubmerged){if(!lastSubmerged){intoIndex=_i11-1;diveCount++;}}else {if(lastSubmerged){outoIndex=_i11-1;diveCount++;}}}lastSubmerged=isSubmerged;}switch(diveCount){case 0:if(lastSubmerged){var 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;}var intoIndex2=(intoIndex+1)%this.m_count;var outoIndex2=(outoIndex+1)%this.m_count;var intoLamdda=(0-depths[intoIndex])/(depths[intoIndex2]-depths[intoIndex]);var outoLamdda=(0-depths[outoIndex])/(depths[outoIndex2]-depths[outoIndex]);var 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);var 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);var area=0;var center=b2PolygonShape.ComputeSubmergedArea_s_center.SetZero();var p2=this.m_vertices[intoIndex2];var p3;var i=intoIndex2;while(i!==outoIndex2){i=(i+1)%this.m_count;if(i===outoIndex2){p3=outoVec;}else {p3=this.m_vertices[i];}var 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;};_proto35.Dump=function Dump(log){log("    const shape: b2PolygonShape = new b2PolygonShape();\n");log("    const vs: b2Vec2[] = [];\n");for(var 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);};b2PolygonShape.ComputeCentroid=function ComputeCentroid(vs,count,out){var c=out;c.SetZero();var area=0;var pRef=b2PolygonShape.ComputeCentroid_s_pRef.SetZero();var inv3=1/3;for(var i=0;i<count;++i){var p1=pRef;var p2=vs[i];var p3=vs[(i+1)%count];var e1=b2Vec2.SubVV(p2,p1,b2PolygonShape.ComputeCentroid_s_e1);var e2=b2Vec2.SubVV(p3,p1,b2PolygonShape.ComputeCentroid_s_e2);var D=b2Vec2.CrossVV(e1,e2);var 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;};return b2PolygonShape;}(b2Shape);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();var b2EdgeShape=function(_b2Shape3){_inheritsLoose(b2EdgeShape,_b2Shape3);function b2EdgeShape(){var _this4;_this4=_b2Shape3.call(this,exports.b2ShapeType.e_edgeShape,b2_polygonRadius)||this;_this4.m_vertex1=new b2Vec2();_this4.m_vertex2=new b2Vec2();_this4.m_vertex0=new b2Vec2();_this4.m_vertex3=new b2Vec2();_this4.m_hasVertex0=false;_this4.m_hasVertex3=false;return _this4;}var _proto36=b2EdgeShape.prototype;_proto36.Set=function Set(v1,v2){this.m_vertex1.Copy(v1);this.m_vertex2.Copy(v2);this.m_hasVertex0=false;this.m_hasVertex3=false;return this;};_proto36.Clone=function Clone(){return new b2EdgeShape().Copy(this);};_proto36.Copy=function Copy(other){_b2Shape3.prototype.Copy.call(this,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;};_proto36.GetChildCount=function GetChildCount(){return 1;};_proto36.TestPoint=function TestPoint(xf,p){return false;};_proto36.ComputeDistance=function ComputeDistance(xf,p,normal,childIndex){var v1=b2Transform.MulXV(xf,this.m_vertex1,b2EdgeShape.ComputeDistance_s_v1);var v2=b2Transform.MulXV(xf,this.m_vertex2,b2EdgeShape.ComputeDistance_s_v2);var d=b2Vec2.SubVV(p,v1,b2EdgeShape.ComputeDistance_s_d);var s=b2Vec2.SubVV(v2,v1,b2EdgeShape.ComputeDistance_s_s);var ds=b2Vec2.DotVV(d,s);if(ds>0){var 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();};_proto36.RayCast=function RayCast(output,input,xf,childIndex){var p1=b2Transform.MulTXV(xf,input.p1,b2EdgeShape.RayCast_s_p1);var p2=b2Transform.MulTXV(xf,input.p2,b2EdgeShape.RayCast_s_p2);var d=b2Vec2.SubVV(p2,p1,b2EdgeShape.RayCast_s_d);var v1=this.m_vertex1;var v2=this.m_vertex2;var e=b2Vec2.SubVV(v2,v1,b2EdgeShape.RayCast_s_e);var normal=output.normal.Set(e.y,-e.x).SelfNormalize();var numerator=b2Vec2.DotVV(normal,b2Vec2.SubVV(v1,p1,b2Vec2.s_t0));var denominator=b2Vec2.DotVV(normal,d);if(denominator===0){return false;}var t=numerator/denominator;if(t<0||input.maxFraction<t){return false;}var q=b2Vec2.AddVMulSV(p1,t,d,b2EdgeShape.RayCast_s_q);var r=b2Vec2.SubVV(v2,v1,b2EdgeShape.RayCast_s_r);var rr=b2Vec2.DotVV(r,r);if(rr===0){return false;}var 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;};_proto36.ComputeAABB=function ComputeAABB(aabb,xf,childIndex){var v1=b2Transform.MulXV(xf,this.m_vertex1,b2EdgeShape.ComputeAABB_s_v1);var v2=b2Transform.MulXV(xf,this.m_vertex2,b2EdgeShape.ComputeAABB_s_v2);b2Vec2.MinV(v1,v2,aabb.lowerBound);b2Vec2.MaxV(v1,v2,aabb.upperBound);var r=this.m_radius;aabb.lowerBound.SelfSubXY(r,r);aabb.upperBound.SelfAddXY(r,r);};_proto36.ComputeMass=function ComputeMass(massData,density){massData.mass=0;b2Vec2.MidVV(this.m_vertex1,this.m_vertex2,massData.center);massData.I=0;};_proto36.SetupDistanceProxy=function 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;};_proto36.ComputeSubmergedArea=function ComputeSubmergedArea(normal,offset,xf,c){c.SetZero();return 0;};_proto36.Dump=function 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);};return b2EdgeShape;}(b2Shape);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();var b2ChainShape=function(_b2Shape4){_inheritsLoose(b2ChainShape,_b2Shape4);function b2ChainShape(){var _this5;_this5=_b2Shape4.call(this,exports.b2ShapeType.e_chainShape,b2_polygonRadius)||this;_this5.m_vertices=[];_this5.m_count=0;_this5.m_prevVertex=new b2Vec2();_this5.m_nextVertex=new b2Vec2();_this5.m_hasPrevVertex=false;_this5.m_hasNextVertex=false;return _this5;}var _proto37=b2ChainShape.prototype;_proto37.CreateLoop=function CreateLoop(){for(var _len6=arguments.length,args=new Array(_len6),_key7=0;_key7<_len6;_key7++){args[_key7]=arguments[_key7];}if(typeof args[0][0]==="number"){var vertices=args[0];if(vertices.length%2!==0){throw new Error();}return this._CreateLoop(function(index){return {x:vertices[index*2],y:vertices[index*2+1]};},vertices.length/2);}else {var _vertices2=args[0];var count=args[1]||_vertices2.length;return this._CreateLoop(function(index){return _vertices2[index];},count);}};_proto37._CreateLoop=function _CreateLoop(vertices,count){if(count<3){return this;}this.m_count=count+1;this.m_vertices=b2Vec2.MakeArray(this.m_count);for(var 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;};_proto37.CreateChain=function CreateChain(){for(var _len7=arguments.length,args=new Array(_len7),_key8=0;_key8<_len7;_key8++){args[_key8]=arguments[_key8];}if(typeof args[0][0]==="number"){var vertices=args[0];if(vertices.length%2!==0){throw new Error();}return this._CreateChain(function(index){return {x:vertices[index*2],y:vertices[index*2+1]};},vertices.length/2);}else {var _vertices3=args[0];var count=args[1]||_vertices3.length;return this._CreateChain(function(index){return _vertices3[index];},count);}};_proto37._CreateChain=function _CreateChain(vertices,count){this.m_count=count;this.m_vertices=b2Vec2.MakeArray(count);for(var 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;};_proto37.SetPrevVertex=function SetPrevVertex(prevVertex){this.m_prevVertex.Copy(prevVertex);this.m_hasPrevVertex=true;return this;};_proto37.SetNextVertex=function SetNextVertex(nextVertex){this.m_nextVertex.Copy(nextVertex);this.m_hasNextVertex=true;return this;};_proto37.Clone=function Clone(){return new b2ChainShape().Copy(this);};_proto37.Copy=function Copy(other){_b2Shape4.prototype.Copy.call(this,other);this._CreateChain(function(index){return 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;};_proto37.GetChildCount=function GetChildCount(){return this.m_count-1;};_proto37.GetChildEdge=function 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;}};_proto37.TestPoint=function TestPoint(xf,p){return false;};_proto37.ComputeDistance=function ComputeDistance(xf,p,normal,childIndex){var edge=b2ChainShape.ComputeDistance_s_edgeShape;this.GetChildEdge(edge,childIndex);return edge.ComputeDistance(xf,p,normal,0);};_proto37.RayCast=function RayCast(output,input,xf,childIndex){var 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);};_proto37.ComputeAABB=function ComputeAABB(aabb,xf,childIndex){var vertexi1=this.m_vertices[childIndex];var vertexi2=this.m_vertices[(childIndex+1)%this.m_count];var v1=b2Transform.MulXV(xf,vertexi1,b2ChainShape.ComputeAABB_s_v1);var v2=b2Transform.MulXV(xf,vertexi2,b2ChainShape.ComputeAABB_s_v2);b2Vec2.MinV(v1,v2,aabb.lowerBound);b2Vec2.MaxV(v1,v2,aabb.upperBound);};_proto37.ComputeMass=function ComputeMass(massData,density){massData.mass=0;massData.center.SetZero();massData.I=0;};_proto37.SetupDistanceProxy=function 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;};_proto37.ComputeSubmergedArea=function ComputeSubmergedArea(normal,offset,xf,c){c.SetZero();return 0;};_proto37.Dump=function Dump(log){log("    const shape: b2ChainShape = new b2ChainShape();\n");log("    const vs: b2Vec2[] = [];\n");for(var 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");};return b2ChainShape;}(b2Shape);b2ChainShape.ComputeDistance_s_edgeShape=new b2EdgeShape();b2ChainShape.RayCast_s_edgeShape=new b2EdgeShape();b2ChainShape.ComputeAABB_s_v1=new b2Vec2();b2ChainShape.ComputeAABB_s_v2=new b2Vec2();var b2Filter=function(){function b2Filter(){this.categoryBits=0x0001;this.maskBits=0xFFFF;this.groupIndex=0;}var _proto38=b2Filter.prototype;_proto38.Clone=function Clone(){return new b2Filter().Copy(this);};_proto38.Copy=function Copy(other){this.categoryBits=other.categoryBits;this.maskBits=other.maskBits;this.groupIndex=other.groupIndex||0;return this;};return b2Filter;}();b2Filter.DEFAULT=new b2Filter();var b2FixtureDef=function b2FixtureDef(){this.userData=null;this.friction=0.2;this.restitution=0;this.density=0;this.isSensor=false;this.filter=new b2Filter();};var b2FixtureProxy=function(){function b2FixtureProxy(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);}var _proto39=b2FixtureProxy.prototype;_proto39.Reset=function Reset(){this.fixture.m_body.m_world.m_contactManager.m_broadPhase.DestroyProxy(this.treeNode);};_proto39.Touch=function Touch(){this.fixture.m_body.m_world.m_contactManager.m_broadPhase.TouchProxy(this.treeNode);};_proto39.Synchronize=function 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 {var aabb1=b2FixtureProxy.Synchronize_s_aabb1;var 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);}};return b2FixtureProxy;}();b2FixtureProxy.Synchronize_s_aabb1=new b2AABB();b2FixtureProxy.Synchronize_s_aabb2=new b2AABB();var b2Fixture=function(){function b2Fixture(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);}var _proto40=b2Fixture.prototype;_proto40.Reset=function Reset(){};_proto40.GetType=function GetType(){return this.m_shape.GetType();};_proto40.GetShape=function GetShape(){return this.m_shape;};_proto40.SetSensor=function SetSensor(sensor){if(sensor!==this.m_isSensor){this.m_body.SetAwake(true);this.m_isSensor=sensor;}};_proto40.IsSensor=function IsSensor(){return this.m_isSensor;};_proto40.SetFilterData=function SetFilterData(filter){this.m_filter.Copy(filter);this.Refilter();};_proto40.GetFilterData=function GetFilterData(){return this.m_filter;};_proto40.Refilter=function Refilter(){var edge=this.m_body.GetContactList();while(edge){var contact=edge.contact;var fixtureA=contact.GetFixtureA();var fixtureB=contact.GetFixtureB();if(fixtureA===this||fixtureB===this){contact.FlagForFiltering();}edge=edge.next;}this.TouchProxies();};_proto40.GetBody=function GetBody(){return this.m_body;};_proto40.GetNext=function GetNext(){return this.m_next;};_proto40.GetUserData=function GetUserData(){return this.m_userData;};_proto40.SetUserData=function SetUserData(data){this.m_userData=data;};_proto40.TestPoint=function TestPoint(p){return this.m_shape.TestPoint(this.m_body.GetTransform(),p);};_proto40.ComputeDistance=function ComputeDistance(p,normal,childIndex){return this.m_shape.ComputeDistance(this.m_body.GetTransform(),p,normal,childIndex);};_proto40.RayCast=function RayCast(output,input,childIndex){return this.m_shape.RayCast(output,input,this.m_body.GetTransform(),childIndex);};_proto40.GetMassData=function GetMassData(massData){if(massData===void 0){massData=new b2MassData();}this.m_shape.ComputeMass(massData,this.m_density);return massData;};_proto40.SetDensity=function SetDensity(density){this.m_density=density;};_proto40.GetDensity=function GetDensity(){return this.m_density;};_proto40.GetFriction=function GetFriction(){return this.m_friction;};_proto40.SetFriction=function SetFriction(friction){this.m_friction=friction;};_proto40.GetRestitution=function GetRestitution(){return this.m_restitution;};_proto40.SetRestitution=function SetRestitution(restitution){this.m_restitution=restitution;};_proto40.GetAABB=function GetAABB(childIndex){return this.m_proxies[childIndex].aabb;};_proto40.Dump=function 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);};_proto40.CreateProxies=function CreateProxies(){if(this.m_proxies.length!==0){throw new Error();}for(var i=0;i<this.m_shape.GetChildCount();++i){this.m_proxies[i]=new b2FixtureProxy(this,i);}};_proto40.DestroyProxies=function DestroyProxies(){for(var _iterator=_createForOfIteratorHelperLoose(this.m_proxies),_step;!(_step=_iterator()).done;){var proxy=_step.value;proxy.Reset();}this.m_proxies.length=0;};_proto40.TouchProxies=function TouchProxies(){for(var _iterator2=_createForOfIteratorHelperLoose(this.m_proxies),_step2;!(_step2=_iterator2()).done;){var proxy=_step2.value;proxy.Touch();}};_proto40.SynchronizeProxies=function SynchronizeProxies(transform1,transform2,displacement){for(var _iterator3=_createForOfIteratorHelperLoose(this.m_proxies),_step3;!(_step3=_iterator3()).done;){var proxy=_step3.value;proxy.Synchronize(transform1,transform2,displacement);}};_createClass(b2Fixture,[{key:"m_proxyCount",get:function get(){return this.m_proxies.length;}}]);return b2Fixture;}();(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={}));var b2BodyDef=function b2BodyDef(){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;};var b2Body=function(){function b2Body(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;}var _proto41=b2Body.prototype;_proto41.CreateFixture=function CreateFixture(a,b){if(b===void 0){b=0;}if(a instanceof b2Shape){return this.CreateFixtureShapeDensity(a,b);}else {return this.CreateFixtureDef(a);}};_proto41.CreateFixtureDef=function CreateFixtureDef(def){if(this.m_world.IsLocked()){throw new Error();}var 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;};_proto41.CreateFixtureShapeDensity=function CreateFixtureShapeDensity(shape,density){if(density===void 0){density=0;}var def=b2Body.CreateFixtureShapeDensity_s_def;def.shape=shape;def.density=density;return this.CreateFixtureDef(def);};_proto41.DestroyFixture=function DestroyFixture(fixture){if(this.m_world.IsLocked()){throw new Error();}var node=this.m_fixtureList;var 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;}var edge=this.m_contactList;while(edge){var c=edge.contact;edge=edge.next;var fixtureA=c.GetFixtureA();var 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();};_proto41.SetTransformVec=function SetTransformVec(position,angle){this.SetTransformXY(position.x,position.y,angle);};_proto41.SetTransformXY=function 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(var 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();};_proto41.SetTransform=function SetTransform(xf){this.SetTransformVec(xf.p,xf.GetAngle());};_proto41.GetTransform=function GetTransform(){return this.m_xf;};_proto41.GetPosition=function GetPosition(){return this.m_xf.p;};_proto41.SetPosition=function SetPosition(position){this.SetTransformVec(position,this.GetAngle());};_proto41.SetPositionXY=function SetPositionXY(x,y){this.SetTransformXY(x,y,this.GetAngle());};_proto41.GetAngle=function GetAngle(){return this.m_sweep.a;};_proto41.SetAngle=function SetAngle(angle){this.SetTransformVec(this.GetPosition(),angle);};_proto41.GetWorldCenter=function GetWorldCenter(){return this.m_sweep.c;};_proto41.GetLocalCenter=function GetLocalCenter(){return this.m_sweep.localCenter;};_proto41.SetLinearVelocity=function 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);};_proto41.GetLinearVelocity=function GetLinearVelocity(){return this.m_linearVelocity;};_proto41.SetAngularVelocity=function SetAngularVelocity(w){if(this.m_type===exports.b2BodyType.b2_staticBody){return;}if(w*w>0){this.SetAwake(true);}this.m_angularVelocity=w;};_proto41.GetAngularVelocity=function GetAngularVelocity(){return this.m_angularVelocity;};_proto41.GetDefinition=function 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;};_proto41.ApplyForce=function ApplyForce(force,point,wake){if(wake===void 0){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;}};_proto41.ApplyForceToCenter=function ApplyForceToCenter(force,wake){if(wake===void 0){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;}};_proto41.ApplyTorque=function ApplyTorque(torque,wake){if(wake===void 0){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;}};_proto41.ApplyLinearImpulse=function ApplyLinearImpulse(impulse,point,wake){if(wake===void 0){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);}};_proto41.ApplyLinearImpulseToCenter=function ApplyLinearImpulseToCenter(impulse,wake){if(wake===void 0){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;}};_proto41.ApplyAngularImpulse=function ApplyAngularImpulse(impulse,wake){if(wake===void 0){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;}};_proto41.GetMass=function GetMass(){return this.m_mass;};_proto41.GetInertia=function GetInertia(){return this.m_I+this.m_mass*b2Vec2.DotVV(this.m_sweep.localCenter,this.m_sweep.localCenter);};_proto41.GetMassData=function 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;};_proto41.SetMassData=function 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;}var 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);};_proto41.ResetMassData=function 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;}var localCenter=b2Body.ResetMassData_s_localCenter.SetZero();for(var f=this.m_fixtureList;f;f=f.m_next){if(f.m_density===0){continue;}var 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;}var 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);};_proto41.GetWorldPoint=function GetWorldPoint(localPoint,out){return b2Transform.MulXV(this.m_xf,localPoint,out);};_proto41.GetWorldVector=function GetWorldVector(localVector,out){return b2Rot.MulRV(this.m_xf.q,localVector,out);};_proto41.GetLocalPoint=function GetLocalPoint(worldPoint,out){return b2Transform.MulTXV(this.m_xf,worldPoint,out);};_proto41.GetLocalVector=function GetLocalVector(worldVector,out){return b2Rot.MulTRV(this.m_xf.q,worldVector,out);};_proto41.GetLinearVelocityFromWorldPoint=function GetLinearVelocityFromWorldPoint(worldPoint,out){return b2Vec2.AddVCrossSV(this.m_linearVelocity,this.m_angularVelocity,b2Vec2.SubVV(worldPoint,this.m_sweep.c,b2Vec2.s_t0),out);};_proto41.GetLinearVelocityFromLocalPoint=function GetLinearVelocityFromLocalPoint(localPoint,out){return this.GetLinearVelocityFromWorldPoint(this.GetWorldPoint(localPoint,out),out);};_proto41.GetLinearDamping=function GetLinearDamping(){return this.m_linearDamping;};_proto41.SetLinearDamping=function SetLinearDamping(linearDamping){this.m_linearDamping=linearDamping;};_proto41.GetAngularDamping=function GetAngularDamping(){return this.m_angularDamping;};_proto41.SetAngularDamping=function SetAngularDamping(angularDamping){this.m_angularDamping=angularDamping;};_proto41.GetGravityScale=function GetGravityScale(){return this.m_gravityScale;};_proto41.SetGravityScale=function SetGravityScale(scale){this.m_gravityScale=scale;};_proto41.SetType=function 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;var ce=this.m_contactList;while(ce){var ce0=ce;ce=ce.next;this.m_world.m_contactManager.Destroy(ce0.contact);}this.m_contactList=null;for(var f=this.m_fixtureList;f;f=f.m_next){f.TouchProxies();}};_proto41.GetType=function GetType(){return this.m_type;};_proto41.SetBullet=function SetBullet(flag){this.m_bulletFlag=flag;};_proto41.IsBullet=function IsBullet(){return this.m_bulletFlag;};_proto41.SetSleepingAllowed=function SetSleepingAllowed(flag){this.m_autoSleepFlag=flag;if(!flag){this.SetAwake(true);}};_proto41.IsSleepingAllowed=function IsSleepingAllowed(){return this.m_autoSleepFlag;};_proto41.SetAwake=function 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;}};_proto41.IsAwake=function IsAwake(){return this.m_awakeFlag;};_proto41.SetActive=function SetActive(flag){if(this.m_world.IsLocked()){throw new Error();}if(flag===this.IsActive()){return;}this.m_activeFlag=flag;if(flag){for(var f=this.m_fixtureList;f;f=f.m_next){f.CreateProxies();}}else {for(var _f=this.m_fixtureList;_f;_f=_f.m_next){_f.DestroyProxies();}var ce=this.m_contactList;while(ce){var ce0=ce;ce=ce.next;this.m_world.m_contactManager.Destroy(ce0.contact);}this.m_contactList=null;}};_proto41.IsActive=function IsActive(){return this.m_activeFlag;};_proto41.SetFixedRotation=function SetFixedRotation(flag){if(this.m_fixedRotationFlag===flag){return;}this.m_fixedRotationFlag=flag;this.m_angularVelocity=0;this.ResetMassData();};_proto41.IsFixedRotation=function IsFixedRotation(){return this.m_fixedRotationFlag;};_proto41.GetFixtureList=function GetFixtureList(){return this.m_fixtureList;};_proto41.GetJointList=function GetJointList(){return this.m_jointList;};_proto41.GetContactList=function GetContactList(){return this.m_contactList;};_proto41.GetNext=function GetNext(){return this.m_next;};_proto41.GetUserData=function GetUserData(){return this.m_userData;};_proto41.SetUserData=function SetUserData(data){this.m_userData=data;};_proto41.GetWorld=function GetWorld(){return this.m_world;};_proto41.Dump=function Dump(log){var bodyIndex=this.m_islandIndex;log("{\n");log("  const bd: b2BodyDef = new b2BodyDef();\n");var 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(var f=this.m_fixtureList;f;f=f.m_next){log("  {\n");f.Dump(log,bodyIndex);log("  }\n");}log("}\n");};_proto41.SynchronizeFixtures=function SynchronizeFixtures(){var 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);var displacement=b2Vec2.SubVV(this.m_sweep.c,this.m_sweep.c0,b2Body.SynchronizeFixtures_s_displacement);for(var f=this.m_fixtureList;f;f=f.m_next){f.SynchronizeProxies(xf1,this.m_xf,displacement);}};_proto41.SynchronizeTransform=function 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);};_proto41.ShouldCollide=function ShouldCollide(other){if(this.m_type===exports.b2BodyType.b2_staticBody&&other.m_type===exports.b2BodyType.b2_staticBody){return false;}return this.ShouldCollideConnected(other);};_proto41.ShouldCollideConnected=function ShouldCollideConnected(other){for(var jn=this.m_jointList;jn;jn=jn.next){if(jn.other===other){if(!jn.joint.m_collideConnected){return false;}}}return true;};_proto41.Advance=function 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);};_proto41.GetControllerList=function GetControllerList(){return this.m_controllerList;};_proto41.GetControllerCount=function GetControllerCount(){return this.m_controllerCount;};return b2Body;}();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={}));var b2Jacobian=function(){function b2Jacobian(){this.linear=new b2Vec2();this.angularA=0;this.angularB=0;}var _proto42=b2Jacobian.prototype;_proto42.SetZero=function SetZero(){this.linear.SetZero();this.angularA=0;this.angularB=0;return this;};_proto42.Set=function Set(x,a1,a2){this.linear.Copy(x);this.angularA=a1;this.angularB=a2;return this;};return b2Jacobian;}();var b2JointEdge=function(){function b2JointEdge(joint){this._other=null;this.prev=null;this.next=null;this.joint=joint;}var _proto43=b2JointEdge.prototype;_proto43.Reset=function Reset(){this._other=null;this.prev=null;this.next=null;};_createClass(b2JointEdge,[{key:"other",get:function get(){if(this._other===null){throw new Error();}return this._other;},set:function set(value){if(this._other!==null){throw new Error();}this._other=value;}}]);return b2JointEdge;}();var b2JointDef=function b2JointDef(type){this.type=exports.b2JointType.e_unknownJoint;this.userData=null;this.collideConnected=false;this.type=type;};var b2Joint=function(){function b2Joint(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);}var _proto44=b2Joint.prototype;_proto44.GetType=function GetType(){return this.m_type;};_proto44.GetBodyA=function GetBodyA(){return this.m_bodyA;};_proto44.GetBodyB=function GetBodyB(){return this.m_bodyB;};_proto44.GetNext=function GetNext(){return this.m_next;};_proto44.GetUserData=function GetUserData(){return this.m_userData;};_proto44.SetUserData=function SetUserData(data){this.m_userData=data;};_proto44.IsActive=function IsActive(){return this.m_bodyA.IsActive()&&this.m_bodyB.IsActive();};_proto44.GetCollideConnected=function GetCollideConnected(){return this.m_collideConnected;};_proto44.Dump=function Dump(log){log("// Dump is not supported for this joint type.\n");};_proto44.ShiftOrigin=function ShiftOrigin(newOrigin){};return b2Joint;}();var b2DistanceJointDef=function(_b2JointDef){_inheritsLoose(b2DistanceJointDef,_b2JointDef);function b2DistanceJointDef(){var _this6;_this6=_b2JointDef.call(this,exports.b2JointType.e_distanceJoint)||this;_this6.localAnchorA=new b2Vec2();_this6.localAnchorB=new b2Vec2();_this6.length=1;_this6.frequencyHz=0;_this6.dampingRatio=0;return _this6;}var _proto45=b2DistanceJointDef.prototype;_proto45.Initialize=function 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;};return b2DistanceJointDef;}(b2JointDef);var b2DistanceJoint=function(_b2Joint){_inheritsLoose(b2DistanceJoint,_b2Joint);function b2DistanceJoint(def){var _this7;_this7=_b2Joint.call(this,def)||this;_this7.m_frequencyHz=0;_this7.m_dampingRatio=0;_this7.m_bias=0;_this7.m_localAnchorA=new b2Vec2();_this7.m_localAnchorB=new b2Vec2();_this7.m_gamma=0;_this7.m_impulse=0;_this7.m_length=0;_this7.m_indexA=0;_this7.m_indexB=0;_this7.m_u=new b2Vec2();_this7.m_rA=new b2Vec2();_this7.m_rB=new b2Vec2();_this7.m_localCenterA=new b2Vec2();_this7.m_localCenterB=new b2Vec2();_this7.m_invMassA=0;_this7.m_invMassB=0;_this7.m_invIA=0;_this7.m_invIB=0;_this7.m_mass=0;_this7.m_qA=new b2Rot();_this7.m_qB=new b2Rot();_this7.m_lalcA=new b2Vec2();_this7.m_lalcB=new b2Vec2();_this7.m_frequencyHz=b2Maybe(def.frequencyHz,0);_this7.m_dampingRatio=b2Maybe(def.dampingRatio,0);_this7.m_localAnchorA.Copy(def.localAnchorA);_this7.m_localAnchorB.Copy(def.localAnchorB);_this7.m_length=def.length;return _this7;}var _proto46=b2DistanceJoint.prototype;_proto46.GetAnchorA=function GetAnchorA(out){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA,out);};_proto46.GetAnchorB=function GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out);};_proto46.GetReactionForce=function 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;};_proto46.GetReactionTorque=function GetReactionTorque(inv_dt){return 0;};_proto46.GetLocalAnchorA=function GetLocalAnchorA(){return this.m_localAnchorA;};_proto46.GetLocalAnchorB=function GetLocalAnchorB(){return this.m_localAnchorB;};_proto46.SetLength=function SetLength(length){this.m_length=length;};_proto46.Length=function Length(){return this.m_length;};_proto46.SetFrequency=function SetFrequency(hz){this.m_frequencyHz=hz;};_proto46.GetFrequency=function GetFrequency(){return this.m_frequencyHz;};_proto46.SetDampingRatio=function SetDampingRatio(ratio){this.m_dampingRatio=ratio;};_proto46.GetDampingRatio=function GetDampingRatio(){return this.m_dampingRatio;};_proto46.Dump=function Dump(log){var indexA=this.m_bodyA.m_islandIndex;var 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);};_proto46.InitVelocityConstraints=function 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;var cA=data.positions[this.m_indexA].c;var aA=data.positions[this.m_indexA].a;var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var cB=data.positions[this.m_indexB].c;var aB=data.positions[this.m_indexB].a;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var 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;var length=this.m_u.Length();if(length>b2_linearSlop){this.m_u.SelfMul(1/length);}else {this.m_u.SetZero();}var crAu=b2Vec2.CrossVV(this.m_rA,this.m_u);var crBu=b2Vec2.CrossVV(this.m_rB,this.m_u);var 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){var C=length-this.m_length;var omega=2*b2_pi*this.m_frequencyHz;var d=2*this.m_mass*this.m_dampingRatio*omega;var k=this.m_mass*omega*omega;var 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;var 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;};_proto46.SolveVelocityConstraints=function SolveVelocityConstraints(data){var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var vpA=b2Vec2.AddVCrossSV(vA,wA,this.m_rA,b2DistanceJoint.SolveVelocityConstraints_s_vpA);var vpB=b2Vec2.AddVCrossSV(vB,wB,this.m_rB,b2DistanceJoint.SolveVelocityConstraints_s_vpB);var Cdot=b2Vec2.DotVV(this.m_u,b2Vec2.SubVV(vpB,vpA,b2Vec2.s_t0));var impulse=-this.m_mass*(Cdot+this.m_bias+this.m_gamma*this.m_impulse);this.m_impulse+=impulse;var 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;};_proto46.SolvePositionConstraints=function SolvePositionConstraints(data){if(this.m_frequencyHz>0){return true;}var cA=data.positions[this.m_indexA].c;var aA=data.positions[this.m_indexA].a;var cB=data.positions[this.m_indexB].c;var aB=data.positions[this.m_indexB].a;var qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);var rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);var rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);var u=this.m_u;u.x=cB.x+rB.x-cA.x-rA.x;u.y=cB.y+rB.y-cA.y-rA.y;var length=this.m_u.Normalize();var C=length-this.m_length;C=b2Clamp(C,-b2_maxLinearCorrection,b2_maxLinearCorrection);var impulse=-this.m_mass*C;var 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;};return b2DistanceJoint;}(b2Joint);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();var b2AreaJointDef=function(_b2JointDef2){_inheritsLoose(b2AreaJointDef,_b2JointDef2);function b2AreaJointDef(){var _this8;_this8=_b2JointDef2.call(this,exports.b2JointType.e_areaJoint)||this;_this8.bodies=[];_this8.frequencyHz=0;_this8.dampingRatio=0;return _this8;}var _proto47=b2AreaJointDef.prototype;_proto47.AddBody=function AddBody(body){this.bodies.push(body);if(this.bodies.length===1){this.bodyA=body;}else if(this.bodies.length===2){this.bodyB=body;}};return b2AreaJointDef;}(b2JointDef);var b2AreaJoint=function(_b2Joint2){_inheritsLoose(b2AreaJoint,_b2Joint2);function b2AreaJoint(def){var _this9;_this9=_b2Joint2.call(this,def)||this;_this9.m_frequencyHz=0;_this9.m_dampingRatio=0;_this9.m_impulse=0;_this9.m_targetArea=0;_this9.m_delta=new b2Vec2();_this9.m_bodies=def.bodies;_this9.m_frequencyHz=b2Maybe(def.frequencyHz,0);_this9.m_dampingRatio=b2Maybe(def.dampingRatio,0);_this9.m_targetLengths=b2MakeNumberArray(def.bodies.length);_this9.m_normals=b2Vec2.MakeArray(def.bodies.length);_this9.m_joints=[];_this9.m_deltas=b2Vec2.MakeArray(def.bodies.length);var djd=new b2DistanceJointDef();djd.frequencyHz=_this9.m_frequencyHz;djd.dampingRatio=_this9.m_dampingRatio;_this9.m_targetArea=0;for(var i=0;i<_this9.m_bodies.length;++i){var body=_this9.m_bodies[i];var next=_this9.m_bodies[(i+1)%_this9.m_bodies.length];var body_c=body.GetWorldCenter();var next_c=next.GetWorldCenter();_this9.m_targetLengths[i]=b2Vec2.DistanceVV(body_c,next_c);_this9.m_targetArea+=b2Vec2.CrossVV(body_c,next_c);djd.Initialize(body,next,body_c,next_c);_this9.m_joints[i]=body.GetWorld().CreateJoint(djd);}_this9.m_targetArea*=0.5;return _this9;}var _proto48=b2AreaJoint.prototype;_proto48.GetAnchorA=function GetAnchorA(out){return out;};_proto48.GetAnchorB=function GetAnchorB(out){return out;};_proto48.GetReactionForce=function GetReactionForce(inv_dt,out){return out;};_proto48.GetReactionTorque=function GetReactionTorque(inv_dt){return 0;};_proto48.SetFrequency=function SetFrequency(hz){this.m_frequencyHz=hz;for(var i=0;i<this.m_joints.length;++i){this.m_joints[i].SetFrequency(hz);}};_proto48.GetFrequency=function GetFrequency(){return this.m_frequencyHz;};_proto48.SetDampingRatio=function SetDampingRatio(ratio){this.m_dampingRatio=ratio;for(var i=0;i<this.m_joints.length;++i){this.m_joints[i].SetDampingRatio(ratio);}};_proto48.GetDampingRatio=function GetDampingRatio(){return this.m_dampingRatio;};_proto48.Dump=function Dump(log){log("Area joint dumping is not supported.\n");};_proto48.InitVelocityConstraints=function InitVelocityConstraints(data){for(var i=0;i<this.m_bodies.length;++i){var prev=this.m_bodies[(i+this.m_bodies.length-1)%this.m_bodies.length];var next=this.m_bodies[(i+1)%this.m_bodies.length];var prev_c=data.positions[prev.m_islandIndex].c;var next_c=data.positions[next.m_islandIndex].c;var delta=this.m_deltas[i];b2Vec2.SubVV(next_c,prev_c,delta);}if(data.step.warmStarting){this.m_impulse*=data.step.dtRatio;for(var _i12=0;_i12<this.m_bodies.length;++_i12){var body=this.m_bodies[_i12];var body_v=data.velocities[body.m_islandIndex].v;var _delta=this.m_deltas[_i12];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;}};_proto48.SolveVelocityConstraints=function SolveVelocityConstraints(data){var dotMassSum=0;var crossMassSum=0;for(var i=0;i<this.m_bodies.length;++i){var body=this.m_bodies[i];var body_v=data.velocities[body.m_islandIndex].v;var delta=this.m_deltas[i];dotMassSum+=delta.LengthSquared()/body.GetMass();crossMassSum+=b2Vec2.CrossVV(body_v,delta);}var lambda=-2*crossMassSum/dotMassSum;this.m_impulse+=lambda;for(var _i13=0;_i13<this.m_bodies.length;++_i13){var _body=this.m_bodies[_i13];var _body_v=data.velocities[_body.m_islandIndex].v;var _delta2=this.m_deltas[_i13];_body_v.x+=_body.m_invMass*_delta2.y*0.5*lambda;_body_v.y+=_body.m_invMass*-_delta2.x*0.5*lambda;}};_proto48.SolvePositionConstraints=function SolvePositionConstraints(data){var perimeter=0;var area=0;for(var i=0;i<this.m_bodies.length;++i){var body=this.m_bodies[i];var next=this.m_bodies[(i+1)%this.m_bodies.length];var body_c=data.positions[body.m_islandIndex].c;var next_c=data.positions[next.m_islandIndex].c;var delta=b2Vec2.SubVV(next_c,body_c,this.m_delta);var 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;var deltaArea=this.m_targetArea-area;var toExtrude=0.5*deltaArea/perimeter;var done=true;for(var _i14=0;_i14<this.m_bodies.length;++_i14){var _body2=this.m_bodies[_i14];var _body_c=data.positions[_body2.m_islandIndex].c;var next_i=(_i14+1)%this.m_bodies.length;var _delta3=b2Vec2.AddVV(this.m_normals[_i14],this.m_normals[next_i],this.m_delta);_delta3.SelfMul(toExtrude);var norm_sq=_delta3.LengthSquared();if(norm_sq>b2Sq(b2_maxLinearCorrection)){_delta3.SelfMul(b2_maxLinearCorrection/b2Sqrt(norm_sq));}if(norm_sq>b2Sq(b2_linearSlop)){done=false;}_body_c.x+=_delta3.x;_body_c.y+=_delta3.y;}return done;};return b2AreaJoint;}(b2Joint);var b2FrictionJointDef=function(_b2JointDef3){_inheritsLoose(b2FrictionJointDef,_b2JointDef3);function b2FrictionJointDef(){var _this10;_this10=_b2JointDef3.call(this,exports.b2JointType.e_frictionJoint)||this;_this10.localAnchorA=new b2Vec2();_this10.localAnchorB=new b2Vec2();_this10.maxForce=0;_this10.maxTorque=0;return _this10;}var _proto49=b2FrictionJointDef.prototype;_proto49.Initialize=function Initialize(bA,bB,anchor){this.bodyA=bA;this.bodyB=bB;this.bodyA.GetLocalPoint(anchor,this.localAnchorA);this.bodyB.GetLocalPoint(anchor,this.localAnchorB);};return b2FrictionJointDef;}(b2JointDef);var b2FrictionJoint=function(_b2Joint3){_inheritsLoose(b2FrictionJoint,_b2Joint3);function b2FrictionJoint(def){var _this11;_this11=_b2Joint3.call(this,def)||this;_this11.m_localAnchorA=new b2Vec2();_this11.m_localAnchorB=new b2Vec2();_this11.m_linearImpulse=new b2Vec2();_this11.m_angularImpulse=0;_this11.m_maxForce=0;_this11.m_maxTorque=0;_this11.m_indexA=0;_this11.m_indexB=0;_this11.m_rA=new b2Vec2();_this11.m_rB=new b2Vec2();_this11.m_localCenterA=new b2Vec2();_this11.m_localCenterB=new b2Vec2();_this11.m_invMassA=0;_this11.m_invMassB=0;_this11.m_invIA=0;_this11.m_invIB=0;_this11.m_linearMass=new b2Mat22();_this11.m_angularMass=0;_this11.m_qA=new b2Rot();_this11.m_qB=new b2Rot();_this11.m_lalcA=new b2Vec2();_this11.m_lalcB=new b2Vec2();_this11.m_K=new b2Mat22();_this11.m_localAnchorA.Copy(def.localAnchorA);_this11.m_localAnchorB.Copy(def.localAnchorB);_this11.m_linearImpulse.SetZero();_this11.m_maxForce=b2Maybe(def.maxForce,0);_this11.m_maxTorque=b2Maybe(def.maxTorque,0);_this11.m_linearMass.SetZero();return _this11;}var _proto50=b2FrictionJoint.prototype;_proto50.InitVelocityConstraints=function 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;var aA=data.positions[this.m_indexA].a;var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var aB=data.positions[this.m_indexB].a;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);var rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);var rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);var mA=this.m_invMassA,mB=this.m_invMassB;var iA=this.m_invIA,iB=this.m_invIB;var 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;var 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;};_proto50.SolveVelocityConstraints=function SolveVelocityConstraints(data){var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var mA=this.m_invMassA,mB=this.m_invMassB;var iA=this.m_invIA,iB=this.m_invIB;var h=data.step.dt;{var Cdot=wB-wA;var impulse=-this.m_angularMass*Cdot;var oldImpulse=this.m_angularImpulse;var 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;}{var 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);var impulseV=b2Mat22.MulMV(this.m_linearMass,Cdot_v2,b2FrictionJoint.SolveVelocityConstraints_s_impulseV).SelfNeg();var oldImpulseV=b2FrictionJoint.SolveVelocityConstraints_s_oldImpulseV.Copy(this.m_linearImpulse);this.m_linearImpulse.SelfAdd(impulseV);var _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;};_proto50.SolvePositionConstraints=function SolvePositionConstraints(data){return true;};_proto50.GetAnchorA=function GetAnchorA(out){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA,out);};_proto50.GetAnchorB=function GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out);};_proto50.GetReactionForce=function GetReactionForce(inv_dt,out){out.x=inv_dt*this.m_linearImpulse.x;out.y=inv_dt*this.m_linearImpulse.y;return out;};_proto50.GetReactionTorque=function GetReactionTorque(inv_dt){return inv_dt*this.m_angularImpulse;};_proto50.GetLocalAnchorA=function GetLocalAnchorA(){return this.m_localAnchorA;};_proto50.GetLocalAnchorB=function GetLocalAnchorB(){return this.m_localAnchorB;};_proto50.SetMaxForce=function SetMaxForce(force){this.m_maxForce=force;};_proto50.GetMaxForce=function GetMaxForce(){return this.m_maxForce;};_proto50.SetMaxTorque=function SetMaxTorque(torque){this.m_maxTorque=torque;};_proto50.GetMaxTorque=function GetMaxTorque(){return this.m_maxTorque;};_proto50.Dump=function Dump(log){var indexA=this.m_bodyA.m_islandIndex;var 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);};return b2FrictionJoint;}(b2Joint);b2FrictionJoint.SolveVelocityConstraints_s_Cdot_v2=new b2Vec2();b2FrictionJoint.SolveVelocityConstraints_s_impulseV=new b2Vec2();b2FrictionJoint.SolveVelocityConstraints_s_oldImpulseV=new b2Vec2();var b2GearJointDef=function(_b2JointDef4){_inheritsLoose(b2GearJointDef,_b2JointDef4);function b2GearJointDef(){var _this12;_this12=_b2JointDef4.call(this,exports.b2JointType.e_gearJoint)||this;_this12.ratio=1;return _this12;}return b2GearJointDef;}(b2JointDef);var b2GearJoint=function(_b2Joint4){_inheritsLoose(b2GearJoint,_b2Joint4);function b2GearJoint(def){var _this13;_this13=_b2Joint4.call(this,def)||this;_this13.m_typeA=exports.b2JointType.e_unknownJoint;_this13.m_typeB=exports.b2JointType.e_unknownJoint;_this13.m_localAnchorA=new b2Vec2();_this13.m_localAnchorB=new b2Vec2();_this13.m_localAnchorC=new b2Vec2();_this13.m_localAnchorD=new b2Vec2();_this13.m_localAxisC=new b2Vec2();_this13.m_localAxisD=new b2Vec2();_this13.m_referenceAngleA=0;_this13.m_referenceAngleB=0;_this13.m_constant=0;_this13.m_ratio=0;_this13.m_impulse=0;_this13.m_indexA=0;_this13.m_indexB=0;_this13.m_indexC=0;_this13.m_indexD=0;_this13.m_lcA=new b2Vec2();_this13.m_lcB=new b2Vec2();_this13.m_lcC=new b2Vec2();_this13.m_lcD=new b2Vec2();_this13.m_mA=0;_this13.m_mB=0;_this13.m_mC=0;_this13.m_mD=0;_this13.m_iA=0;_this13.m_iB=0;_this13.m_iC=0;_this13.m_iD=0;_this13.m_JvAC=new b2Vec2();_this13.m_JvBD=new b2Vec2();_this13.m_JwA=0;_this13.m_JwB=0;_this13.m_JwC=0;_this13.m_JwD=0;_this13.m_mass=0;_this13.m_qA=new b2Rot();_this13.m_qB=new b2Rot();_this13.m_qC=new b2Rot();_this13.m_qD=new b2Rot();_this13.m_lalcA=new b2Vec2();_this13.m_lalcB=new b2Vec2();_this13.m_lalcC=new b2Vec2();_this13.m_lalcD=new b2Vec2();_this13.m_joint1=def.joint1;_this13.m_joint2=def.joint2;_this13.m_typeA=_this13.m_joint1.GetType();_this13.m_typeB=_this13.m_joint2.GetType();var coordinateA,coordinateB;_this13.m_bodyC=_this13.m_joint1.GetBodyA();_this13.m_bodyA=_this13.m_joint1.GetBodyB();var xfA=_this13.m_bodyA.m_xf;var aA=_this13.m_bodyA.m_sweep.a;var xfC=_this13.m_bodyC.m_xf;var aC=_this13.m_bodyC.m_sweep.a;if(_this13.m_typeA===exports.b2JointType.e_revoluteJoint){var revolute=def.joint1;_this13.m_localAnchorC.Copy(revolute.m_localAnchorA);_this13.m_localAnchorA.Copy(revolute.m_localAnchorB);_this13.m_referenceAngleA=revolute.m_referenceAngle;_this13.m_localAxisC.SetZero();coordinateA=aA-aC-_this13.m_referenceAngleA;}else {var prismatic=def.joint1;_this13.m_localAnchorC.Copy(prismatic.m_localAnchorA);_this13.m_localAnchorA.Copy(prismatic.m_localAnchorB);_this13.m_referenceAngleA=prismatic.m_referenceAngle;_this13.m_localAxisC.Copy(prismatic.m_localXAxisA);var pC=_this13.m_localAnchorC;var pA=b2Rot.MulTRV(xfC.q,b2Vec2.AddVV(b2Rot.MulRV(xfA.q,_this13.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),_this13.m_localAxisC);}_this13.m_bodyD=_this13.m_joint2.GetBodyA();_this13.m_bodyB=_this13.m_joint2.GetBodyB();var xfB=_this13.m_bodyB.m_xf;var aB=_this13.m_bodyB.m_sweep.a;var xfD=_this13.m_bodyD.m_xf;var aD=_this13.m_bodyD.m_sweep.a;if(_this13.m_typeB===exports.b2JointType.e_revoluteJoint){var _revolute=def.joint2;_this13.m_localAnchorD.Copy(_revolute.m_localAnchorA);_this13.m_localAnchorB.Copy(_revolute.m_localAnchorB);_this13.m_referenceAngleB=_revolute.m_referenceAngle;_this13.m_localAxisD.SetZero();coordinateB=aB-aD-_this13.m_referenceAngleB;}else {var _prismatic=def.joint2;_this13.m_localAnchorD.Copy(_prismatic.m_localAnchorA);_this13.m_localAnchorB.Copy(_prismatic.m_localAnchorB);_this13.m_referenceAngleB=_prismatic.m_referenceAngle;_this13.m_localAxisD.Copy(_prismatic.m_localXAxisA);var pD=_this13.m_localAnchorD;var pB=b2Rot.MulTRV(xfD.q,b2Vec2.AddVV(b2Rot.MulRV(xfB.q,_this13.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),_this13.m_localAxisD);}_this13.m_ratio=b2Maybe(def.ratio,1);_this13.m_constant=coordinateA+_this13.m_ratio*coordinateB;_this13.m_impulse=0;return _this13;}var _proto51=b2GearJoint.prototype;_proto51.InitVelocityConstraints=function 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;var aA=data.positions[this.m_indexA].a;var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var aB=data.positions[this.m_indexB].a;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var aC=data.positions[this.m_indexC].a;var vC=data.velocities[this.m_indexC].v;var wC=data.velocities[this.m_indexC].w;var aD=data.positions[this.m_indexD].a;var vD=data.velocities[this.m_indexD].v;var wD=data.velocities[this.m_indexD].w;var 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 {var u=b2Rot.MulRV(qC,this.m_localAxisC,b2GearJoint.InitVelocityConstraints_s_u);b2Vec2.SubVV(this.m_localAnchorC,this.m_lcC,this.m_lalcC);var rC=b2Rot.MulRV(qC,this.m_lalcC,b2GearJoint.InitVelocityConstraints_s_rC);b2Vec2.SubVV(this.m_localAnchorA,this.m_lcA,this.m_lalcA);var 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 {var _u=b2Rot.MulRV(qD,this.m_localAxisD,b2GearJoint.InitVelocityConstraints_s_u);b2Vec2.SubVV(this.m_localAnchorD,this.m_lcD,this.m_lalcD);var rD=b2Rot.MulRV(qD,this.m_lalcD,b2GearJoint.InitVelocityConstraints_s_rD);b2Vec2.SubVV(this.m_localAnchorB,this.m_lcB,this.m_lalcB);var 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;};_proto51.SolveVelocityConstraints=function SolveVelocityConstraints(data){var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var vC=data.velocities[this.m_indexC].v;var wC=data.velocities[this.m_indexC].w;var vD=data.velocities[this.m_indexD].v;var wD=data.velocities[this.m_indexD].w;var 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);var 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;};_proto51.SolvePositionConstraints=function SolvePositionConstraints(data){var cA=data.positions[this.m_indexA].c;var aA=data.positions[this.m_indexA].a;var cB=data.positions[this.m_indexB].c;var aB=data.positions[this.m_indexB].a;var cC=data.positions[this.m_indexC].c;var aC=data.positions[this.m_indexC].a;var cD=data.positions[this.m_indexD].c;var aD=data.positions[this.m_indexD].a;var qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB),qC=this.m_qC.SetAngle(aC),qD=this.m_qD.SetAngle(aD);var linearError=0;var coordinateA,coordinateB;var JvAC=this.m_JvAC,JvBD=this.m_JvBD;var JwA,JwB,JwC,JwD;var 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 {var u=b2Rot.MulRV(qC,this.m_localAxisC,b2GearJoint.SolvePositionConstraints_s_u);var rC=b2Rot.MulRV(qC,this.m_lalcC,b2GearJoint.SolvePositionConstraints_s_rC);var 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;var pC=this.m_lalcC;var 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 {var _u2=b2Rot.MulRV(qD,this.m_localAxisD,b2GearJoint.SolvePositionConstraints_s_u);var rD=b2Rot.MulRV(qD,this.m_lalcD,b2GearJoint.SolvePositionConstraints_s_rD);var rB=b2Rot.MulRV(qB,this.m_lalcB,b2GearJoint.SolvePositionConstraints_s_rB);b2Vec2.MulSV(this.m_ratio,_u2,JvBD);JwD=this.m_ratio*b2Vec2.CrossVV(rD,_u2);JwB=this.m_ratio*b2Vec2.CrossVV(rB,_u2);mass+=this.m_ratio*this.m_ratio*(this.m_mD+this.m_mB)+this.m_iD*JwD*JwD+this.m_iB*JwB*JwB;var pD=this.m_lalcD;var 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);}var C=coordinateA+this.m_ratio*coordinateB-this.m_constant;var 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;};_proto51.GetAnchorA=function GetAnchorA(out){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA,out);};_proto51.GetAnchorB=function GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out);};_proto51.GetReactionForce=function GetReactionForce(inv_dt,out){return b2Vec2.MulSV(inv_dt*this.m_impulse,this.m_JvAC,out);};_proto51.GetReactionTorque=function GetReactionTorque(inv_dt){return inv_dt*this.m_impulse*this.m_JwA;};_proto51.GetJoint1=function GetJoint1(){return this.m_joint1;};_proto51.GetJoint2=function GetJoint2(){return this.m_joint2;};_proto51.GetRatio=function GetRatio(){return this.m_ratio;};_proto51.SetRatio=function SetRatio(ratio){this.m_ratio=ratio;};_proto51.Dump=function Dump(log){var indexA=this.m_bodyA.m_islandIndex;var indexB=this.m_bodyB.m_islandIndex;var index1=this.m_joint1.m_index;var 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);};return b2GearJoint;}(b2Joint);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();var b2MotorJointDef=function(_b2JointDef5){_inheritsLoose(b2MotorJointDef,_b2JointDef5);function b2MotorJointDef(){var _this14;_this14=_b2JointDef5.call(this,exports.b2JointType.e_motorJoint)||this;_this14.linearOffset=new b2Vec2(0,0);_this14.angularOffset=0;_this14.maxForce=1;_this14.maxTorque=1;_this14.correctionFactor=0.3;return _this14;}var _proto52=b2MotorJointDef.prototype;_proto52.Initialize=function Initialize(bA,bB){this.bodyA=bA;this.bodyB=bB;this.bodyA.GetLocalPoint(this.bodyB.GetPosition(),this.linearOffset);var angleA=this.bodyA.GetAngle();var angleB=this.bodyB.GetAngle();this.angularOffset=angleB-angleA;};return b2MotorJointDef;}(b2JointDef);var b2MotorJoint=function(_b2Joint5){_inheritsLoose(b2MotorJoint,_b2Joint5);function b2MotorJoint(def){var _this15;_this15=_b2Joint5.call(this,def)||this;_this15.m_linearOffset=new b2Vec2();_this15.m_angularOffset=0;_this15.m_linearImpulse=new b2Vec2();_this15.m_angularImpulse=0;_this15.m_maxForce=0;_this15.m_maxTorque=0;_this15.m_correctionFactor=0.3;_this15.m_indexA=0;_this15.m_indexB=0;_this15.m_rA=new b2Vec2();_this15.m_rB=new b2Vec2();_this15.m_localCenterA=new b2Vec2();_this15.m_localCenterB=new b2Vec2();_this15.m_linearError=new b2Vec2();_this15.m_angularError=0;_this15.m_invMassA=0;_this15.m_invMassB=0;_this15.m_invIA=0;_this15.m_invIB=0;_this15.m_linearMass=new b2Mat22();_this15.m_angularMass=0;_this15.m_qA=new b2Rot();_this15.m_qB=new b2Rot();_this15.m_K=new b2Mat22();_this15.m_linearOffset.Copy(b2Maybe(def.linearOffset,b2Vec2.ZERO));_this15.m_linearImpulse.SetZero();_this15.m_maxForce=b2Maybe(def.maxForce,0);_this15.m_maxTorque=b2Maybe(def.maxTorque,0);_this15.m_correctionFactor=b2Maybe(def.correctionFactor,0.3);return _this15;}var _proto53=b2MotorJoint.prototype;_proto53.GetAnchorA=function GetAnchorA(out){var pos=this.m_bodyA.GetPosition();out.x=pos.x;out.y=pos.y;return out;};_proto53.GetAnchorB=function GetAnchorB(out){var pos=this.m_bodyB.GetPosition();out.x=pos.x;out.y=pos.y;return out;};_proto53.GetReactionForce=function GetReactionForce(inv_dt,out){return b2Vec2.MulSV(inv_dt,this.m_linearImpulse,out);};_proto53.GetReactionTorque=function GetReactionTorque(inv_dt){return inv_dt*this.m_angularImpulse;};_proto53.SetLinearOffset=function SetLinearOffset(linearOffset){if(!b2Vec2.IsEqualToV(linearOffset,this.m_linearOffset)){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_linearOffset.Copy(linearOffset);}};_proto53.GetLinearOffset=function GetLinearOffset(){return this.m_linearOffset;};_proto53.SetAngularOffset=function SetAngularOffset(angularOffset){if(angularOffset!==this.m_angularOffset){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_angularOffset=angularOffset;}};_proto53.GetAngularOffset=function GetAngularOffset(){return this.m_angularOffset;};_proto53.SetMaxForce=function SetMaxForce(force){this.m_maxForce=force;};_proto53.GetMaxForce=function GetMaxForce(){return this.m_maxForce;};_proto53.SetMaxTorque=function SetMaxTorque(torque){this.m_maxTorque=torque;};_proto53.GetMaxTorque=function GetMaxTorque(){return this.m_maxTorque;};_proto53.InitVelocityConstraints=function 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;var cA=data.positions[this.m_indexA].c;var aA=data.positions[this.m_indexA].a;var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var cB=data.positions[this.m_indexB].c;var aB=data.positions[this.m_indexB].a;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);var rA=b2Rot.MulRV(qA,b2Vec2.SubVV(this.m_linearOffset,this.m_localCenterA,b2Vec2.s_t0),this.m_rA);var rB=b2Rot.MulRV(qB,b2Vec2.NegV(this.m_localCenterB,b2Vec2.s_t0),this.m_rB);var mA=this.m_invMassA,mB=this.m_invMassB;var iA=this.m_invIA,iB=this.m_invIB;var 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;var 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;};_proto53.SolveVelocityConstraints=function SolveVelocityConstraints(data){var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var mA=this.m_invMassA,mB=this.m_invMassB;var iA=this.m_invIA,iB=this.m_invIB;var h=data.step.dt;var inv_h=data.step.inv_dt;{var Cdot=wB-wA+inv_h*this.m_correctionFactor*this.m_angularError;var impulse=-this.m_angularMass*Cdot;var oldImpulse=this.m_angularImpulse;var 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;}{var rA=this.m_rA;var rB=this.m_rB;var 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);var impulse_v2=b2Mat22.MulMV(this.m_linearMass,Cdot_v2,b2MotorJoint.SolveVelocityConstraints_s_impulse_v2).SelfNeg();var oldImpulse_v2=b2MotorJoint.SolveVelocityConstraints_s_oldImpulse_v2.Copy(this.m_linearImpulse);this.m_linearImpulse.SelfAdd(impulse_v2);var _maxImpulse2=h*this.m_maxForce;if(this.m_linearImpulse.LengthSquared()>_maxImpulse2*_maxImpulse2){this.m_linearImpulse.Normalize();this.m_linearImpulse.SelfMul(_maxImpulse2);}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;};_proto53.SolvePositionConstraints=function SolvePositionConstraints(data){return true;};_proto53.Dump=function Dump(log){var indexA=this.m_bodyA.m_islandIndex;var 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);};return b2MotorJoint;}(b2Joint);b2MotorJoint.SolveVelocityConstraints_s_Cdot_v2=new b2Vec2();b2MotorJoint.SolveVelocityConstraints_s_impulse_v2=new b2Vec2();b2MotorJoint.SolveVelocityConstraints_s_oldImpulse_v2=new b2Vec2();var b2MouseJointDef=function(_b2JointDef6){_inheritsLoose(b2MouseJointDef,_b2JointDef6);function b2MouseJointDef(){var _this16;_this16=_b2JointDef6.call(this,exports.b2JointType.e_mouseJoint)||this;_this16.target=new b2Vec2();_this16.maxForce=0;_this16.frequencyHz=5;_this16.dampingRatio=0.7;return _this16;}return b2MouseJointDef;}(b2JointDef);var b2MouseJoint=function(_b2Joint6){_inheritsLoose(b2MouseJoint,_b2Joint6);function b2MouseJoint(def){var _this17;_this17=_b2Joint6.call(this,def)||this;_this17.m_localAnchorB=new b2Vec2();_this17.m_targetA=new b2Vec2();_this17.m_frequencyHz=0;_this17.m_dampingRatio=0;_this17.m_beta=0;_this17.m_impulse=new b2Vec2();_this17.m_maxForce=0;_this17.m_gamma=0;_this17.m_indexA=0;_this17.m_indexB=0;_this17.m_rB=new b2Vec2();_this17.m_localCenterB=new b2Vec2();_this17.m_invMassB=0;_this17.m_invIB=0;_this17.m_mass=new b2Mat22();_this17.m_C=new b2Vec2();_this17.m_qB=new b2Rot();_this17.m_lalcB=new b2Vec2();_this17.m_K=new b2Mat22();_this17.m_targetA.Copy(b2Maybe(def.target,b2Vec2.ZERO));b2Transform.MulTXV(_this17.m_bodyB.GetTransform(),_this17.m_targetA,_this17.m_localAnchorB);_this17.m_maxForce=b2Maybe(def.maxForce,0);_this17.m_impulse.SetZero();_this17.m_frequencyHz=b2Maybe(def.frequencyHz,0);_this17.m_dampingRatio=b2Maybe(def.dampingRatio,0);_this17.m_beta=0;_this17.m_gamma=0;return _this17;}var _proto54=b2MouseJoint.prototype;_proto54.SetTarget=function SetTarget(target){if(!this.m_bodyB.IsAwake()){this.m_bodyB.SetAwake(true);}this.m_targetA.Copy(target);};_proto54.GetTarget=function GetTarget(){return this.m_targetA;};_proto54.SetMaxForce=function SetMaxForce(maxForce){this.m_maxForce=maxForce;};_proto54.GetMaxForce=function GetMaxForce(){return this.m_maxForce;};_proto54.SetFrequency=function SetFrequency(hz){this.m_frequencyHz=hz;};_proto54.GetFrequency=function GetFrequency(){return this.m_frequencyHz;};_proto54.SetDampingRatio=function SetDampingRatio(ratio){this.m_dampingRatio=ratio;};_proto54.GetDampingRatio=function GetDampingRatio(){return this.m_dampingRatio;};_proto54.InitVelocityConstraints=function 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;var cB=data.positions[this.m_indexB].c;var aB=data.positions[this.m_indexB].a;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var qB=this.m_qB.SetAngle(aB);var mass=this.m_bodyB.GetMass();var omega=2*b2_pi*this.m_frequencyHz;var d=2*mass*this.m_dampingRatio*omega;var k=mass*(omega*omega);var 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);var 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;};_proto54.SolveVelocityConstraints=function SolveVelocityConstraints(data){var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var Cdot=b2Vec2.AddVCrossSV(vB,wB,this.m_rB,b2MouseJoint.SolveVelocityConstraints_s_Cdot);var 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);var oldImpulse=b2MouseJoint.SolveVelocityConstraints_s_oldImpulse.Copy(this.m_impulse);this.m_impulse.SelfAdd(impulse);var 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;};_proto54.SolvePositionConstraints=function SolvePositionConstraints(data){return true;};_proto54.GetAnchorA=function GetAnchorA(out){out.x=this.m_targetA.x;out.y=this.m_targetA.y;return out;};_proto54.GetAnchorB=function GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out);};_proto54.GetReactionForce=function GetReactionForce(inv_dt,out){return b2Vec2.MulSV(inv_dt,this.m_impulse,out);};_proto54.GetReactionTorque=function GetReactionTorque(inv_dt){return 0;};_proto54.Dump=function Dump(log){log("Mouse joint dumping is not supported.\n");};_proto54.ShiftOrigin=function ShiftOrigin(newOrigin){this.m_targetA.SelfSub(newOrigin);};return b2MouseJoint;}(b2Joint);b2MouseJoint.SolveVelocityConstraints_s_Cdot=new b2Vec2();b2MouseJoint.SolveVelocityConstraints_s_impulse=new b2Vec2();b2MouseJoint.SolveVelocityConstraints_s_oldImpulse=new b2Vec2();var b2PrismaticJointDef=function(_b2JointDef7){_inheritsLoose(b2PrismaticJointDef,_b2JointDef7);function b2PrismaticJointDef(){var _this18;_this18=_b2JointDef7.call(this,exports.b2JointType.e_prismaticJoint)||this;_this18.localAnchorA=new b2Vec2();_this18.localAnchorB=new b2Vec2();_this18.localAxisA=new b2Vec2(1,0);_this18.referenceAngle=0;_this18.enableLimit=false;_this18.lowerTranslation=0;_this18.upperTranslation=0;_this18.enableMotor=false;_this18.maxMotorForce=0;_this18.motorSpeed=0;return _this18;}var _proto55=b2PrismaticJointDef.prototype;_proto55.Initialize=function 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();};return b2PrismaticJointDef;}(b2JointDef);var b2PrismaticJoint=function(_b2Joint7){_inheritsLoose(b2PrismaticJoint,_b2Joint7);function b2PrismaticJoint(def){var _this19;_this19=_b2Joint7.call(this,def)||this;_this19.m_localAnchorA=new b2Vec2();_this19.m_localAnchorB=new b2Vec2();_this19.m_localXAxisA=new b2Vec2();_this19.m_localYAxisA=new b2Vec2();_this19.m_referenceAngle=0;_this19.m_impulse=new b2Vec3(0,0,0);_this19.m_motorImpulse=0;_this19.m_lowerTranslation=0;_this19.m_upperTranslation=0;_this19.m_maxMotorForce=0;_this19.m_motorSpeed=0;_this19.m_enableLimit=false;_this19.m_enableMotor=false;_this19.m_limitState=exports.b2LimitState.e_inactiveLimit;_this19.m_indexA=0;_this19.m_indexB=0;_this19.m_localCenterA=new b2Vec2();_this19.m_localCenterB=new b2Vec2();_this19.m_invMassA=0;_this19.m_invMassB=0;_this19.m_invIA=0;_this19.m_invIB=0;_this19.m_axis=new b2Vec2(0,0);_this19.m_perp=new b2Vec2(0,0);_this19.m_s1=0;_this19.m_s2=0;_this19.m_a1=0;_this19.m_a2=0;_this19.m_K=new b2Mat33();_this19.m_K3=new b2Mat33();_this19.m_K2=new b2Mat22();_this19.m_motorMass=0;_this19.m_qA=new b2Rot();_this19.m_qB=new b2Rot();_this19.m_lalcA=new b2Vec2();_this19.m_lalcB=new b2Vec2();_this19.m_rA=new b2Vec2();_this19.m_rB=new b2Vec2();_this19.m_localAnchorA.Copy(b2Maybe(def.localAnchorA,b2Vec2.ZERO));_this19.m_localAnchorB.Copy(b2Maybe(def.localAnchorB,b2Vec2.ZERO));_this19.m_localXAxisA.Copy(b2Maybe(def.localAxisA,new b2Vec2(1,0))).SelfNormalize();b2Vec2.CrossOneV(_this19.m_localXAxisA,_this19.m_localYAxisA);_this19.m_referenceAngle=b2Maybe(def.referenceAngle,0);_this19.m_lowerTranslation=b2Maybe(def.lowerTranslation,0);_this19.m_upperTranslation=b2Maybe(def.upperTranslation,0);_this19.m_maxMotorForce=b2Maybe(def.maxMotorForce,0);_this19.m_motorSpeed=b2Maybe(def.motorSpeed,0);_this19.m_enableLimit=b2Maybe(def.enableLimit,false);_this19.m_enableMotor=b2Maybe(def.enableMotor,false);return _this19;}var _proto56=b2PrismaticJoint.prototype;_proto56.InitVelocityConstraints=function 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;var cA=data.positions[this.m_indexA].c;var aA=data.positions[this.m_indexA].a;var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var cB=data.positions[this.m_indexB].c;var aB=data.positions[this.m_indexB].a;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);var rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);var rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);var d=b2Vec2.AddVV(b2Vec2.SubVV(cB,cA,b2Vec2.s_t0),b2Vec2.SubVV(rB,rA,b2Vec2.s_t1),b2PrismaticJoint.InitVelocityConstraints_s_d);var mA=this.m_invMassA,mB=this.m_invMassB;var 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){var 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;var 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);var LA=this.m_impulse.x*this.m_s1+this.m_impulse.y+(this.m_motorImpulse+this.m_impulse.z)*this.m_a1;var 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;};_proto56.SolveVelocityConstraints=function SolveVelocityConstraints(data){var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var mA=this.m_invMassA,mB=this.m_invMassB;var iA=this.m_invIA,iB=this.m_invIB;if(this.m_enableMotor&&this.m_limitState!==exports.b2LimitState.e_equalLimits){var Cdot=b2Vec2.DotVV(this.m_axis,b2Vec2.SubVV(vB,vA,b2Vec2.s_t0))+this.m_a2*wB-this.m_a1*wA;var impulse=this.m_motorMass*(this.m_motorSpeed-Cdot);var oldImpulse=this.m_motorImpulse;var maxImpulse=data.step.dt*this.m_maxMotorForce;this.m_motorImpulse=b2Clamp(this.m_motorImpulse+impulse,-maxImpulse,maxImpulse);impulse=this.m_motorImpulse-oldImpulse;var P=b2Vec2.MulSV(impulse,this.m_axis,b2PrismaticJoint.SolveVelocityConstraints_s_P);var LA=impulse*this.m_a1;var LB=impulse*this.m_a2;vA.SelfMulSub(mA,P);wA-=iA*LA;vB.SelfMulAdd(mB,P);wB+=iB*LB;}var Cdot1_x=b2Vec2.DotVV(this.m_perp,b2Vec2.SubVV(vB,vA,b2Vec2.s_t0))+this.m_s2*wB-this.m_s1*wA;var Cdot1_y=wB-wA;if(this.m_enableLimit&&this.m_limitState!==exports.b2LimitState.e_inactiveLimit){var Cdot2=b2Vec2.DotVV(this.m_axis,b2Vec2.SubVV(vB,vA,b2Vec2.s_t0))+this.m_a2*wB-this.m_a1*wA;var f1=b2PrismaticJoint.SolveVelocityConstraints_s_f1.Copy(this.m_impulse);var 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);}var b_x=-Cdot1_x-(this.m_impulse.z-f1.z)*this.m_K.ez.x;var b_y=-Cdot1_y-(this.m_impulse.z-f1.z)*this.m_K.ez.y;var 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;var _P3=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);var _LA=df3.x*this.m_s1+df3.y+df3.z*this.m_a1;var _LB=df3.x*this.m_s2+df3.y+df3.z*this.m_a2;vA.SelfMulSub(mA,_P3);wA-=iA*_LA;vB.SelfMulAdd(mB,_P3);wB+=iB*_LB;}else {var 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;var _P4=b2Vec2.MulSV(df2.x,this.m_perp,b2PrismaticJoint.SolveVelocityConstraints_s_P);var _LA2=df2.x*this.m_s1+df2.y;var _LB2=df2.x*this.m_s2+df2.y;vA.SelfMulSub(mA,_P4);wA-=iA*_LA2;vB.SelfMulAdd(mB,_P4);wB+=iB*_LB2;}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;};_proto56.SolvePositionConstraints=function SolvePositionConstraints(data){var cA=data.positions[this.m_indexA].c;var aA=data.positions[this.m_indexA].a;var cB=data.positions[this.m_indexB].c;var aB=data.positions[this.m_indexB].a;var qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);var mA=this.m_invMassA,mB=this.m_invMassB;var iA=this.m_invIA,iB=this.m_invIB;var rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);var rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);var d=b2Vec2.SubVV(b2Vec2.AddVV(cB,rB,b2Vec2.s_t0),b2Vec2.AddVV(cA,rA,b2Vec2.s_t1),b2PrismaticJoint.SolvePositionConstraints_s_d);var axis=b2Rot.MulRV(qA,this.m_localXAxisA,this.m_axis);var a1=b2Vec2.CrossVV(b2Vec2.AddVV(d,rA,b2Vec2.s_t0),axis);var a2=b2Vec2.CrossVV(rB,axis);var perp=b2Rot.MulRV(qA,this.m_localYAxisA,this.m_perp);var s1=b2Vec2.CrossVV(b2Vec2.AddVV(d,rA,b2Vec2.s_t0),perp);var s2=b2Vec2.CrossVV(rB,perp);var impulse=b2PrismaticJoint.SolvePositionConstraints_s_impulse;var C1_x=b2Vec2.DotVV(perp,d);var C1_y=aB-aA-this.m_referenceAngle;var linearError=b2Abs(C1_x);var angularError=b2Abs(C1_y);var active=false;var C2=0;if(this.m_enableLimit){var 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){var k11=mA+mB+iA*s1*s1+iB*s2*s2;var k12=iA*s1+iB*s2;var k13=iA*s1*a1+iB*s2*a2;var k22=iA+iB;if(k22===0){k22=1;}var k23=iA*a1+iB*a2;var k33=mA+mB+iA*a1*a1+iB*a2*a2;var 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 {var _k=mA+mB+iA*s1*s1+iB*s2*s2;var _k2=iA*s1+iB*s2;var _k3=iA+iB;if(_k3===0){_k3=1;}var K2=this.m_K2;K2.ex.Set(_k,_k2);K2.ey.Set(_k2,_k3);var impulse1=K2.Solve(-C1_x,-C1_y,b2PrismaticJoint.SolvePositionConstraints_s_impulse1);impulse.x=impulse1.x;impulse.y=impulse1.y;impulse.z=0;}var P=b2Vec2.AddVV(b2Vec2.MulSV(impulse.x,perp,b2Vec2.s_t0),b2Vec2.MulSV(impulse.z,axis,b2Vec2.s_t1),b2PrismaticJoint.SolvePositionConstraints_s_P);var LA=impulse.x*s1+impulse.y+impulse.z*a1;var 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;};_proto56.GetAnchorA=function GetAnchorA(out){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA,out);};_proto56.GetAnchorB=function GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out);};_proto56.GetReactionForce=function 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;};_proto56.GetReactionTorque=function GetReactionTorque(inv_dt){return inv_dt*this.m_impulse.y;};_proto56.GetLocalAnchorA=function GetLocalAnchorA(){return this.m_localAnchorA;};_proto56.GetLocalAnchorB=function GetLocalAnchorB(){return this.m_localAnchorB;};_proto56.GetLocalAxisA=function GetLocalAxisA(){return this.m_localXAxisA;};_proto56.GetReferenceAngle=function GetReferenceAngle(){return this.m_referenceAngle;};_proto56.GetJointTranslation=function GetJointTranslation(){var pA=this.m_bodyA.GetWorldPoint(this.m_localAnchorA,b2PrismaticJoint.GetJointTranslation_s_pA);var pB=this.m_bodyB.GetWorldPoint(this.m_localAnchorB,b2PrismaticJoint.GetJointTranslation_s_pB);var d=b2Vec2.SubVV(pB,pA,b2PrismaticJoint.GetJointTranslation_s_d);var axis=this.m_bodyA.GetWorldVector(this.m_localXAxisA,b2PrismaticJoint.GetJointTranslation_s_axis);var translation=b2Vec2.DotVV(d,axis);return translation;};_proto56.GetJointSpeed=function GetJointSpeed(){var bA=this.m_bodyA;var bB=this.m_bodyB;b2Vec2.SubVV(this.m_localAnchorA,bA.m_sweep.localCenter,this.m_lalcA);var 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);var rB=b2Rot.MulRV(bB.m_xf.q,this.m_lalcB,this.m_rB);var pA=b2Vec2.AddVV(bA.m_sweep.c,rA,b2Vec2.s_t0);var pB=b2Vec2.AddVV(bB.m_sweep.c,rB,b2Vec2.s_t1);var d=b2Vec2.SubVV(pB,pA,b2Vec2.s_t2);var axis=bA.GetWorldVector(this.m_localXAxisA,this.m_axis);var vA=bA.m_linearVelocity;var vB=bB.m_linearVelocity;var wA=bA.m_angularVelocity;var wB=bB.m_angularVelocity;var 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;};_proto56.IsLimitEnabled=function IsLimitEnabled(){return this.m_enableLimit;};_proto56.EnableLimit=function 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;}};_proto56.GetLowerLimit=function GetLowerLimit(){return this.m_lowerTranslation;};_proto56.GetUpperLimit=function GetUpperLimit(){return this.m_upperTranslation;};_proto56.SetLimits=function 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;}};_proto56.IsMotorEnabled=function IsMotorEnabled(){return this.m_enableMotor;};_proto56.EnableMotor=function EnableMotor(flag){if(flag!==this.m_enableMotor){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_enableMotor=flag;}};_proto56.SetMotorSpeed=function SetMotorSpeed(speed){if(speed!==this.m_motorSpeed){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_motorSpeed=speed;}};_proto56.GetMotorSpeed=function GetMotorSpeed(){return this.m_motorSpeed;};_proto56.SetMaxMotorForce=function SetMaxMotorForce(force){if(force!==this.m_maxMotorForce){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_maxMotorForce=force;}};_proto56.GetMaxMotorForce=function GetMaxMotorForce(){return this.m_maxMotorForce;};_proto56.GetMotorForce=function GetMotorForce(inv_dt){return inv_dt*this.m_motorImpulse;};_proto56.Dump=function Dump(log){var indexA=this.m_bodyA.m_islandIndex;var 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);};return b2PrismaticJoint;}(b2Joint);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();var b2_minPulleyLength=2;var b2PulleyJointDef=function(_b2JointDef8){_inheritsLoose(b2PulleyJointDef,_b2JointDef8);function b2PulleyJointDef(){var _this20;_this20=_b2JointDef8.call(this,exports.b2JointType.e_pulleyJoint)||this;_this20.groundAnchorA=new b2Vec2(-1,1);_this20.groundAnchorB=new b2Vec2(1,1);_this20.localAnchorA=new b2Vec2(-1,0);_this20.localAnchorB=new b2Vec2(1,0);_this20.lengthA=0;_this20.lengthB=0;_this20.ratio=1;_this20.collideConnected=true;return _this20;}var _proto57=b2PulleyJointDef.prototype;_proto57.Initialize=function 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;};return b2PulleyJointDef;}(b2JointDef);var b2PulleyJoint=function(_b2Joint8){_inheritsLoose(b2PulleyJoint,_b2Joint8);function b2PulleyJoint(def){var _this21;_this21=_b2Joint8.call(this,def)||this;_this21.m_groundAnchorA=new b2Vec2();_this21.m_groundAnchorB=new b2Vec2();_this21.m_lengthA=0;_this21.m_lengthB=0;_this21.m_localAnchorA=new b2Vec2();_this21.m_localAnchorB=new b2Vec2();_this21.m_constant=0;_this21.m_ratio=0;_this21.m_impulse=0;_this21.m_indexA=0;_this21.m_indexB=0;_this21.m_uA=new b2Vec2();_this21.m_uB=new b2Vec2();_this21.m_rA=new b2Vec2();_this21.m_rB=new b2Vec2();_this21.m_localCenterA=new b2Vec2();_this21.m_localCenterB=new b2Vec2();_this21.m_invMassA=0;_this21.m_invMassB=0;_this21.m_invIA=0;_this21.m_invIB=0;_this21.m_mass=0;_this21.m_qA=new b2Rot();_this21.m_qB=new b2Rot();_this21.m_lalcA=new b2Vec2();_this21.m_lalcB=new b2Vec2();_this21.m_groundAnchorA.Copy(b2Maybe(def.groundAnchorA,new b2Vec2(-1,1)));_this21.m_groundAnchorB.Copy(b2Maybe(def.groundAnchorB,new b2Vec2(1,0)));_this21.m_localAnchorA.Copy(b2Maybe(def.localAnchorA,new b2Vec2(-1,0)));_this21.m_localAnchorB.Copy(b2Maybe(def.localAnchorB,new b2Vec2(1,0)));_this21.m_lengthA=b2Maybe(def.lengthA,0);_this21.m_lengthB=b2Maybe(def.lengthB,0);_this21.m_ratio=b2Maybe(def.ratio,1);_this21.m_constant=b2Maybe(def.lengthA,0)+_this21.m_ratio*b2Maybe(def.lengthB,0);_this21.m_impulse=0;return _this21;}var _proto58=b2PulleyJoint.prototype;_proto58.InitVelocityConstraints=function 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;var cA=data.positions[this.m_indexA].c;var aA=data.positions[this.m_indexA].a;var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var cB=data.positions[this.m_indexB].c;var aB=data.positions[this.m_indexB].a;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var 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);var lengthA=this.m_uA.Length();var 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();}var ruA=b2Vec2.CrossVV(this.m_rA,this.m_uA);var ruB=b2Vec2.CrossVV(this.m_rB,this.m_uB);var mA=this.m_invMassA+this.m_invIA*ruA*ruA;var 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;var PA=b2Vec2.MulSV(-this.m_impulse,this.m_uA,b2PulleyJoint.InitVelocityConstraints_s_PA);var 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;};_proto58.SolveVelocityConstraints=function SolveVelocityConstraints(data){var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var vpA=b2Vec2.AddVCrossSV(vA,wA,this.m_rA,b2PulleyJoint.SolveVelocityConstraints_s_vpA);var vpB=b2Vec2.AddVCrossSV(vB,wB,this.m_rB,b2PulleyJoint.SolveVelocityConstraints_s_vpB);var Cdot=-b2Vec2.DotVV(this.m_uA,vpA)-this.m_ratio*b2Vec2.DotVV(this.m_uB,vpB);var impulse=-this.m_mass*Cdot;this.m_impulse+=impulse;var PA=b2Vec2.MulSV(-impulse,this.m_uA,b2PulleyJoint.SolveVelocityConstraints_s_PA);var 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;};_proto58.SolvePositionConstraints=function SolvePositionConstraints(data){var cA=data.positions[this.m_indexA].c;var aA=data.positions[this.m_indexA].a;var cB=data.positions[this.m_indexB].c;var aB=data.positions[this.m_indexB].a;var qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);var rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);var rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);var uA=this.m_uA.Copy(cA).SelfAdd(rA).SelfSub(this.m_groundAnchorA);var uB=this.m_uB.Copy(cB).SelfAdd(rB).SelfSub(this.m_groundAnchorB);var lengthA=uA.Length();var 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();}var ruA=b2Vec2.CrossVV(rA,uA);var ruB=b2Vec2.CrossVV(rB,uB);var mA=this.m_invMassA+this.m_invIA*ruA*ruA;var mB=this.m_invMassB+this.m_invIB*ruB*ruB;var mass=mA+this.m_ratio*this.m_ratio*mB;if(mass>0){mass=1/mass;}var C=this.m_constant-lengthA-this.m_ratio*lengthB;var linearError=b2Abs(C);var impulse=-mass*C;var PA=b2Vec2.MulSV(-impulse,uA,b2PulleyJoint.SolvePositionConstraints_s_PA);var 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;};_proto58.GetAnchorA=function GetAnchorA(out){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA,out);};_proto58.GetAnchorB=function GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out);};_proto58.GetReactionForce=function 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;};_proto58.GetReactionTorque=function GetReactionTorque(inv_dt){return 0;};_proto58.GetGroundAnchorA=function GetGroundAnchorA(){return this.m_groundAnchorA;};_proto58.GetGroundAnchorB=function GetGroundAnchorB(){return this.m_groundAnchorB;};_proto58.GetLengthA=function GetLengthA(){return this.m_lengthA;};_proto58.GetLengthB=function GetLengthB(){return this.m_lengthB;};_proto58.GetRatio=function GetRatio(){return this.m_ratio;};_proto58.GetCurrentLengthA=function GetCurrentLengthA(){var p=this.m_bodyA.GetWorldPoint(this.m_localAnchorA,b2PulleyJoint.GetCurrentLengthA_s_p);var s=this.m_groundAnchorA;return b2Vec2.DistanceVV(p,s);};_proto58.GetCurrentLengthB=function GetCurrentLengthB(){var p=this.m_bodyB.GetWorldPoint(this.m_localAnchorB,b2PulleyJoint.GetCurrentLengthB_s_p);var s=this.m_groundAnchorB;return b2Vec2.DistanceVV(p,s);};_proto58.Dump=function Dump(log){var indexA=this.m_bodyA.m_islandIndex;var 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);};_proto58.ShiftOrigin=function ShiftOrigin(newOrigin){this.m_groundAnchorA.SelfSub(newOrigin);this.m_groundAnchorB.SelfSub(newOrigin);};return b2PulleyJoint;}(b2Joint);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();var b2RevoluteJointDef=function(_b2JointDef9){_inheritsLoose(b2RevoluteJointDef,_b2JointDef9);function b2RevoluteJointDef(){var _this22;_this22=_b2JointDef9.call(this,exports.b2JointType.e_revoluteJoint)||this;_this22.localAnchorA=new b2Vec2(0,0);_this22.localAnchorB=new b2Vec2(0,0);_this22.referenceAngle=0;_this22.enableLimit=false;_this22.lowerAngle=0;_this22.upperAngle=0;_this22.enableMotor=false;_this22.motorSpeed=0;_this22.maxMotorTorque=0;return _this22;}var _proto59=b2RevoluteJointDef.prototype;_proto59.Initialize=function 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();};return b2RevoluteJointDef;}(b2JointDef);var b2RevoluteJoint=function(_b2Joint9){_inheritsLoose(b2RevoluteJoint,_b2Joint9);function b2RevoluteJoint(def){var _this23;_this23=_b2Joint9.call(this,def)||this;_this23.m_localAnchorA=new b2Vec2();_this23.m_localAnchorB=new b2Vec2();_this23.m_impulse=new b2Vec3();_this23.m_motorImpulse=0;_this23.m_enableMotor=false;_this23.m_maxMotorTorque=0;_this23.m_motorSpeed=0;_this23.m_enableLimit=false;_this23.m_referenceAngle=0;_this23.m_lowerAngle=0;_this23.m_upperAngle=0;_this23.m_indexA=0;_this23.m_indexB=0;_this23.m_rA=new b2Vec2();_this23.m_rB=new b2Vec2();_this23.m_localCenterA=new b2Vec2();_this23.m_localCenterB=new b2Vec2();_this23.m_invMassA=0;_this23.m_invMassB=0;_this23.m_invIA=0;_this23.m_invIB=0;_this23.m_mass=new b2Mat33();_this23.m_motorMass=0;_this23.m_limitState=exports.b2LimitState.e_inactiveLimit;_this23.m_qA=new b2Rot();_this23.m_qB=new b2Rot();_this23.m_lalcA=new b2Vec2();_this23.m_lalcB=new b2Vec2();_this23.m_K=new b2Mat22();_this23.m_localAnchorA.Copy(b2Maybe(def.localAnchorA,b2Vec2.ZERO));_this23.m_localAnchorB.Copy(b2Maybe(def.localAnchorB,b2Vec2.ZERO));_this23.m_referenceAngle=b2Maybe(def.referenceAngle,0);_this23.m_impulse.SetZero();_this23.m_motorImpulse=0;_this23.m_lowerAngle=b2Maybe(def.lowerAngle,0);_this23.m_upperAngle=b2Maybe(def.upperAngle,0);_this23.m_maxMotorTorque=b2Maybe(def.maxMotorTorque,0);_this23.m_motorSpeed=b2Maybe(def.motorSpeed,0);_this23.m_enableLimit=b2Maybe(def.enableLimit,false);_this23.m_enableMotor=b2Maybe(def.enableMotor,false);_this23.m_limitState=exports.b2LimitState.e_inactiveLimit;return _this23;}var _proto60=b2RevoluteJoint.prototype;_proto60.InitVelocityConstraints=function 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;var aA=data.positions[this.m_indexA].a;var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var aB=data.positions[this.m_indexB].a;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var 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);var mA=this.m_invMassA,mB=this.m_invMassB;var iA=this.m_invIA,iB=this.m_invIB;var 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){var 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;var 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;};_proto60.SolveVelocityConstraints=function SolveVelocityConstraints(data){var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var mA=this.m_invMassA,mB=this.m_invMassB;var iA=this.m_invIA,iB=this.m_invIB;var fixedRotation=iA+iB===0;if(this.m_enableMotor&&this.m_limitState!==exports.b2LimitState.e_equalLimits&&!fixedRotation){var Cdot=wB-wA-this.m_motorSpeed;var impulse=-this.m_motorMass*Cdot;var oldImpulse=this.m_motorImpulse;var 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){var 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);var Cdot2=wB-wA;var 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){var newImpulse=this.m_impulse.z+impulse_v3.z;if(newImpulse<0){var rhs_x=-Cdot1.x+this.m_impulse.z*this.m_mass.ez.x;var rhs_y=-Cdot1.y+this.m_impulse.z*this.m_mass.ez.y;var 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){var _newImpulse=this.m_impulse.z+impulse_v3.z;if(_newImpulse>0){var _rhs_x=-Cdot1.x+this.m_impulse.z*this.m_mass.ez.x;var _rhs_y=-Cdot1.y+this.m_impulse.z*this.m_mass.ez.y;var _reduced_v=this.m_mass.Solve22(_rhs_x,_rhs_y,b2RevoluteJoint.SolveVelocityConstraints_s_reduced_v2);impulse_v3.x=_reduced_v.x;impulse_v3.y=_reduced_v.y;impulse_v3.z=-this.m_impulse.z;this.m_impulse.x+=_reduced_v.x;this.m_impulse.y+=_reduced_v.y;this.m_impulse.z=0;}else {this.m_impulse.SelfAdd(impulse_v3);}}var 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 {var 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);var 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;};_proto60.SolvePositionConstraints=function SolvePositionConstraints(data){var cA=data.positions[this.m_indexA].c;var aA=data.positions[this.m_indexA].a;var cB=data.positions[this.m_indexB].c;var aB=data.positions[this.m_indexB].a;var qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);var angularError=0;var positionError=0;var fixedRotation=this.m_invIA+this.m_invIB===0;if(this.m_enableLimit&&this.m_limitState!==exports.b2LimitState.e_inactiveLimit&&!fixedRotation){var angle=aB-aA-this.m_referenceAngle;var limitImpulse=0;if(this.m_limitState===exports.b2LimitState.e_equalLimits){var 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){var _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){var _C2=angle-this.m_upperAngle;angularError=_C2;_C2=b2Clamp(_C2-b2_angularSlop,0,b2_maxAngularCorrection);limitImpulse=-this.m_motorMass*_C2;}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);var rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);var rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);var 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();var mA=this.m_invMassA,mB=this.m_invMassB;var iA=this.m_invIA,iB=this.m_invIB;var 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;var 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;};_proto60.GetAnchorA=function GetAnchorA(out){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA,out);};_proto60.GetAnchorB=function GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out);};_proto60.GetReactionForce=function GetReactionForce(inv_dt,out){out.x=inv_dt*this.m_impulse.x;out.y=inv_dt*this.m_impulse.y;return out;};_proto60.GetReactionTorque=function GetReactionTorque(inv_dt){return inv_dt*this.m_impulse.z;};_proto60.GetLocalAnchorA=function GetLocalAnchorA(){return this.m_localAnchorA;};_proto60.GetLocalAnchorB=function GetLocalAnchorB(){return this.m_localAnchorB;};_proto60.GetReferenceAngle=function GetReferenceAngle(){return this.m_referenceAngle;};_proto60.GetJointAngle=function GetJointAngle(){return this.m_bodyB.m_sweep.a-this.m_bodyA.m_sweep.a-this.m_referenceAngle;};_proto60.GetJointSpeed=function GetJointSpeed(){return this.m_bodyB.m_angularVelocity-this.m_bodyA.m_angularVelocity;};_proto60.IsMotorEnabled=function IsMotorEnabled(){return this.m_enableMotor;};_proto60.EnableMotor=function EnableMotor(flag){if(flag!==this.m_enableMotor){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_enableMotor=flag;}};_proto60.GetMotorTorque=function GetMotorTorque(inv_dt){return inv_dt*this.m_motorImpulse;};_proto60.GetMotorSpeed=function GetMotorSpeed(){return this.m_motorSpeed;};_proto60.SetMaxMotorTorque=function SetMaxMotorTorque(torque){if(torque!==this.m_maxMotorTorque){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_maxMotorTorque=torque;}};_proto60.GetMaxMotorTorque=function GetMaxMotorTorque(){return this.m_maxMotorTorque;};_proto60.IsLimitEnabled=function IsLimitEnabled(){return this.m_enableLimit;};_proto60.EnableLimit=function 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;}};_proto60.GetLowerLimit=function GetLowerLimit(){return this.m_lowerAngle;};_proto60.GetUpperLimit=function GetUpperLimit(){return this.m_upperAngle;};_proto60.SetLimits=function 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;}};_proto60.SetMotorSpeed=function SetMotorSpeed(speed){if(speed!==this.m_motorSpeed){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_motorSpeed=speed;}};_proto60.Dump=function Dump(log){var indexA=this.m_bodyA.m_islandIndex;var 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);};return b2RevoluteJoint;}(b2Joint);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();var b2RopeJointDef=function(_b2JointDef10){_inheritsLoose(b2RopeJointDef,_b2JointDef10);function b2RopeJointDef(){var _this24;_this24=_b2JointDef10.call(this,exports.b2JointType.e_ropeJoint)||this;_this24.localAnchorA=new b2Vec2(-1,0);_this24.localAnchorB=new b2Vec2(1,0);_this24.maxLength=0;return _this24;}return b2RopeJointDef;}(b2JointDef);var b2RopeJoint=function(_b2Joint10){_inheritsLoose(b2RopeJoint,_b2Joint10);function b2RopeJoint(def){var _this25;_this25=_b2Joint10.call(this,def)||this;_this25.m_localAnchorA=new b2Vec2();_this25.m_localAnchorB=new b2Vec2();_this25.m_maxLength=0;_this25.m_length=0;_this25.m_impulse=0;_this25.m_indexA=0;_this25.m_indexB=0;_this25.m_u=new b2Vec2();_this25.m_rA=new b2Vec2();_this25.m_rB=new b2Vec2();_this25.m_localCenterA=new b2Vec2();_this25.m_localCenterB=new b2Vec2();_this25.m_invMassA=0;_this25.m_invMassB=0;_this25.m_invIA=0;_this25.m_invIB=0;_this25.m_mass=0;_this25.m_state=exports.b2LimitState.e_inactiveLimit;_this25.m_qA=new b2Rot();_this25.m_qB=new b2Rot();_this25.m_lalcA=new b2Vec2();_this25.m_lalcB=new b2Vec2();_this25.m_localAnchorA.Copy(b2Maybe(def.localAnchorA,new b2Vec2(-1,0)));_this25.m_localAnchorB.Copy(b2Maybe(def.localAnchorB,new b2Vec2(1,0)));_this25.m_maxLength=b2Maybe(def.maxLength,0);return _this25;}var _proto61=b2RopeJoint.prototype;_proto61.InitVelocityConstraints=function 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;var cA=data.positions[this.m_indexA].c;var aA=data.positions[this.m_indexA].a;var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var cB=data.positions[this.m_indexB].c;var aB=data.positions[this.m_indexB].a;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var 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();var 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;}var crA=b2Vec2.CrossVV(this.m_rA,this.m_u);var crB=b2Vec2.CrossVV(this.m_rB,this.m_u);var 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;var 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;};_proto61.SolveVelocityConstraints=function SolveVelocityConstraints(data){var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var vpA=b2Vec2.AddVCrossSV(vA,wA,this.m_rA,b2RopeJoint.SolveVelocityConstraints_s_vpA);var vpB=b2Vec2.AddVCrossSV(vB,wB,this.m_rB,b2RopeJoint.SolveVelocityConstraints_s_vpB);var C=this.m_length-this.m_maxLength;var Cdot=b2Vec2.DotVV(this.m_u,b2Vec2.SubVV(vpB,vpA,b2Vec2.s_t0));if(C<0){Cdot+=data.step.inv_dt*C;}var impulse=-this.m_mass*Cdot;var oldImpulse=this.m_impulse;this.m_impulse=b2Min(0,this.m_impulse+impulse);impulse=this.m_impulse-oldImpulse;var 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;};_proto61.SolvePositionConstraints=function SolvePositionConstraints(data){var cA=data.positions[this.m_indexA].c;var aA=data.positions[this.m_indexA].a;var cB=data.positions[this.m_indexB].c;var aB=data.positions[this.m_indexB].a;var qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);var rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);var rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);var u=this.m_u.Copy(cB).SelfAdd(rB).SelfSub(cA).SelfSub(rA);var length=u.Normalize();var C=length-this.m_maxLength;C=b2Clamp(C,0,b2_maxLinearCorrection);var impulse=-this.m_mass*C;var 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;};_proto61.GetAnchorA=function GetAnchorA(out){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA,out);};_proto61.GetAnchorB=function GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out);};_proto61.GetReactionForce=function GetReactionForce(inv_dt,out){return b2Vec2.MulSV(inv_dt*this.m_impulse,this.m_u,out);};_proto61.GetReactionTorque=function GetReactionTorque(inv_dt){return 0;};_proto61.GetLocalAnchorA=function GetLocalAnchorA(){return this.m_localAnchorA;};_proto61.GetLocalAnchorB=function GetLocalAnchorB(){return this.m_localAnchorB;};_proto61.SetMaxLength=function SetMaxLength(length){this.m_maxLength=length;};_proto61.GetMaxLength=function GetMaxLength(){return this.m_maxLength;};_proto61.GetLimitState=function GetLimitState(){return this.m_state;};_proto61.Dump=function Dump(log){var indexA=this.m_bodyA.m_islandIndex;var 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);};return b2RopeJoint;}(b2Joint);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();var b2WeldJointDef=function(_b2JointDef11){_inheritsLoose(b2WeldJointDef,_b2JointDef11);function b2WeldJointDef(){var _this26;_this26=_b2JointDef11.call(this,exports.b2JointType.e_weldJoint)||this;_this26.localAnchorA=new b2Vec2();_this26.localAnchorB=new b2Vec2();_this26.referenceAngle=0;_this26.frequencyHz=0;_this26.dampingRatio=0;return _this26;}var _proto62=b2WeldJointDef.prototype;_proto62.Initialize=function 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();};return b2WeldJointDef;}(b2JointDef);var b2WeldJoint=function(_b2Joint11){_inheritsLoose(b2WeldJoint,_b2Joint11);function b2WeldJoint(def){var _this27;_this27=_b2Joint11.call(this,def)||this;_this27.m_frequencyHz=0;_this27.m_dampingRatio=0;_this27.m_bias=0;_this27.m_localAnchorA=new b2Vec2();_this27.m_localAnchorB=new b2Vec2();_this27.m_referenceAngle=0;_this27.m_gamma=0;_this27.m_impulse=new b2Vec3(0,0,0);_this27.m_indexA=0;_this27.m_indexB=0;_this27.m_rA=new b2Vec2();_this27.m_rB=new b2Vec2();_this27.m_localCenterA=new b2Vec2();_this27.m_localCenterB=new b2Vec2();_this27.m_invMassA=0;_this27.m_invMassB=0;_this27.m_invIA=0;_this27.m_invIB=0;_this27.m_mass=new b2Mat33();_this27.m_qA=new b2Rot();_this27.m_qB=new b2Rot();_this27.m_lalcA=new b2Vec2();_this27.m_lalcB=new b2Vec2();_this27.m_K=new b2Mat33();_this27.m_frequencyHz=b2Maybe(def.frequencyHz,0);_this27.m_dampingRatio=b2Maybe(def.dampingRatio,0);_this27.m_localAnchorA.Copy(b2Maybe(def.localAnchorA,b2Vec2.ZERO));_this27.m_localAnchorB.Copy(b2Maybe(def.localAnchorB,b2Vec2.ZERO));_this27.m_referenceAngle=b2Maybe(def.referenceAngle,0);_this27.m_impulse.SetZero();return _this27;}var _proto63=b2WeldJoint.prototype;_proto63.InitVelocityConstraints=function 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;var aA=data.positions[this.m_indexA].a;var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var aB=data.positions[this.m_indexB].a;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var 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);var mA=this.m_invMassA,mB=this.m_invMassB;var iA=this.m_invIA,iB=this.m_invIB;var 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);var invM=iA+iB;var m=invM>0?1/invM:0;var C=aB-aA-this.m_referenceAngle;var omega=2*b2_pi*this.m_frequencyHz;var d=2*m*this.m_dampingRatio*omega;var k=m*omega*omega;var 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);var 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;};_proto63.SolveVelocityConstraints=function SolveVelocityConstraints(data){var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var mA=this.m_invMassA,mB=this.m_invMassB;var iA=this.m_invIA,iB=this.m_invIB;if(this.m_frequencyHz>0){var Cdot2=wB-wA;var 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;var 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);var 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;var 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 {var _Cdot=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);var _Cdot2=wB-wA;var impulse=b2Mat33.MulM33XYZ(this.m_mass,_Cdot.x,_Cdot.y,_Cdot2,b2WeldJoint.SolveVelocityConstraints_s_impulse).SelfNeg();this.m_impulse.SelfAdd(impulse);var _P5=b2WeldJoint.SolveVelocityConstraints_s_P.Set(impulse.x,impulse.y);vA.SelfMulSub(mA,_P5);wA-=iA*(b2Vec2.CrossVV(this.m_rA,_P5)+impulse.z);vB.SelfMulAdd(mB,_P5);wB+=iB*(b2Vec2.CrossVV(this.m_rB,_P5)+impulse.z);}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;};_proto63.SolvePositionConstraints=function SolvePositionConstraints(data){var cA=data.positions[this.m_indexA].c;var aA=data.positions[this.m_indexA].a;var cB=data.positions[this.m_indexB].c;var aB=data.positions[this.m_indexB].a;var qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);var mA=this.m_invMassA,mB=this.m_invMassB;var iA=this.m_invIA,iB=this.m_invIB;b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);var rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);var rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);var positionError,angularError;var 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){var 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;var 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 {var _C3=b2Vec2.SubVV(b2Vec2.AddVV(cB,rB,b2Vec2.s_t0),b2Vec2.AddVV(cA,rA,b2Vec2.s_t1),b2WeldJoint.SolvePositionConstraints_s_C1);var C2=aB-aA-this.m_referenceAngle;positionError=_C3.Length();angularError=b2Abs(C2);var impulse=K.Solve33(_C3.x,_C3.y,C2,b2WeldJoint.SolvePositionConstraints_s_impulse).SelfNeg();var _P6=b2WeldJoint.SolvePositionConstraints_s_P.Set(impulse.x,impulse.y);cA.SelfMulSub(mA,_P6);aA-=iA*(b2Vec2.CrossVV(this.m_rA,_P6)+impulse.z);cB.SelfMulAdd(mB,_P6);aB+=iB*(b2Vec2.CrossVV(this.m_rB,_P6)+impulse.z);}data.positions[this.m_indexA].a=aA;data.positions[this.m_indexB].a=aB;return positionError<=b2_linearSlop&&angularError<=b2_angularSlop;};_proto63.GetAnchorA=function GetAnchorA(out){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA,out);};_proto63.GetAnchorB=function GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out);};_proto63.GetReactionForce=function GetReactionForce(inv_dt,out){out.x=inv_dt*this.m_impulse.x;out.y=inv_dt*this.m_impulse.y;return out;};_proto63.GetReactionTorque=function GetReactionTorque(inv_dt){return inv_dt*this.m_impulse.z;};_proto63.GetLocalAnchorA=function GetLocalAnchorA(){return this.m_localAnchorA;};_proto63.GetLocalAnchorB=function GetLocalAnchorB(){return this.m_localAnchorB;};_proto63.GetReferenceAngle=function GetReferenceAngle(){return this.m_referenceAngle;};_proto63.SetFrequency=function SetFrequency(hz){this.m_frequencyHz=hz;};_proto63.GetFrequency=function GetFrequency(){return this.m_frequencyHz;};_proto63.SetDampingRatio=function SetDampingRatio(ratio){this.m_dampingRatio=ratio;};_proto63.GetDampingRatio=function GetDampingRatio(){return this.m_dampingRatio;};_proto63.Dump=function Dump(log){var indexA=this.m_bodyA.m_islandIndex;var 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);};return b2WeldJoint;}(b2Joint);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();var b2WheelJointDef=function(_b2JointDef12){_inheritsLoose(b2WheelJointDef,_b2JointDef12);function b2WheelJointDef(){var _this28;_this28=_b2JointDef12.call(this,exports.b2JointType.e_wheelJoint)||this;_this28.localAnchorA=new b2Vec2(0,0);_this28.localAnchorB=new b2Vec2(0,0);_this28.localAxisA=new b2Vec2(1,0);_this28.enableMotor=false;_this28.maxMotorTorque=0;_this28.motorSpeed=0;_this28.frequencyHz=2;_this28.dampingRatio=0.7;return _this28;}var _proto64=b2WheelJointDef.prototype;_proto64.Initialize=function 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);};return b2WheelJointDef;}(b2JointDef);var b2WheelJoint=function(_b2Joint12){_inheritsLoose(b2WheelJoint,_b2Joint12);function b2WheelJoint(def){var _this29;_this29=_b2Joint12.call(this,def)||this;_this29.m_frequencyHz=0;_this29.m_dampingRatio=0;_this29.m_localAnchorA=new b2Vec2();_this29.m_localAnchorB=new b2Vec2();_this29.m_localXAxisA=new b2Vec2();_this29.m_localYAxisA=new b2Vec2();_this29.m_impulse=0;_this29.m_motorImpulse=0;_this29.m_springImpulse=0;_this29.m_maxMotorTorque=0;_this29.m_motorSpeed=0;_this29.m_enableMotor=false;_this29.m_indexA=0;_this29.m_indexB=0;_this29.m_localCenterA=new b2Vec2();_this29.m_localCenterB=new b2Vec2();_this29.m_invMassA=0;_this29.m_invMassB=0;_this29.m_invIA=0;_this29.m_invIB=0;_this29.m_ax=new b2Vec2();_this29.m_ay=new b2Vec2();_this29.m_sAx=0;_this29.m_sBx=0;_this29.m_sAy=0;_this29.m_sBy=0;_this29.m_mass=0;_this29.m_motorMass=0;_this29.m_springMass=0;_this29.m_bias=0;_this29.m_gamma=0;_this29.m_qA=new b2Rot();_this29.m_qB=new b2Rot();_this29.m_lalcA=new b2Vec2();_this29.m_lalcB=new b2Vec2();_this29.m_rA=new b2Vec2();_this29.m_rB=new b2Vec2();_this29.m_frequencyHz=b2Maybe(def.frequencyHz,2);_this29.m_dampingRatio=b2Maybe(def.dampingRatio,0.7);_this29.m_localAnchorA.Copy(b2Maybe(def.localAnchorA,b2Vec2.ZERO));_this29.m_localAnchorB.Copy(b2Maybe(def.localAnchorB,b2Vec2.ZERO));_this29.m_localXAxisA.Copy(b2Maybe(def.localAxisA,b2Vec2.UNITX));b2Vec2.CrossOneV(_this29.m_localXAxisA,_this29.m_localYAxisA);_this29.m_maxMotorTorque=b2Maybe(def.maxMotorTorque,0);_this29.m_motorSpeed=b2Maybe(def.motorSpeed,0);_this29.m_enableMotor=b2Maybe(def.enableMotor,false);_this29.m_ax.SetZero();_this29.m_ay.SetZero();return _this29;}var _proto65=b2WheelJoint.prototype;_proto65.GetMotorSpeed=function GetMotorSpeed(){return this.m_motorSpeed;};_proto65.GetMaxMotorTorque=function GetMaxMotorTorque(){return this.m_maxMotorTorque;};_proto65.SetSpringFrequencyHz=function SetSpringFrequencyHz(hz){this.m_frequencyHz=hz;};_proto65.GetSpringFrequencyHz=function GetSpringFrequencyHz(){return this.m_frequencyHz;};_proto65.SetSpringDampingRatio=function SetSpringDampingRatio(ratio){this.m_dampingRatio=ratio;};_proto65.GetSpringDampingRatio=function GetSpringDampingRatio(){return this.m_dampingRatio;};_proto65.InitVelocityConstraints=function 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;var mA=this.m_invMassA,mB=this.m_invMassB;var iA=this.m_invIA,iB=this.m_invIB;var cA=data.positions[this.m_indexA].c;var aA=data.positions[this.m_indexA].a;var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var cB=data.positions[this.m_indexB].c;var aB=data.positions[this.m_indexB].a;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);var rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);var rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);var 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);var 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;var C=b2Vec2.DotVV(d,this.m_ax);var omega=2*b2_pi*this.m_frequencyHz;var damp=2*this.m_springMass*this.m_dampingRatio*omega;var k=this.m_springMass*omega*omega;var 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;var 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);var LA=this.m_impulse*this.m_sAy+this.m_springImpulse*this.m_sAx+this.m_motorImpulse;var 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;};_proto65.SolveVelocityConstraints=function SolveVelocityConstraints(data){var mA=this.m_invMassA,mB=this.m_invMassB;var iA=this.m_invIA,iB=this.m_invIB;var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;{var Cdot=b2Vec2.DotVV(this.m_ax,b2Vec2.SubVV(vB,vA,b2Vec2.s_t0))+this.m_sBx*wB-this.m_sAx*wA;var impulse=-this.m_springMass*(Cdot+this.m_bias+this.m_gamma*this.m_springImpulse);this.m_springImpulse+=impulse;var P=b2Vec2.MulSV(impulse,this.m_ax,b2WheelJoint.SolveVelocityConstraints_s_P);var LA=impulse*this.m_sAx;var LB=impulse*this.m_sBx;vA.SelfMulSub(mA,P);wA-=iA*LA;vB.SelfMulAdd(mB,P);wB+=iB*LB;}{var _Cdot3=wB-wA-this.m_motorSpeed;var _impulse=-this.m_motorMass*_Cdot3;var oldImpulse=this.m_motorImpulse;var 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;}{var _Cdot4=b2Vec2.DotVV(this.m_ay,b2Vec2.SubVV(vB,vA,b2Vec2.s_t0))+this.m_sBy*wB-this.m_sAy*wA;var _impulse2=-this.m_mass*_Cdot4;this.m_impulse+=_impulse2;var _P7=b2Vec2.MulSV(_impulse2,this.m_ay,b2WheelJoint.SolveVelocityConstraints_s_P);var _LA3=_impulse2*this.m_sAy;var _LB3=_impulse2*this.m_sBy;vA.SelfMulSub(mA,_P7);wA-=iA*_LA3;vB.SelfMulAdd(mB,_P7);wB+=iB*_LB3;}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;};_proto65.SolvePositionConstraints=function SolvePositionConstraints(data){var cA=data.positions[this.m_indexA].c;var aA=data.positions[this.m_indexA].a;var cB=data.positions[this.m_indexB].c;var aB=data.positions[this.m_indexB].a;var qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);var rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);var rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);var d=b2Vec2.AddVV(b2Vec2.SubVV(cB,cA,b2Vec2.s_t0),b2Vec2.SubVV(rB,rA,b2Vec2.s_t1),b2WheelJoint.SolvePositionConstraints_s_d);var ay=b2Rot.MulRV(qA,this.m_localYAxisA,this.m_ay);var sAy=b2Vec2.CrossVV(b2Vec2.AddVV(d,rA,b2Vec2.s_t0),ay);var sBy=b2Vec2.CrossVV(rB,ay);var C=b2Vec2.DotVV(d,this.m_ay);var 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;var impulse;if(k!==0){impulse=-C/k;}else {impulse=0;}var P=b2Vec2.MulSV(impulse,ay,b2WheelJoint.SolvePositionConstraints_s_P);var LA=impulse*sAy;var 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;};_proto65.GetDefinition=function GetDefinition(def){return def;};_proto65.GetAnchorA=function GetAnchorA(out){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA,out);};_proto65.GetAnchorB=function GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out);};_proto65.GetReactionForce=function 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;};_proto65.GetReactionTorque=function GetReactionTorque(inv_dt){return inv_dt*this.m_motorImpulse;};_proto65.GetLocalAnchorA=function GetLocalAnchorA(){return this.m_localAnchorA;};_proto65.GetLocalAnchorB=function GetLocalAnchorB(){return this.m_localAnchorB;};_proto65.GetLocalAxisA=function GetLocalAxisA(){return this.m_localXAxisA;};_proto65.GetJointTranslation=function GetJointTranslation(){return this.GetPrismaticJointTranslation();};_proto65.GetJointLinearSpeed=function GetJointLinearSpeed(){return this.GetPrismaticJointSpeed();};_proto65.GetJointAngle=function GetJointAngle(){return this.GetRevoluteJointAngle();};_proto65.GetJointAngularSpeed=function GetJointAngularSpeed(){return this.GetRevoluteJointSpeed();};_proto65.GetPrismaticJointTranslation=function GetPrismaticJointTranslation(){var bA=this.m_bodyA;var bB=this.m_bodyB;var pA=bA.GetWorldPoint(this.m_localAnchorA,new b2Vec2());var pB=bB.GetWorldPoint(this.m_localAnchorB,new b2Vec2());var d=b2Vec2.SubVV(pB,pA,new b2Vec2());var axis=bA.GetWorldVector(this.m_localXAxisA,new b2Vec2());var translation=b2Vec2.DotVV(d,axis);return translation;};_proto65.GetPrismaticJointSpeed=function GetPrismaticJointSpeed(){var bA=this.m_bodyA;var bB=this.m_bodyB;b2Vec2.SubVV(this.m_localAnchorA,bA.m_sweep.localCenter,this.m_lalcA);var 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);var rB=b2Rot.MulRV(bB.m_xf.q,this.m_lalcB,this.m_rB);var pA=b2Vec2.AddVV(bA.m_sweep.c,rA,b2Vec2.s_t0);var pB=b2Vec2.AddVV(bB.m_sweep.c,rB,b2Vec2.s_t1);var d=b2Vec2.SubVV(pB,pA,b2Vec2.s_t2);var axis=bA.GetWorldVector(this.m_localXAxisA,new b2Vec2());var vA=bA.m_linearVelocity;var vB=bB.m_linearVelocity;var wA=bA.m_angularVelocity;var wB=bB.m_angularVelocity;var 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;};_proto65.GetRevoluteJointAngle=function GetRevoluteJointAngle(){return this.m_bodyB.m_sweep.a-this.m_bodyA.m_sweep.a;};_proto65.GetRevoluteJointSpeed=function GetRevoluteJointSpeed(){var wA=this.m_bodyA.m_angularVelocity;var wB=this.m_bodyB.m_angularVelocity;return wB-wA;};_proto65.IsMotorEnabled=function IsMotorEnabled(){return this.m_enableMotor;};_proto65.EnableMotor=function EnableMotor(flag){if(flag!==this.m_enableMotor){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_enableMotor=flag;}};_proto65.SetMotorSpeed=function SetMotorSpeed(speed){if(speed!==this.m_motorSpeed){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_motorSpeed=speed;}};_proto65.SetMaxMotorTorque=function SetMaxMotorTorque(force){if(force!==this.m_maxMotorTorque){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_maxMotorTorque=force;}};_proto65.GetMotorTorque=function GetMotorTorque(inv_dt){return inv_dt*this.m_motorImpulse;};_proto65.Dump=function Dump(log){var indexA=this.m_bodyA.m_islandIndex;var 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);};return b2WheelJoint;}(b2Joint);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;}var b2ContactEdge=function(){function b2ContactEdge(contact){this._other=null;this.prev=null;this.next=null;this.contact=contact;}var _proto66=b2ContactEdge.prototype;_proto66.Reset=function Reset(){this._other=null;this.prev=null;this.next=null;};_createClass(b2ContactEdge,[{key:"other",get:function get(){if(this._other===null){throw new Error();}return this._other;},set:function set(value){if(this._other!==null){throw new Error();}this._other=value;}}]);return b2ContactEdge;}();var b2Contact=function(){function b2Contact(){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();}var _proto67=b2Contact.prototype;_proto67.GetManifold=function GetManifold(){return this.m_manifold;};_proto67.GetWorldManifold=function GetWorldManifold(worldManifold){var bodyA=this.m_fixtureA.GetBody();var bodyB=this.m_fixtureB.GetBody();var shapeA=this.GetShapeA();var shapeB=this.GetShapeB();worldManifold.Initialize(this.m_manifold,bodyA.GetTransform(),shapeA.m_radius,bodyB.GetTransform(),shapeB.m_radius);};_proto67.IsTouching=function IsTouching(){return this.m_touchingFlag;};_proto67.SetEnabled=function SetEnabled(flag){this.m_enabledFlag=flag;};_proto67.IsEnabled=function IsEnabled(){return this.m_enabledFlag;};_proto67.GetNext=function GetNext(){return this.m_next;};_proto67.GetFixtureA=function GetFixtureA(){return this.m_fixtureA;};_proto67.GetChildIndexA=function GetChildIndexA(){return this.m_indexA;};_proto67.GetShapeA=function GetShapeA(){return this.m_fixtureA.GetShape();};_proto67.GetFixtureB=function GetFixtureB(){return this.m_fixtureB;};_proto67.GetChildIndexB=function GetChildIndexB(){return this.m_indexB;};_proto67.GetShapeB=function GetShapeB(){return this.m_fixtureB.GetShape();};_proto67.FlagForFiltering=function FlagForFiltering(){this.m_filterFlag=true;};_proto67.SetFriction=function SetFriction(friction){this.m_friction=friction;};_proto67.GetFriction=function GetFriction(){return this.m_friction;};_proto67.ResetFriction=function ResetFriction(){this.m_friction=b2MixFriction(this.m_fixtureA.m_friction,this.m_fixtureB.m_friction);};_proto67.SetRestitution=function SetRestitution(restitution){this.m_restitution=restitution;};_proto67.GetRestitution=function GetRestitution(){return this.m_restitution;};_proto67.ResetRestitution=function ResetRestitution(){this.m_restitution=b2MixRestitution(this.m_fixtureA.m_restitution,this.m_fixtureB.m_restitution);};_proto67.SetTangentSpeed=function SetTangentSpeed(speed){this.m_tangentSpeed=speed;};_proto67.GetTangentSpeed=function GetTangentSpeed(){return this.m_tangentSpeed;};_proto67.Reset=function 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);};_proto67.Update=function Update(listener){var tManifold=this.m_oldManifold;this.m_oldManifold=this.m_manifold;this.m_manifold=tManifold;this.m_enabledFlag=true;var touching=false;var wasTouching=this.m_touchingFlag;var sensorA=this.m_fixtureA.IsSensor();var sensorB=this.m_fixtureB.IsSensor();var sensor=sensorA||sensorB;var bodyA=this.m_fixtureA.GetBody();var bodyB=this.m_fixtureB.GetBody();var xfA=bodyA.GetTransform();var xfB=bodyB.GetTransform();if(sensor){var shapeA=this.GetShapeA();var 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(var i=0;i<this.m_manifold.pointCount;++i){var mp2=this.m_manifold.points[i];mp2.normalImpulse=0;mp2.tangentImpulse=0;var id2=mp2.id;for(var j=0;j<this.m_oldManifold.pointCount;++j){var 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);}};_proto67.ComputeTOI=function ComputeTOI(sweepA,sweepB){var 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;var output=b2Contact.ComputeTOI_s_output;b2TimeOfImpact(output,input);return output.t;};return b2Contact;}();b2Contact.ComputeTOI_s_input=new b2TOIInput();b2Contact.ComputeTOI_s_output=new b2TOIOutput();var b2CircleContact=function(_b2Contact){_inheritsLoose(b2CircleContact,_b2Contact);function b2CircleContact(){return _b2Contact.apply(this,arguments)||this;}b2CircleContact.Create=function Create(){return new b2CircleContact();};b2CircleContact.Destroy=function Destroy(contact){};var _proto68=b2CircleContact.prototype;_proto68.Evaluate=function Evaluate(manifold,xfA,xfB){b2CollideCircles(manifold,this.GetShapeA(),xfA,this.GetShapeB(),xfB);};return b2CircleContact;}(b2Contact);var b2PolygonContact=function(_b2Contact2){_inheritsLoose(b2PolygonContact,_b2Contact2);function b2PolygonContact(){return _b2Contact2.apply(this,arguments)||this;}b2PolygonContact.Create=function Create(){return new b2PolygonContact();};b2PolygonContact.Destroy=function Destroy(contact){};var _proto69=b2PolygonContact.prototype;_proto69.Evaluate=function Evaluate(manifold,xfA,xfB){b2CollidePolygons(manifold,this.GetShapeA(),xfA,this.GetShapeB(),xfB);};return b2PolygonContact;}(b2Contact);var b2PolygonAndCircleContact=function(_b2Contact3){_inheritsLoose(b2PolygonAndCircleContact,_b2Contact3);function b2PolygonAndCircleContact(){return _b2Contact3.apply(this,arguments)||this;}b2PolygonAndCircleContact.Create=function Create(){return new b2PolygonAndCircleContact();};b2PolygonAndCircleContact.Destroy=function Destroy(contact){};var _proto70=b2PolygonAndCircleContact.prototype;_proto70.Evaluate=function Evaluate(manifold,xfA,xfB){b2CollidePolygonAndCircle(manifold,this.GetShapeA(),xfA,this.GetShapeB(),xfB);};return b2PolygonAndCircleContact;}(b2Contact);var b2EdgeAndCircleContact=function(_b2Contact4){_inheritsLoose(b2EdgeAndCircleContact,_b2Contact4);function b2EdgeAndCircleContact(){return _b2Contact4.apply(this,arguments)||this;}b2EdgeAndCircleContact.Create=function Create(){return new b2EdgeAndCircleContact();};b2EdgeAndCircleContact.Destroy=function Destroy(contact){};var _proto71=b2EdgeAndCircleContact.prototype;_proto71.Evaluate=function Evaluate(manifold,xfA,xfB){b2CollideEdgeAndCircle(manifold,this.GetShapeA(),xfA,this.GetShapeB(),xfB);};return b2EdgeAndCircleContact;}(b2Contact);var b2EdgeAndPolygonContact=function(_b2Contact5){_inheritsLoose(b2EdgeAndPolygonContact,_b2Contact5);function b2EdgeAndPolygonContact(){return _b2Contact5.apply(this,arguments)||this;}b2EdgeAndPolygonContact.Create=function Create(){return new b2EdgeAndPolygonContact();};b2EdgeAndPolygonContact.Destroy=function Destroy(contact){};var _proto72=b2EdgeAndPolygonContact.prototype;_proto72.Evaluate=function Evaluate(manifold,xfA,xfB){b2CollideEdgeAndPolygon(manifold,this.GetShapeA(),xfA,this.GetShapeB(),xfB);};return b2EdgeAndPolygonContact;}(b2Contact);var b2ChainAndCircleContact=function(_b2Contact6){_inheritsLoose(b2ChainAndCircleContact,_b2Contact6);function b2ChainAndCircleContact(){return _b2Contact6.apply(this,arguments)||this;}b2ChainAndCircleContact.Create=function Create(){return new b2ChainAndCircleContact();};b2ChainAndCircleContact.Destroy=function Destroy(contact){};var _proto73=b2ChainAndCircleContact.prototype;_proto73.Evaluate=function Evaluate(manifold,xfA,xfB){var edge=b2ChainAndCircleContact.Evaluate_s_edge;this.GetShapeA().GetChildEdge(edge,this.m_indexA);b2CollideEdgeAndCircle(manifold,edge,xfA,this.GetShapeB(),xfB);};return b2ChainAndCircleContact;}(b2Contact);b2ChainAndCircleContact.Evaluate_s_edge=new b2EdgeShape();var b2ChainAndPolygonContact=function(_b2Contact7){_inheritsLoose(b2ChainAndPolygonContact,_b2Contact7);function b2ChainAndPolygonContact(){return _b2Contact7.apply(this,arguments)||this;}b2ChainAndPolygonContact.Create=function Create(){return new b2ChainAndPolygonContact();};b2ChainAndPolygonContact.Destroy=function Destroy(contact){};var _proto74=b2ChainAndPolygonContact.prototype;_proto74.Evaluate=function Evaluate(manifold,xfA,xfB){var edge=b2ChainAndPolygonContact.Evaluate_s_edge;this.GetShapeA().GetChildEdge(edge,this.m_indexA);b2CollideEdgeAndPolygon(manifold,edge,xfA,this.GetShapeB(),xfB);};return b2ChainAndPolygonContact;}(b2Contact);b2ChainAndPolygonContact.Evaluate_s_edge=new b2EdgeShape();var b2ContactRegister=function b2ContactRegister(){this.pool=[];this.createFcn=null;this.destroyFcn=null;this.primary=false;};var b2ContactFactory=function(){function b2ContactFactory(){this.m_registers=[];this.InitializeRegisters();}var _proto75=b2ContactFactory.prototype;_proto75.AddType=function AddType(createFcn,destroyFcn,typeA,typeB){var 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;}};_proto75.InitializeRegisters=function InitializeRegisters(){for(var i=0;i<exports.b2ShapeType.e_shapeTypeCount;i++){this.m_registers[i]=[];for(var 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);};_proto75.Create=function Create(fixtureA,indexA,fixtureB,indexB){var typeA=fixtureA.GetType();var typeB=fixtureB.GetType();var reg=this.m_registers[typeA][typeB];if(reg.createFcn){var c=reg.createFcn();if(reg.primary){c.Reset(fixtureA,indexA,fixtureB,indexB);}else {c.Reset(fixtureB,indexB,fixtureA,indexA);}return c;}else {return null;}};_proto75.Destroy=function Destroy(contact){var typeA=contact.m_fixtureA.GetType();var typeB=contact.m_fixtureB.GetType();var reg=this.m_registers[typeA][typeB];if(reg.destroyFcn){reg.destroyFcn(contact);}};return b2ContactFactory;}();var b2DestructionListener=function(){function b2DestructionListener(){}var _proto76=b2DestructionListener.prototype;_proto76.SayGoodbyeJoint=function SayGoodbyeJoint(joint){};_proto76.SayGoodbyeFixture=function SayGoodbyeFixture(fixture){};_proto76.SayGoodbyeParticleGroup=function SayGoodbyeParticleGroup(group){};_proto76.SayGoodbyeParticle=function SayGoodbyeParticle(system,index){};return b2DestructionListener;}();var b2ContactFilter=function(){function b2ContactFilter(){}var _proto77=b2ContactFilter.prototype;_proto77.ShouldCollide=function ShouldCollide(fixtureA,fixtureB){var bodyA=fixtureA.GetBody();var bodyB=fixtureB.GetBody();if(bodyB.GetType()===exports.b2BodyType.b2_staticBody&&bodyA.GetType()===exports.b2BodyType.b2_staticBody){return false;}if(!bodyB.ShouldCollideConnected(bodyA)){return false;}var filter1=fixtureA.GetFilterData();var filter2=fixtureB.GetFilterData();if(filter1.groupIndex===filter2.groupIndex&&filter1.groupIndex!==0){return filter1.groupIndex>0;}var collide=(filter1.maskBits&filter2.categoryBits)!==0&&(filter1.categoryBits&filter2.maskBits)!==0;return collide;};_proto77.ShouldCollideFixtureParticle=function ShouldCollideFixtureParticle(fixture,system,index){return true;};_proto77.ShouldCollideParticleParticle=function ShouldCollideParticleParticle(system,indexA,indexB){return true;};return b2ContactFilter;}();b2ContactFilter.b2_defaultFilter=new b2ContactFilter();var b2ContactImpulse=function b2ContactImpulse(){this.normalImpulses=b2MakeNumberArray(b2_maxManifoldPoints);this.tangentImpulses=b2MakeNumberArray(b2_maxManifoldPoints);this.count=0;};var b2ContactListener=function(){function b2ContactListener(){}var _proto78=b2ContactListener.prototype;_proto78.BeginContact=function BeginContact(contact){};_proto78.EndContact=function EndContact(contact){};_proto78.BeginContactFixtureParticle=function BeginContactFixtureParticle(system,contact){};_proto78.EndContactFixtureParticle=function EndContactFixtureParticle(system,contact){};_proto78.BeginContactParticleParticle=function BeginContactParticleParticle(system,contact){};_proto78.EndContactParticleParticle=function EndContactParticleParticle(system,contact){};_proto78.PreSolve=function PreSolve(contact,oldManifold){};_proto78.PostSolve=function PostSolve(contact,impulse){};return b2ContactListener;}();b2ContactListener.b2_defaultListener=new b2ContactListener();var b2QueryCallback=function(){function b2QueryCallback(){}var _proto79=b2QueryCallback.prototype;_proto79.ReportFixture=function ReportFixture(fixture){return true;};_proto79.ReportParticle=function ReportParticle(system,index){return false;};_proto79.ShouldQueryParticleSystem=function ShouldQueryParticleSystem(system){return true;};return b2QueryCallback;}();var b2RayCastCallback=function(){function b2RayCastCallback(){}var _proto80=b2RayCastCallback.prototype;_proto80.ReportFixture=function ReportFixture(fixture,point,normal,fraction){return fraction;};_proto80.ReportParticle=function ReportParticle(system,index,point,normal,fraction){return 0;};_proto80.ShouldQueryParticleSystem=function ShouldQueryParticleSystem(system){return true;};return b2RayCastCallback;}();var b2ContactManager=function(){function b2ContactManager(){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();}var _proto81=b2ContactManager.prototype;_proto81.AddPair=function AddPair(proxyA,proxyB){var fixtureA=proxyA.fixture;var fixtureB=proxyB.fixture;var indexA=proxyA.childIndex;var indexB=proxyB.childIndex;var bodyA=fixtureA.GetBody();var bodyB=fixtureB.GetBody();if(bodyA===bodyB){return;}var edge=bodyB.GetContactList();while(edge){if(edge.other===bodyA){var fA=edge.contact.GetFixtureA();var fB=edge.contact.GetFixtureB();var iA=edge.contact.GetChildIndexA();var 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;}var 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;};_proto81.FindNewContacts=function FindNewContacts(){var _this30=this;this.m_broadPhase.UpdatePairs(function(proxyA,proxyB){_this30.AddPair(proxyA,proxyB);});};_proto81.Destroy=function Destroy(c){var fixtureA=c.GetFixtureA();var fixtureB=c.GetFixtureB();var bodyA=fixtureA.GetBody();var 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;};_proto81.Collide=function Collide(){var c=this.m_contactList;while(c){var fixtureA=c.GetFixtureA();var fixtureB=c.GetFixtureB();var indexA=c.GetChildIndexA();var indexB=c.GetChildIndexB();var bodyA=fixtureA.GetBody();var bodyB=fixtureB.GetBody();if(c.m_filterFlag){if(this.m_contactFilter&&!this.m_contactFilter.ShouldCollide(fixtureA,fixtureB)){var cNuke=c;c=cNuke.m_next;this.Destroy(cNuke);continue;}c.m_filterFlag=false;}var activeA=bodyA.IsAwake()&&bodyA.m_type!==exports.b2BodyType.b2_staticBody;var activeB=bodyB.IsAwake()&&bodyB.m_type!==exports.b2BodyType.b2_staticBody;if(!activeA&&!activeB){c=c.m_next;continue;}var treeNodeA=fixtureA.m_proxies[indexA].treeNode;var treeNodeB=fixtureB.m_proxies[indexB].treeNode;var overlap=b2TestOverlapAABB(treeNodeA.aabb,treeNodeB.aabb);if(!overlap){var _cNuke=c;c=_cNuke.m_next;this.Destroy(_cNuke);continue;}c.Update(this.m_contactListener);c=c.m_next;}};return b2ContactManager;}();var b2Profile=function(){function b2Profile(){this.step=0;this.collide=0;this.solve=0;this.solveInit=0;this.solveVelocity=0;this.solvePosition=0;this.broadphase=0;this.solveTOI=0;}var _proto82=b2Profile.prototype;_proto82.Reset=function 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;};return b2Profile;}();var b2TimeStep=function(){function b2TimeStep(){this.dt=0;this.inv_dt=0;this.dtRatio=0;this.velocityIterations=0;this.positionIterations=0;this.particleIterations=0;this.warmStarting=false;}var _proto83=b2TimeStep.prototype;_proto83.Copy=function 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;};return b2TimeStep;}();var b2Position=function(){function b2Position(){this.c=new b2Vec2();this.a=0;}b2Position.MakeArray=function MakeArray(length){return b2MakeArray(length,function(i){return new b2Position();});};return b2Position;}();var b2Velocity=function(){function b2Velocity(){this.v=new b2Vec2();this.w=0;}b2Velocity.MakeArray=function MakeArray(length){return b2MakeArray(length,function(i){return new b2Velocity();});};return b2Velocity;}();var b2SolverData=function b2SolverData(){this.step=new b2TimeStep();};var g_blockSolve=false;var b2VelocityConstraintPoint=function(){function b2VelocityConstraintPoint(){this.rA=new b2Vec2();this.rB=new b2Vec2();this.normalImpulse=0;this.tangentImpulse=0;this.normalMass=0;this.tangentMass=0;this.velocityBias=0;}b2VelocityConstraintPoint.MakeArray=function MakeArray(length){return b2MakeArray(length,function(i){return new b2VelocityConstraintPoint();});};return b2VelocityConstraintPoint;}();var b2ContactVelocityConstraint=function(){function b2ContactVelocityConstraint(){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;}b2ContactVelocityConstraint.MakeArray=function MakeArray(length){return b2MakeArray(length,function(i){return new b2ContactVelocityConstraint();});};return b2ContactVelocityConstraint;}();var b2ContactPositionConstraint=function(){function b2ContactPositionConstraint(){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;}b2ContactPositionConstraint.MakeArray=function MakeArray(length){return b2MakeArray(length,function(i){return new b2ContactPositionConstraint();});};return b2ContactPositionConstraint;}();var b2ContactSolverDef=function b2ContactSolverDef(){this.step=new b2TimeStep();this.count=0;};var b2PositionSolverManifold=function(){function b2PositionSolverManifold(){this.normal=new b2Vec2();this.point=new b2Vec2();this.separation=0;}var _proto84=b2PositionSolverManifold.prototype;_proto84.Initialize=function Initialize(pc,xfA,xfB,index){var pointA=b2PositionSolverManifold.Initialize_s_pointA;var pointB=b2PositionSolverManifold.Initialize_s_pointB;var planePoint=b2PositionSolverManifold.Initialize_s_planePoint;var 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;}}};return b2PositionSolverManifold;}();b2PositionSolverManifold.Initialize_s_pointA=new b2Vec2();b2PositionSolverManifold.Initialize_s_pointB=new b2Vec2();b2PositionSolverManifold.Initialize_s_planePoint=new b2Vec2();b2PositionSolverManifold.Initialize_s_clipPoint=new b2Vec2();var b2ContactSolver=function(){function b2ContactSolver(){this.m_step=new b2TimeStep();this.m_positionConstraints=b2ContactPositionConstraint.MakeArray(1024);this.m_velocityConstraints=b2ContactVelocityConstraint.MakeArray(1024);this.m_count=0;}var _proto85=b2ContactSolver.prototype;_proto85.Initialize=function Initialize(def){this.m_step.Copy(def.step);this.m_count=def.count;if(this.m_positionConstraints.length<this.m_count){var 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){var _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(var i=0;i<this.m_count;++i){var contact=this.m_contacts[i];var fixtureA=contact.m_fixtureA;var fixtureB=contact.m_fixtureB;var shapeA=fixtureA.GetShape();var shapeB=fixtureB.GetShape();var radiusA=shapeA.m_radius;var radiusB=shapeB.m_radius;var bodyA=fixtureA.GetBody();var bodyB=fixtureB.GetBody();var manifold=contact.GetManifold();var pointCount=manifold.pointCount;var 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();var 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(var j=0;j<pointCount;++j){var cp=manifold.points[j];var 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;};_proto85.InitializeVelocityConstraints=function InitializeVelocityConstraints(){var xfA=b2ContactSolver.InitializeVelocityConstraints_s_xfA;var xfB=b2ContactSolver.InitializeVelocityConstraints_s_xfB;var worldManifold=b2ContactSolver.InitializeVelocityConstraints_s_worldManifold;var k_maxConditionNumber=1000;for(var i=0;i<this.m_count;++i){var vc=this.m_velocityConstraints[i];var pc=this.m_positionConstraints[i];var radiusA=pc.radiusA;var radiusB=pc.radiusB;var manifold=this.m_contacts[vc.contactIndex].GetManifold();var indexA=vc.indexA;var indexB=vc.indexB;var mA=vc.invMassA;var mB=vc.invMassB;var iA=vc.invIA;var iB=vc.invIB;var localCenterA=pc.localCenterA;var localCenterB=pc.localCenterB;var cA=this.m_positions[indexA].c;var aA=this.m_positions[indexA].a;var vA=this.m_velocities[indexA].v;var wA=this.m_velocities[indexA].w;var cB=this.m_positions[indexB].c;var aB=this.m_positions[indexB].a;var vB=this.m_velocities[indexB].v;var 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);var pointCount=vc.pointCount;for(var j=0;j<pointCount;++j){var vcp=vc.points[j];b2Vec2.SubVV(worldManifold.points[j],cA,vcp.rA);b2Vec2.SubVV(worldManifold.points[j],cB,vcp.rB);var rnA=b2Vec2.CrossVV(vcp.rA,vc.normal);var rnB=b2Vec2.CrossVV(vcp.rB,vc.normal);var kNormal=mA+mB+iA*rnA*rnA+iB*rnB*rnB;vcp.normalMass=kNormal>0?1/kNormal:0;var tangent=vc.tangent;var rtA=b2Vec2.CrossVV(vcp.rA,tangent);var rtB=b2Vec2.CrossVV(vcp.rB,tangent);var kTangent=mA+mB+iA*rtA*rtA+iB*rtB*rtB;vcp.tangentMass=kTangent>0?1/kTangent:0;vcp.velocityBias=0;var 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){var vcp1=vc.points[0];var vcp2=vc.points[1];var rn1A=b2Vec2.CrossVV(vcp1.rA,vc.normal);var rn1B=b2Vec2.CrossVV(vcp1.rB,vc.normal);var rn2A=b2Vec2.CrossVV(vcp2.rA,vc.normal);var rn2B=b2Vec2.CrossVV(vcp2.rB,vc.normal);var k11=mA+mB+iA*rn1A*rn1A+iB*rn1B*rn1B;var k22=mA+mB+iA*rn2A*rn2A+iB*rn2B*rn2B;var 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;}}}};_proto85.WarmStart=function WarmStart(){var P=b2ContactSolver.WarmStart_s_P;for(var i=0;i<this.m_count;++i){var vc=this.m_velocityConstraints[i];var indexA=vc.indexA;var indexB=vc.indexB;var mA=vc.invMassA;var iA=vc.invIA;var mB=vc.invMassB;var iB=vc.invIB;var pointCount=vc.pointCount;var vA=this.m_velocities[indexA].v;var wA=this.m_velocities[indexA].w;var vB=this.m_velocities[indexB].v;var wB=this.m_velocities[indexB].w;var normal=vc.normal;var tangent=vc.tangent;for(var j=0;j<pointCount;++j){var 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;}};_proto85.SolveVelocityConstraints=function SolveVelocityConstraints(){var dv=b2ContactSolver.SolveVelocityConstraints_s_dv;var dv1=b2ContactSolver.SolveVelocityConstraints_s_dv1;var dv2=b2ContactSolver.SolveVelocityConstraints_s_dv2;var P=b2ContactSolver.SolveVelocityConstraints_s_P;var a=b2ContactSolver.SolveVelocityConstraints_s_a;var b=b2ContactSolver.SolveVelocityConstraints_s_b;var x=b2ContactSolver.SolveVelocityConstraints_s_x;var d=b2ContactSolver.SolveVelocityConstraints_s_d;var P1=b2ContactSolver.SolveVelocityConstraints_s_P1;var P2=b2ContactSolver.SolveVelocityConstraints_s_P2;var P1P2=b2ContactSolver.SolveVelocityConstraints_s_P1P2;for(var i=0;i<this.m_count;++i){var vc=this.m_velocityConstraints[i];var indexA=vc.indexA;var indexB=vc.indexB;var mA=vc.invMassA;var iA=vc.invIA;var mB=vc.invMassB;var iB=vc.invIB;var pointCount=vc.pointCount;var vA=this.m_velocities[indexA].v;var wA=this.m_velocities[indexA].w;var vB=this.m_velocities[indexB].v;var wB=this.m_velocities[indexB].w;var normal=vc.normal;var tangent=vc.tangent;var friction=vc.friction;for(var j=0;j<pointCount;++j){var 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);var vt=b2Vec2.DotVV(dv,tangent)-vc.tangentSpeed;var lambda=vcp.tangentMass*-vt;var maxFriction=friction*vcp.normalImpulse;var 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(var _j3=0;_j3<pointCount;++_j3){var _vcp=vc.points[_j3];b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB,wB,_vcp.rB,b2Vec2.s_t0),b2Vec2.AddVCrossSV(vA,wA,_vcp.rA,b2Vec2.s_t1),dv);var vn=b2Vec2.DotVV(dv,normal);var _lambda=-_vcp.normalMass*(vn-_vcp.velocityBias);var _newImpulse2=b2Max(_vcp.normalImpulse+_lambda,0);_lambda=_newImpulse2-_vcp.normalImpulse;_vcp.normalImpulse=_newImpulse2;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 {var cp1=vc.points[0];var 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);var vn1=b2Vec2.DotVV(dv1,normal);var 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;}};_proto85.StoreImpulses=function StoreImpulses(){for(var i=0;i<this.m_count;++i){var vc=this.m_velocityConstraints[i];var manifold=this.m_contacts[vc.contactIndex].GetManifold();for(var j=0;j<vc.pointCount;++j){manifold.points[j].normalImpulse=vc.points[j].normalImpulse;manifold.points[j].tangentImpulse=vc.points[j].tangentImpulse;}}};_proto85.SolvePositionConstraints=function SolvePositionConstraints(){var xfA=b2ContactSolver.SolvePositionConstraints_s_xfA;var xfB=b2ContactSolver.SolvePositionConstraints_s_xfB;var psm=b2ContactSolver.SolvePositionConstraints_s_psm;var rA=b2ContactSolver.SolvePositionConstraints_s_rA;var rB=b2ContactSolver.SolvePositionConstraints_s_rB;var P=b2ContactSolver.SolvePositionConstraints_s_P;var minSeparation=0;for(var i=0;i<this.m_count;++i){var pc=this.m_positionConstraints[i];var indexA=pc.indexA;var indexB=pc.indexB;var localCenterA=pc.localCenterA;var mA=pc.invMassA;var iA=pc.invIA;var localCenterB=pc.localCenterB;var mB=pc.invMassB;var iB=pc.invIB;var pointCount=pc.pointCount;var cA=this.m_positions[indexA].c;var aA=this.m_positions[indexA].a;var cB=this.m_positions[indexB].c;var aB=this.m_positions[indexB].a;for(var 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);var normal=psm.normal;var point=psm.point;var separation=psm.separation;b2Vec2.SubVV(point,cA,rA);b2Vec2.SubVV(point,cB,rB);minSeparation=b2Min(minSeparation,separation);var C=b2Clamp(b2_baumgarte*(separation+b2_linearSlop),-b2_maxLinearCorrection,0);var rnA=b2Vec2.CrossVV(rA,normal);var rnB=b2Vec2.CrossVV(rB,normal);var K=mA+mB+iA*rnA*rnA+iB*rnB*rnB;var 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;};_proto85.SolveTOIPositionConstraints=function SolveTOIPositionConstraints(toiIndexA,toiIndexB){var xfA=b2ContactSolver.SolveTOIPositionConstraints_s_xfA;var xfB=b2ContactSolver.SolveTOIPositionConstraints_s_xfB;var psm=b2ContactSolver.SolveTOIPositionConstraints_s_psm;var rA=b2ContactSolver.SolveTOIPositionConstraints_s_rA;var rB=b2ContactSolver.SolveTOIPositionConstraints_s_rB;var P=b2ContactSolver.SolveTOIPositionConstraints_s_P;var minSeparation=0;for(var i=0;i<this.m_count;++i){var pc=this.m_positionConstraints[i];var indexA=pc.indexA;var indexB=pc.indexB;var localCenterA=pc.localCenterA;var localCenterB=pc.localCenterB;var pointCount=pc.pointCount;var mA=0;var iA=0;if(indexA===toiIndexA||indexA===toiIndexB){mA=pc.invMassA;iA=pc.invIA;}var mB=0;var iB=0;if(indexB===toiIndexA||indexB===toiIndexB){mB=pc.invMassB;iB=pc.invIB;}var cA=this.m_positions[indexA].c;var aA=this.m_positions[indexA].a;var cB=this.m_positions[indexB].c;var aB=this.m_positions[indexB].a;for(var 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);var normal=psm.normal;var point=psm.point;var separation=psm.separation;b2Vec2.SubVV(point,cA,rA);b2Vec2.SubVV(point,cB,rB);minSeparation=b2Min(minSeparation,separation);var C=b2Clamp(b2_toiBaumgarte*(separation+b2_linearSlop),-b2_maxLinearCorrection,0);var rnA=b2Vec2.CrossVV(rA,normal);var rnB=b2Vec2.CrossVV(rB,normal);var K=mA+mB+iA*rnA*rnA+iB*rnB*rnB;var 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;};return b2ContactSolver;}();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();var b2Island=function(){function b2Island(){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;}var _proto86=b2Island.prototype;_proto86.Initialize=function 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){var 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){var _new_length2=b2Max(this.m_velocities.length*2,bodyCapacity);while(this.m_velocities.length<_new_length2){this.m_velocities[this.m_velocities.length]=new b2Velocity();}}};_proto86.Clear=function Clear(){this.m_bodyCount=0;this.m_contactCount=0;this.m_jointCount=0;};_proto86.AddBody=function AddBody(body){body.m_islandIndex=this.m_bodyCount;this.m_bodies[this.m_bodyCount++]=body;};_proto86.AddContact=function AddContact(contact){this.m_contacts[this.m_contactCount++]=contact;};_proto86.AddJoint=function AddJoint(joint){this.m_joints[this.m_jointCount++]=joint;};_proto86.Solve=function Solve(profile,step,gravity,allowSleep){var timer=b2Island.s_timer.Reset();var h=step.dt;for(var i=0;i<this.m_bodyCount;++i){var b=this.m_bodies[i];this.m_positions[i].c.Copy(b.m_sweep.c);var a=b.m_sweep.a;var v=this.m_velocities[i].v.Copy(b.m_linearVelocity);var 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();var solverData=b2Island.s_solverData;solverData.step.Copy(step);solverData.positions=this.m_positions;solverData.velocities=this.m_velocities;var 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;var contactSolver=b2Island.s_contactSolver.Initialize(contactSolverDef);contactSolver.InitializeVelocityConstraints();if(step.warmStarting){contactSolver.WarmStart();}for(var _i15=0;_i15<this.m_jointCount;++_i15){this.m_joints[_i15].InitVelocityConstraints(solverData);}profile.solveInit=timer.GetMilliseconds();timer.Reset();for(var _i16=0;_i16<step.velocityIterations;++_i16){for(var j=0;j<this.m_jointCount;++j){this.m_joints[j].SolveVelocityConstraints(solverData);}contactSolver.SolveVelocityConstraints();}contactSolver.StoreImpulses();profile.solveVelocity=timer.GetMilliseconds();for(var _i17=0;_i17<this.m_bodyCount;++_i17){var c=this.m_positions[_i17].c;var _a=this.m_positions[_i17].a;var _v3=this.m_velocities[_i17].v;var _w=this.m_velocities[_i17].w;var translation=b2Vec2.MulSV(h,_v3,b2Island.s_translation);if(b2Vec2.DotVV(translation,translation)>b2_maxTranslationSquared){var ratio=b2_maxTranslation/translation.Length();_v3.SelfMul(ratio);}var rotation=h*_w;if(rotation*rotation>b2_maxRotationSquared){var _ratio=b2_maxRotation/b2Abs(rotation);_w*=_ratio;}c.x+=h*_v3.x;c.y+=h*_v3.y;_a+=h*_w;this.m_positions[_i17].a=_a;this.m_velocities[_i17].w=_w;}timer.Reset();var positionSolved=false;for(var _i18=0;_i18<step.positionIterations;++_i18){var contactsOkay=contactSolver.SolvePositionConstraints();var jointsOkay=true;for(var _j4=0;_j4<this.m_jointCount;++_j4){var jointOkay=this.m_joints[_j4].SolvePositionConstraints(solverData);jointsOkay=jointsOkay&&jointOkay;}if(contactsOkay&&jointsOkay){positionSolved=true;break;}}for(var _i19=0;_i19<this.m_bodyCount;++_i19){var body=this.m_bodies[_i19];body.m_sweep.c.Copy(this.m_positions[_i19].c);body.m_sweep.a=this.m_positions[_i19].a;body.m_linearVelocity.Copy(this.m_velocities[_i19].v);body.m_angularVelocity=this.m_velocities[_i19].w;body.SynchronizeTransform();}profile.solvePosition=timer.GetMilliseconds();this.Report(contactSolver.m_velocityConstraints);if(allowSleep){var minSleepTime=b2_maxFloat;var linTolSqr=b2_linearSleepTolerance*b2_linearSleepTolerance;var angTolSqr=b2_angularSleepTolerance*b2_angularSleepTolerance;for(var _i20=0;_i20<this.m_bodyCount;++_i20){var _b=this.m_bodies[_i20];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(var _i21=0;_i21<this.m_bodyCount;++_i21){var _b2=this.m_bodies[_i21];_b2.SetAwake(false);}}}};_proto86.SolveTOI=function SolveTOI(subStep,toiIndexA,toiIndexB){for(var i=0;i<this.m_bodyCount;++i){var 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;}var 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;var contactSolver=b2Island.s_contactSolver.Initialize(contactSolverDef);for(var _i22=0;_i22<subStep.positionIterations;++_i22){var 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(var _i23=0;_i23<subStep.velocityIterations;++_i23){contactSolver.SolveVelocityConstraints();}var h=subStep.dt;for(var _i24=0;_i24<this.m_bodyCount;++_i24){var c=this.m_positions[_i24].c;var a=this.m_positions[_i24].a;var v=this.m_velocities[_i24].v;var w=this.m_velocities[_i24].w;var translation=b2Vec2.MulSV(h,v,b2Island.s_translation);if(b2Vec2.DotVV(translation,translation)>b2_maxTranslationSquared){var ratio=b2_maxTranslation/translation.Length();v.SelfMul(ratio);}var rotation=h*w;if(rotation*rotation>b2_maxRotationSquared){var _ratio2=b2_maxRotation/b2Abs(rotation);w*=_ratio2;}c.SelfMulAdd(h,v);a+=h*w;this.m_positions[_i24].a=a;this.m_velocities[_i24].w=w;var body=this.m_bodies[_i24];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);};_proto86.Report=function Report(constraints){if(this.m_listener===null){return;}for(var i=0;i<this.m_contactCount;++i){var c=this.m_contacts[i];if(!c){continue;}var vc=constraints[i];var impulse=b2Island.s_impulse;impulse.count=vc.pointCount;for(var 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);}};return b2Island;}();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={}));var b2ParticleDef=function b2ParticleDef(){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){var B2_MAX_RECOMMENDED_PARTICLE_ITERATIONS=8;var B2_RADIUS_THRESHOLD=0.01;var iterations=Math.ceil(Math.sqrt(gravity/(B2_RADIUS_THRESHOLD*radius))*timeStep);return b2Clamp(iterations,1,B2_MAX_RECOMMENDED_PARTICLE_ITERATIONS);}var b2ParticleHandle=function(){function b2ParticleHandle(){this.m_index=b2_invalidParticleIndex;}var _proto87=b2ParticleHandle.prototype;_proto87.GetIndex=function GetIndex(){return this.m_index;};_proto87.SetIndex=function SetIndex(index){this.m_index=index;};return b2ParticleHandle;}();(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={}));var b2ParticleGroupDef=function b2ParticleGroupDef(){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;};var b2ParticleGroup=function(){function b2ParticleGroup(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;}var _proto88=b2ParticleGroup.prototype;_proto88.GetNext=function GetNext(){return this.m_next;};_proto88.GetParticleSystem=function GetParticleSystem(){return this.m_system;};_proto88.GetParticleCount=function GetParticleCount(){return this.m_lastIndex-this.m_firstIndex;};_proto88.GetBufferIndex=function GetBufferIndex(){return this.m_firstIndex;};_proto88.ContainsParticle=function ContainsParticle(index){return this.m_firstIndex<=index&&index<this.m_lastIndex;};_proto88.GetAllParticleFlags=function GetAllParticleFlags(){if(!this.m_system.m_flagsBuffer.data){throw new Error();}var flags=0;for(var i=this.m_firstIndex;i<this.m_lastIndex;i++){flags|=this.m_system.m_flagsBuffer.data[i];}return flags;};_proto88.GetGroupFlags=function GetGroupFlags(){return this.m_groupFlags;};_proto88.SetGroupFlags=function SetGroupFlags(flags){flags|=this.m_groupFlags&exports.b2ParticleGroupFlag.b2_particleGroupInternalMask;this.m_system.SetGroupFlags(this,flags);};_proto88.GetMass=function GetMass(){this.UpdateStatistics();return this.m_mass;};_proto88.GetInertia=function GetInertia(){this.UpdateStatistics();return this.m_inertia;};_proto88.GetCenter=function GetCenter(){this.UpdateStatistics();return this.m_center;};_proto88.GetLinearVelocity=function GetLinearVelocity(){this.UpdateStatistics();return this.m_linearVelocity;};_proto88.GetAngularVelocity=function GetAngularVelocity(){this.UpdateStatistics();return this.m_angularVelocity;};_proto88.GetTransform=function GetTransform(){return this.m_transform;};_proto88.GetPosition=function GetPosition(){return this.m_transform.p;};_proto88.GetAngle=function GetAngle(){return this.m_transform.q.GetAngle();};_proto88.GetLinearVelocityFromWorldPoint=function GetLinearVelocityFromWorldPoint(worldPoint,out){var 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);};_proto88.GetUserData=function GetUserData(){return this.m_userData;};_proto88.SetUserData=function SetUserData(data){this.m_userData=data;};_proto88.ApplyForce=function ApplyForce(force){this.m_system.ApplyForce(this.m_firstIndex,this.m_lastIndex,force);};_proto88.ApplyLinearImpulse=function ApplyLinearImpulse(impulse){this.m_system.ApplyLinearImpulse(this.m_firstIndex,this.m_lastIndex,impulse);};_proto88.DestroyParticles=function DestroyParticles(callDestructionListener){if(this.m_system.m_world.IsLocked()){throw new Error();}for(var i=this.m_firstIndex;i<this.m_lastIndex;i++){this.m_system.DestroyParticle(i,callDestructionListener);}};_proto88.UpdateStatistics=function UpdateStatistics(){if(!this.m_system.m_positionBuffer.data){throw new Error();}if(!this.m_system.m_velocityBuffer.data){throw new Error();}var p=new b2Vec2();var v=new b2Vec2();if(this.m_timestamp!==this.m_system.m_timestamp){var m=this.m_system.GetParticleMass();this.m_mass=m*(this.m_lastIndex-this.m_firstIndex);this.m_center.SetZero();this.m_linearVelocity.SetZero();for(var 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){var 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(var _i25=this.m_firstIndex;_i25<this.m_lastIndex;_i25++){b2Vec2.SubVV(this.m_system.m_positionBuffer.data[_i25],this.m_center,p);b2Vec2.SubVV(this.m_system.m_velocityBuffer.data[_i25],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;}};return b2ParticleGroup;}();b2ParticleGroup.GetLinearVelocityFromWorldPoint_s_t0=new b2Vec2();var b2StackQueue=function(){function b2StackQueue(capacity){this.m_buffer=[];this.m_front=0;this.m_back=0;this.m_buffer.fill(null,0,capacity);}var _proto89=b2StackQueue.prototype;_proto89.Push=function Push(item){if(this.m_back>=this.m_capacity){for(var 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++;};_proto89.Pop=function Pop(){this.m_buffer[this.m_front]=null;this.m_front++;};_proto89.Empty=function Empty(){return this.m_front===this.m_back;};_proto89.Front=function Front(){var item=this.m_buffer[this.m_front];if(!item){throw new Error();}return item;};_createClass(b2StackQueue,[{key:"m_capacity",get:function get(){return this.m_buffer.length;}}]);return b2StackQueue;}();var b2VoronoiDiagram=function(){function b2VoronoiDiagram(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,function(index){return new b2VoronoiDiagram_Generator();});this.m_generatorCapacity=generatorCapacity;}var _proto90=b2VoronoiDiagram.prototype;_proto90.AddGenerator=function AddGenerator(center,tag,necessary){var g=this.m_generatorBuffer[this.m_generatorCount++];g.center.Copy(center);g.tag=tag;g.necessary=necessary;};_proto90.Generate=function Generate(radius,margin){var inverseRadius=1/radius;var lower=new b2Vec2(+b2_maxFloat,+b2_maxFloat);var upper=new b2Vec2(-b2_maxFloat,-b2_maxFloat);var necessary_count=0;for(var k=0;k<this.m_generatorCount;k++){var 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=[];var queue=new b2StackQueue(4*this.m_countX*this.m_countY);for(var _k4=0;_k4<this.m_generatorCount;_k4++){var _g=this.m_generatorBuffer[_k4];_g.center.SelfSub(lower).SelfMul(inverseRadius);var x=Math.floor(_g.center.x);var 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()){var task=queue.Front();var _x=task.m_x;var _y=task.m_y;var i=task.m_i;var _g2=task.m_generator;queue.Pop();if(!this.m_diagram[i]){this.m_diagram[i]=_g2;if(_x>0){queue.Push(new b2VoronoiDiagram_Task(_x-1,_y,i-1,_g2));}if(_y>0){queue.Push(new b2VoronoiDiagram_Task(_x,_y-1,i-this.m_countX,_g2));}if(_x<this.m_countX-1){queue.Push(new b2VoronoiDiagram_Task(_x+1,_y,i+1,_g2));}if(_y<this.m_countY-1){queue.Push(new b2VoronoiDiagram_Task(_x,_y+1,i+this.m_countX,_g2));}}}for(var _y2=0;_y2<this.m_countY;_y2++){for(var _x2=0;_x2<this.m_countX-1;_x2++){var _i26=_x2+_y2*this.m_countX;var a=this.m_diagram[_i26];var b=this.m_diagram[_i26+1];if(a!==b){queue.Push(new b2VoronoiDiagram_Task(_x2,_y2,_i26,b));queue.Push(new b2VoronoiDiagram_Task(_x2+1,_y2,_i26+1,a));}}}for(var _y3=0;_y3<this.m_countY-1;_y3++){for(var _x3=0;_x3<this.m_countX;_x3++){var _i27=_x3+_y3*this.m_countX;var _a2=this.m_diagram[_i27];var _b3=this.m_diagram[_i27+this.m_countX];if(_a2!==_b3){queue.Push(new b2VoronoiDiagram_Task(_x3,_y3,_i27,_b3));queue.Push(new b2VoronoiDiagram_Task(_x3,_y3+1,_i27+this.m_countX,_a2));}}}while(!queue.Empty()){var _task=queue.Front();var _x4=_task.m_x;var _y4=_task.m_y;var _i28=_task.m_i;var _k5=_task.m_generator;queue.Pop();var _a3=this.m_diagram[_i28];var _b4=_k5;if(_a3!==_b4){var ax=_a3.center.x-_x4;var ay=_a3.center.y-_y4;var bx=_b4.center.x-_x4;var by=_b4.center.y-_y4;var a2=ax*ax+ay*ay;var b2=bx*bx+by*by;if(a2>b2){this.m_diagram[_i28]=_b4;if(_x4>0){queue.Push(new b2VoronoiDiagram_Task(_x4-1,_y4,_i28-1,_b4));}if(_y4>0){queue.Push(new b2VoronoiDiagram_Task(_x4,_y4-1,_i28-this.m_countX,_b4));}if(_x4<this.m_countX-1){queue.Push(new b2VoronoiDiagram_Task(_x4+1,_y4,_i28+1,_b4));}if(_y4<this.m_countY-1){queue.Push(new b2VoronoiDiagram_Task(_x4,_y4+1,_i28+this.m_countX,_b4));}}}}};_proto90.GetNodes=function GetNodes(callback){for(var y=0;y<this.m_countY-1;y++){for(var x=0;x<this.m_countX-1;x++){var i=x+y*this.m_countX;var a=this.m_diagram[i];var b=this.m_diagram[i+1];var c=this.m_diagram[i+this.m_countX];var 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);}}}}};return b2VoronoiDiagram;}();var b2VoronoiDiagram_Generator=function b2VoronoiDiagram_Generator(){this.center=new b2Vec2();this.tag=0;this.necessary=false;};var b2VoronoiDiagram_Task=function b2VoronoiDiagram_Task(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){var 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,len,cmp){if(first===void 0){first=0;}if(len===void 0){len=array.length-first;}if(cmp===void 0){cmp=default_compare$1;}var left=first;var stack=[];var pos=0;for(;;){for(;left+1<len;len++){var pivot=array[left+Math.floor(Math.random()*(len-left))];stack[pos++]=len;for(var 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,len,cmp){if(first===void 0){first=0;}if(len===void 0){len=array.length-first;}if(cmp===void 0){cmp=default_compare$1;}return std_sort$1(array,first,len,cmp);}function std_remove_if(array,predicate,length){if(length===void 0){length=array.length;}var l=0;for(var 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){var count=last-first;while(count>0){var step=Math.floor(count/2);var 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){var count=last-first;while(count>0){var step=Math.floor(count/2);var 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){var 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;}var result=first;while(++first!==last){if(!cmp(array[result],array[first])){std_iter_swap$1(array,++result,first);}}return ++result;}var b2GrowableBuffer=function(){function b2GrowableBuffer(allocator){this.data=[];this.count=0;this.capacity=0;this.allocator=allocator;}var _proto91=b2GrowableBuffer.prototype;_proto91.Append=function Append(){if(this.count>=this.capacity){this.Grow();}return this.count++;};_proto91.Reserve=function Reserve(newCapacity){if(this.capacity>=newCapacity){return;}for(var i=this.capacity;i<newCapacity;++i){this.data[i]=this.allocator();}this.capacity=newCapacity;};_proto91.Grow=function Grow(){var newCapacity=this.capacity?2*this.capacity:b2_minParticleSystemBufferCapacity;this.Reserve(newCapacity);};_proto91.Free=function Free(){if(this.data.length===0){return;}this.data=[];this.capacity=0;this.count=0;};_proto91.Shorten=function Shorten(newEnd){};_proto91.Data=function Data(){return this.data;};_proto91.GetCount=function GetCount(){return this.count;};_proto91.SetCount=function SetCount(newCount){this.count=newCount;};_proto91.GetCapacity=function GetCapacity(){return this.capacity;};_proto91.RemoveIf=function RemoveIf(pred){this.count=std_remove_if(this.data,pred,this.count);};_proto91.Unique=function Unique(pred){this.count=std_unique(this.data,0,this.count,pred);};return b2GrowableBuffer;}();var b2FixtureParticleQueryCallback=function(_b2QueryCallback){_inheritsLoose(b2FixtureParticleQueryCallback,_b2QueryCallback);function b2FixtureParticleQueryCallback(system){var _this31;_this31=_b2QueryCallback.call(this)||this;_this31.m_system=system;return _this31;}var _proto92=b2FixtureParticleQueryCallback.prototype;_proto92.ShouldQueryParticleSystem=function ShouldQueryParticleSystem(system){return false;};_proto92.ReportFixture=function ReportFixture(fixture){if(fixture.IsSensor()){return true;}var shape=fixture.GetShape();var childCount=shape.GetChildCount();for(var childIndex=0;childIndex<childCount;childIndex++){var aabb=fixture.GetAABB(childIndex);var enumerator=this.m_system.GetInsideBoundsEnumerator(aabb);var index=void 0;while((index=enumerator.GetNext())>=0){this.ReportFixtureAndParticle(fixture,childIndex,index);}}return true;};_proto92.ReportParticle=function ReportParticle(system,index){return false;};_proto92.ReportFixtureAndParticle=function ReportFixtureAndParticle(fixture,childIndex,index){};return b2FixtureParticleQueryCallback;}(b2QueryCallback);var b2ParticleContact=function(){function b2ParticleContact(){this.indexA=0;this.indexB=0;this.weight=0;this.normal=new b2Vec2();this.flags=0;}var _proto93=b2ParticleContact.prototype;_proto93.SetIndices=function SetIndices(a,b){this.indexA=a;this.indexB=b;};_proto93.SetWeight=function SetWeight(w){this.weight=w;};_proto93.SetNormal=function SetNormal(n){this.normal.Copy(n);};_proto93.SetFlags=function SetFlags(f){this.flags=f;};_proto93.GetIndexA=function GetIndexA(){return this.indexA;};_proto93.GetIndexB=function GetIndexB(){return this.indexB;};_proto93.GetWeight=function GetWeight(){return this.weight;};_proto93.GetNormal=function GetNormal(){return this.normal;};_proto93.GetFlags=function GetFlags(){return this.flags;};_proto93.IsEqual=function 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;};_proto93.IsNotEqual=function IsNotEqual(rhs){return !this.IsEqual(rhs);};_proto93.ApproximatelyEqual=function ApproximatelyEqual(rhs){var MAX_WEIGHT_DIFF=0.01;var 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;};return b2ParticleContact;}();var b2ParticleBodyContact=function b2ParticleBodyContact(){this.index=0;this.weight=0.0;this.normal=new b2Vec2();this.mass=0.0;};var b2ParticlePair=function b2ParticlePair(){this.indexA=0;this.indexB=0;this.flags=0;this.strength=0.0;this.distance=0.0;};var b2ParticleTriad=function b2ParticleTriad(){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;};var b2ParticleSystemDef=function(){function b2ParticleSystemDef(){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;}var _proto94=b2ParticleSystemDef.prototype;_proto94.Copy=function 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;};_proto94.Clone=function Clone(){return new b2ParticleSystemDef().Copy(this);};return b2ParticleSystemDef;}();var b2ParticleSystem=function(){function b2ParticleSystem(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(function(){return 0;});this.m_proxyBuffer=new b2GrowableBuffer(function(){return new b2ParticleSystem_Proxy();});this.m_contactBuffer=new b2GrowableBuffer(function(){return new b2ParticleContact();});this.m_bodyContactBuffer=new b2GrowableBuffer(function(){return new b2ParticleBodyContact();});this.m_pairBuffer=new b2GrowableBuffer(function(){return new b2ParticlePair();});this.m_triadBuffer=new b2GrowableBuffer(function(){return 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);}b2ParticleSystem.computeTag=function computeTag(x,y){return (y+b2ParticleSystem.yOffset>>>0<<b2ParticleSystem.yShift)+(b2ParticleSystem.xScale*x+b2ParticleSystem.xOffset>>>0)>>>0;};b2ParticleSystem.computeRelativeTag=function computeRelativeTag(tag,x,y){return tag+(y<<b2ParticleSystem.yShift)+(x<<b2ParticleSystem.xShift)>>>0;};var _proto95=b2ParticleSystem.prototype;_proto95.Drop=function 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);};_proto95.CreateParticle=function CreateParticle(def){if(this.m_world.IsLocked()){throw new Error();}if(this.m_count>=this.m_internalAllocatedCapacity){var 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;}}var 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;}var 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;}var proxy=this.m_proxyBuffer.data[this.m_proxyBuffer.Append()];var lifetime=b2Maybe(def.lifetime,0.0);var 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;var 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;};_proto95.GetParticleHandleFromIndex=function GetParticleHandleFromIndex(index){this.m_handleIndexBuffer.data=this.RequestBuffer(this.m_handleIndexBuffer.data);var handle=this.m_handleIndexBuffer.data[index];if(handle){return handle;}handle=new b2ParticleHandle();handle.SetIndex(index);this.m_handleIndexBuffer.data[index]=handle;return handle;};_proto95.DestroyParticle=function DestroyParticle(index,callDestructionListener){if(callDestructionListener===void 0){callDestructionListener=false;}var flags=exports.b2ParticleFlag.b2_zombieParticle;if(callDestructionListener){flags|=exports.b2ParticleFlag.b2_destructionListenerParticle;}this.SetParticleFlags(index,this.m_flagsBuffer.data[index]|flags);};_proto95.DestroyOldestParticle=function DestroyOldestParticle(index,callDestructionListener){if(callDestructionListener===void 0){callDestructionListener=false;}var particleCount=this.GetParticleCount();var oldestFiniteLifetimeParticle=this.m_indexByExpirationTimeBuffer.data[particleCount-(index+1)];var oldestInfiniteLifetimeParticle=this.m_indexByExpirationTimeBuffer.data[index];this.DestroyParticle(this.m_expirationTimeBuffer.data[oldestFiniteLifetimeParticle]>0.0?oldestFiniteLifetimeParticle:oldestInfiniteLifetimeParticle,callDestructionListener);};_proto95.DestroyParticlesInShape=function DestroyParticlesInShape(shape,xf,callDestructionListener){if(callDestructionListener===void 0){callDestructionListener=false;}var s_aabb=b2ParticleSystem.DestroyParticlesInShape_s_aabb;if(this.m_world.IsLocked()){throw new Error();}var callback=new b2ParticleSystem_DestroyParticlesInShapeCallback(this,shape,xf,callDestructionListener);var aabb=s_aabb;shape.ComputeAABB(aabb,xf,0);this.m_world.QueryAABB(callback,aabb);return callback.Destroyed();};_proto95.CreateParticleGroup=function CreateParticleGroup(groupDef){var s_transform=b2ParticleSystem.CreateParticleGroup_s_transform;if(this.m_world.IsLocked()){throw new Error();}var transform=s_transform;transform.SetPositionAngle(b2Maybe(groupDef.position,b2Vec2.ZERO),b2Maybe(groupDef.angle,0));var 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){var count=b2Maybe(groupDef.particleCount,groupDef.positionData.length);for(var i=0;i<count;i++){var p=groupDef.positionData[i];this.CreateParticleForGroup(groupDef,transform,p);}}var lastIndex=this.m_count;var 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(var _i29=firstIndex;_i29<lastIndex;_i29++){this.m_groupBuffer[_i29]=group;}this.SetGroupFlags(group,b2Maybe(groupDef.groupFlags,0));var 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;};_proto95.JoinParticleGroups=function 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);var filter=new b2ParticleSystem_JoinParticleGroupsFilter(groupB.m_firstIndex);this.UpdateContacts(true);this.UpdatePairsAndTriads(groupA.m_firstIndex,groupB.m_lastIndex,filter);for(var i=groupB.m_firstIndex;i<groupB.m_lastIndex;i++){this.m_groupBuffer[i]=groupA;}var 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);};_proto95.SplitParticleGroup=function SplitParticleGroup(group){this.UpdateContacts(true);var particleCount=group.GetParticleCount();var nodeBuffer=b2MakeArray(particleCount,function(index){return new b2ParticleSystem_ParticleListNode();});b2ParticleSystem.InitializeParticleLists(group,nodeBuffer);this.MergeParticleListsInContact(group,nodeBuffer);var survivingList=b2ParticleSystem.FindLongestParticleList(group,nodeBuffer);this.MergeZombieParticleListNodes(group,nodeBuffer,survivingList);this.CreateParticleGroupsFromParticleList(group,nodeBuffer,survivingList);this.UpdatePairsAndTriadsWithParticleList(group,nodeBuffer);};_proto95.GetParticleGroupList=function GetParticleGroupList(){return this.m_groupList;};_proto95.GetParticleGroupCount=function GetParticleGroupCount(){return this.m_groupCount;};_proto95.GetParticleCount=function GetParticleCount(){return this.m_count;};_proto95.GetMaxParticleCount=function GetMaxParticleCount(){return this.m_def.maxCount;};_proto95.SetMaxParticleCount=function SetMaxParticleCount(count){this.m_def.maxCount=count;};_proto95.GetAllParticleFlags=function GetAllParticleFlags(){return this.m_allParticleFlags;};_proto95.GetAllGroupFlags=function GetAllGroupFlags(){return this.m_allGroupFlags;};_proto95.SetPaused=function SetPaused(paused){this.m_paused=paused;};_proto95.GetPaused=function GetPaused(){return this.m_paused;};_proto95.SetDensity=function SetDensity(density){this.m_def.density=density;this.m_inverseDensity=1/this.m_def.density;};_proto95.GetDensity=function GetDensity(){return this.m_def.density;};_proto95.SetGravityScale=function SetGravityScale(gravityScale){this.m_def.gravityScale=gravityScale;};_proto95.GetGravityScale=function GetGravityScale(){return this.m_def.gravityScale;};_proto95.SetDamping=function SetDamping(damping){this.m_def.dampingStrength=damping;};_proto95.GetDamping=function GetDamping(){return this.m_def.dampingStrength;};_proto95.SetStaticPressureIterations=function SetStaticPressureIterations(iterations){this.m_def.staticPressureIterations=iterations;};_proto95.GetStaticPressureIterations=function GetStaticPressureIterations(){return this.m_def.staticPressureIterations;};_proto95.SetRadius=function SetRadius(radius){this.m_particleDiameter=2*radius;this.m_squaredDiameter=this.m_particleDiameter*this.m_particleDiameter;this.m_inverseDiameter=1/this.m_particleDiameter;};_proto95.GetRadius=function GetRadius(){return this.m_particleDiameter/2;};_proto95.GetPositionBuffer=function GetPositionBuffer(){return this.m_positionBuffer.data;};_proto95.GetVelocityBuffer=function GetVelocityBuffer(){return this.m_velocityBuffer.data;};_proto95.GetColorBuffer=function GetColorBuffer(){this.m_colorBuffer.data=this.RequestBuffer(this.m_colorBuffer.data);return this.m_colorBuffer.data;};_proto95.GetGroupBuffer=function GetGroupBuffer(){return this.m_groupBuffer;};_proto95.GetWeightBuffer=function GetWeightBuffer(){return this.m_weightBuffer;};_proto95.GetUserDataBuffer=function GetUserDataBuffer(){this.m_userDataBuffer.data=this.RequestBuffer(this.m_userDataBuffer.data);return this.m_userDataBuffer.data;};_proto95.GetFlagsBuffer=function GetFlagsBuffer(){return this.m_flagsBuffer.data;};_proto95.SetParticleFlags=function SetParticleFlags(index,newFlags){var 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;};_proto95.GetParticleFlags=function GetParticleFlags(index){return this.m_flagsBuffer.data[index];};_proto95.SetFlagsBuffer=function SetFlagsBuffer(buffer){this.SetUserOverridableBuffer(this.m_flagsBuffer,buffer);};_proto95.SetPositionBuffer=function SetPositionBuffer(buffer){if(buffer instanceof Float32Array){if(buffer.length%2!==0){throw new Error();}var count=buffer.length/2;var array=new Array(count);for(var i=0;i<count;++i){array[i]=new b2Vec2(buffer.subarray(i*2,i*2+2));}buffer=array;}this.SetUserOverridableBuffer(this.m_positionBuffer,buffer);};_proto95.SetVelocityBuffer=function SetVelocityBuffer(buffer){if(buffer instanceof Float32Array){if(buffer.length%2!==0){throw new Error();}var count=buffer.length/2;var array=new Array(count);for(var i=0;i<count;++i){array[i]=new b2Vec2(buffer.subarray(i*2,i*2+2));}buffer=array;}this.SetUserOverridableBuffer(this.m_velocityBuffer,buffer);};_proto95.SetColorBuffer=function SetColorBuffer(buffer){if(buffer instanceof Float32Array){if(buffer.length%4!==0){throw new Error();}var count=buffer.length/4;var array=new Array(count);for(var i=0;i<count;++i){array[i]=new b2Color(buffer.subarray(i*4,i*4+4));}buffer=array;}this.SetUserOverridableBuffer(this.m_colorBuffer,buffer);};_proto95.SetUserDataBuffer=function SetUserDataBuffer(buffer){this.SetUserOverridableBuffer(this.m_userDataBuffer,buffer);};_proto95.GetContacts=function GetContacts(){return this.m_contactBuffer.data;};_proto95.GetContactCount=function GetContactCount(){return this.m_contactBuffer.count;};_proto95.GetBodyContacts=function GetBodyContacts(){return this.m_bodyContactBuffer.data;};_proto95.GetBodyContactCount=function GetBodyContactCount(){return this.m_bodyContactBuffer.count;};_proto95.GetPairs=function GetPairs(){return this.m_pairBuffer.data;};_proto95.GetPairCount=function GetPairCount(){return this.m_pairBuffer.count;};_proto95.GetTriads=function GetTriads(){return this.m_triadBuffer.data;};_proto95.GetTriadCount=function GetTriadCount(){return this.m_triadBuffer.count;};_proto95.SetStuckThreshold=function 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);}};_proto95.GetStuckCandidates=function GetStuckCandidates(){return this.m_stuckParticleBuffer.Data();};_proto95.GetStuckCandidateCount=function GetStuckCandidateCount(){return this.m_stuckParticleBuffer.GetCount();};_proto95.ComputeCollisionEnergy=function ComputeCollisionEnergy(){var s_v=b2ParticleSystem.ComputeCollisionEnergy_s_v;var vel_data=this.m_velocityBuffer.data;var sum_v2=0;for(var k=0;k<this.m_contactBuffer.count;k++){var contact=this.m_contactBuffer.data[k];var a=contact.indexA;var b=contact.indexB;var n=contact.normal;var v=b2Vec2.SubVV(vel_data[b],vel_data[a],s_v);var vn=b2Vec2.DotVV(v,n);if(vn<0){sum_v2+=vn*vn;}}return 0.5*this.GetParticleMass()*sum_v2;};_proto95.SetStrictContactCheck=function SetStrictContactCheck(enabled){this.m_def.strictContactCheck=enabled;};_proto95.GetStrictContactCheck=function GetStrictContactCheck(){return this.m_def.strictContactCheck;};_proto95.SetParticleLifetime=function SetParticleLifetime(index,lifetime){var 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){var particleCount=this.GetParticleCount();for(var i=0;i<particleCount;++i){this.m_indexByExpirationTimeBuffer.data[i]=i;}}var quantizedLifetime=lifetime/this.m_def.lifetimeGranularity;var 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;}};_proto95.GetParticleLifetime=function GetParticleLifetime(index){return this.ExpirationTimeToLifetime(this.GetExpirationTimeBuffer()[index]);};_proto95.SetDestructionByAge=function SetDestructionByAge(enable){if(enable){this.GetExpirationTimeBuffer();}this.m_def.destroyByAge=enable;};_proto95.GetDestructionByAge=function GetDestructionByAge(){return this.m_def.destroyByAge;};_proto95.GetExpirationTimeBuffer=function GetExpirationTimeBuffer(){this.m_expirationTimeBuffer.data=this.RequestBuffer(this.m_expirationTimeBuffer.data);return this.m_expirationTimeBuffer.data;};_proto95.ExpirationTimeToLifetime=function ExpirationTimeToLifetime(expirationTime){return (expirationTime>0?expirationTime-this.GetQuantizedTimeElapsed():expirationTime)*this.m_def.lifetimeGranularity;};_proto95.GetIndexByExpirationTimeBuffer=function 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;};_proto95.ParticleApplyLinearImpulse=function ParticleApplyLinearImpulse(index,impulse){this.ApplyLinearImpulse(index,index+1,impulse);};_proto95.ApplyLinearImpulse=function ApplyLinearImpulse(firstIndex,lastIndex,impulse){var vel_data=this.m_velocityBuffer.data;var numParticles=lastIndex-firstIndex;var totalMass=numParticles*this.GetParticleMass();var velocityDelta=new b2Vec2().Copy(impulse).SelfMul(1/totalMass);for(var i=firstIndex;i<lastIndex;i++){vel_data[i].SelfAdd(velocityDelta);}};b2ParticleSystem.IsSignificantForce=function IsSignificantForce(force){return force.x!==0||force.y!==0;};_proto95.ParticleApplyForce=function ParticleApplyForce(index,force){if(b2ParticleSystem.IsSignificantForce(force)&&this.ForceCanBeApplied(this.m_flagsBuffer.data[index])){this.PrepareForceBuffer();this.m_forceBuffer[index].SelfAdd(force);}};_proto95.ApplyForce=function ApplyForce(firstIndex,lastIndex,force){var distributedForce=new b2Vec2().Copy(force).SelfMul(1/(lastIndex-firstIndex));if(b2ParticleSystem.IsSignificantForce(distributedForce)){this.PrepareForceBuffer();for(var i=firstIndex;i<lastIndex;i++){this.m_forceBuffer[i].SelfAdd(distributedForce);}}};_proto95.GetNext=function GetNext(){return this.m_next;};_proto95.QueryAABB=function QueryAABB(callback,aabb){if(this.m_proxyBuffer.count===0){return;}var beginProxy=0;var endProxy=this.m_proxyBuffer.count;var 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);var 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);var pos_data=this.m_positionBuffer.data;for(var k=firstProxy;k<lastProxy;++k){var proxy=this.m_proxyBuffer.data[k];var i=proxy.index;var 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;}}}};_proto95.QueryShapeAABB=function QueryShapeAABB(callback,shape,xf,childIndex){if(childIndex===void 0){childIndex=0;}var s_aabb=b2ParticleSystem.QueryShapeAABB_s_aabb;var aabb=s_aabb;shape.ComputeAABB(aabb,xf,childIndex);this.QueryAABB(callback,aabb);};_proto95.QueryPointAABB=function QueryPointAABB(callback,point,slop){if(slop===void 0){slop=b2_linearSlop;}var s_aabb=b2ParticleSystem.QueryPointAABB_s_aabb;var 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);};_proto95.RayCast=function RayCast(callback,point1,point2){var s_aabb=b2ParticleSystem.RayCast_s_aabb;var s_p=b2ParticleSystem.RayCast_s_p;var s_v=b2ParticleSystem.RayCast_s_v;var s_n=b2ParticleSystem.RayCast_s_n;var s_point=b2ParticleSystem.RayCast_s_point;if(this.m_proxyBuffer.count===0){return;}var pos_data=this.m_positionBuffer.data;var aabb=s_aabb;b2Vec2.MinV(point1,point2,aabb.lowerBound);b2Vec2.MaxV(point1,point2,aabb.upperBound);var fraction=1;var v=b2Vec2.SubVV(point2,point1,s_v);var v2=b2Vec2.DotVV(v,v);var enumerator=this.GetInsideBoundsEnumerator(aabb);var i;while((i=enumerator.GetNext())>=0){var p=b2Vec2.SubVV(point1,pos_data[i],s_p);var pv=b2Vec2.DotVV(p,v);var p2=b2Vec2.DotVV(p,p);var determinant=pv*pv-v2*(p2-this.m_squaredDiameter);if(determinant>=0){var sqrtDeterminant=b2Sqrt(determinant);var t=(-pv-sqrtDeterminant)/v2;if(t>fraction){continue;}if(t<0){t=(-pv+sqrtDeterminant)/v2;if(t<0||t>fraction){continue;}}var n=b2Vec2.AddVMulSV(p,t,v,s_n);n.Normalize();var f=callback.ReportParticle(this,i,b2Vec2.AddVMulSV(point1,t,v,s_point),n,t);fraction=b2Min(fraction,f);if(fraction<=0){break;}}}};_proto95.ComputeAABB=function ComputeAABB(aabb){var particleCount=this.GetParticleCount();aabb.lowerBound.x=+b2_maxFloat;aabb.lowerBound.y=+b2_maxFloat;aabb.upperBound.x=-b2_maxFloat;aabb.upperBound.y=-b2_maxFloat;var pos_data=this.m_positionBuffer.data;for(var i=0;i<particleCount;i++){var 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;};_proto95.FreeBuffer=function FreeBuffer(b,capacity){if(b===null){return;}b.length=0;};_proto95.FreeUserOverridableBuffer=function FreeUserOverridableBuffer(b){if(b.userSuppliedCapacity===0){this.FreeBuffer(b.data,this.m_internalAllocatedCapacity);}};_proto95.ReallocateBuffer3=function ReallocateBuffer3(oldBuffer,oldCapacity,newCapacity){if(newCapacity<=oldCapacity){throw new Error();}var newBuffer=oldBuffer?oldBuffer.slice():[];newBuffer.length=newCapacity;return newBuffer;};_proto95.ReallocateBuffer5=function 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;};_proto95.ReallocateBuffer4=function ReallocateBuffer4(buffer,oldCapacity,newCapacity,deferred){return this.ReallocateBuffer5(buffer.data,buffer.userSuppliedCapacity,oldCapacity,newCapacity,deferred);};_proto95.RequestBuffer=function RequestBuffer(buffer){if(!buffer){if(this.m_internalAllocatedCapacity===0){this.ReallocateInternalAllocatedBuffers(b2_minParticleSystemBufferCapacity);}buffer=[];buffer.length=this.m_internalAllocatedCapacity;}return buffer;};_proto95.ReallocateHandleBuffers=function ReallocateHandleBuffers(newCapacity){this.m_handleIndexBuffer.data=this.ReallocateBuffer4(this.m_handleIndexBuffer,this.m_internalAllocatedCapacity,newCapacity,true);};_proto95.ReallocateInternalAllocatedBuffers=function 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);var 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;}};_proto95.CreateParticleForGroup=function CreateParticleForGroup(groupDef,xf,p){var 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);};_proto95.CreateParticlesStrokeShapeForGroup=function CreateParticlesStrokeShapeForGroup(shape,groupDef,xf){var s_edge=b2ParticleSystem.CreateParticlesStrokeShapeForGroup_s_edge;var s_d=b2ParticleSystem.CreateParticlesStrokeShapeForGroup_s_d;var s_p=b2ParticleSystem.CreateParticlesStrokeShapeForGroup_s_p;var stride=b2Maybe(groupDef.stride,0);if(stride===0){stride=this.GetParticleStride();}var positionOnEdge=0;var childCount=shape.GetChildCount();for(var childIndex=0;childIndex<childCount;childIndex++){var edge=null;if(shape.GetType()===exports.b2ShapeType.e_edgeShape){edge=shape;}else {edge=s_edge;shape.GetChildEdge(edge,childIndex);}var d=b2Vec2.SubVV(edge.m_vertex2,edge.m_vertex1,s_d);var edgeLength=d.Length();while(positionOnEdge<edgeLength){var p=b2Vec2.AddVMulSV(edge.m_vertex1,positionOnEdge/edgeLength,d,s_p);this.CreateParticleForGroup(groupDef,xf,p);positionOnEdge+=stride;}positionOnEdge-=edgeLength;}};_proto95.CreateParticlesFillShapeForGroup=function CreateParticlesFillShapeForGroup(shape,groupDef,xf){var s_aabb=b2ParticleSystem.CreateParticlesFillShapeForGroup_s_aabb;var s_p=b2ParticleSystem.CreateParticlesFillShapeForGroup_s_p;var stride=b2Maybe(groupDef.stride,0);if(stride===0){stride=this.GetParticleStride();}var identity=b2Transform.IDENTITY;var aabb=s_aabb;shape.ComputeAABB(aabb,identity,0);for(var y=Math.floor(aabb.lowerBound.y/stride)*stride;y<aabb.upperBound.y;y+=stride){for(var x=Math.floor(aabb.lowerBound.x/stride)*stride;x<aabb.upperBound.x;x+=stride){var p=s_p.Set(x,y);if(shape.TestPoint(identity,p)){this.CreateParticleForGroup(groupDef,xf,p);}}}};_proto95.CreateParticlesWithShapeForGroup=function 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;}};_proto95.CreateParticlesWithShapesForGroup=function CreateParticlesWithShapesForGroup(shapes,shapeCount,groupDef,xf){var compositeShape=new b2ParticleSystem_CompositeShape(shapes,shapeCount);this.CreateParticlesFillShapeForGroup(compositeShape,groupDef,xf);};_proto95.CloneParticle=function CloneParticle(oldIndex,group){var 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;var newIndex=this.CreateParticle(def);if(this.m_handleIndexBuffer.data){var 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;};_proto95.DestroyParticlesInGroup=function DestroyParticlesInGroup(group,callDestructionListener){if(callDestructionListener===void 0){callDestructionListener=false;}for(var i=group.m_firstIndex;i<group.m_lastIndex;i++){this.DestroyParticle(i,callDestructionListener);}};_proto95.DestroyParticleGroup=function DestroyParticleGroup(group){if(this.m_world.m_destructionListener){this.m_world.m_destructionListener.SayGoodbyeParticleGroup(group);}this.SetGroupFlags(group,0);for(var 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;};b2ParticleSystem.ParticleCanBeConnected=function 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;};_proto95.UpdatePairsAndTriads=function UpdatePairsAndTriads(firstIndex,lastIndex,filter){var s_dab=b2ParticleSystem.UpdatePairsAndTriads_s_dab;var s_dbc=b2ParticleSystem.UpdatePairsAndTriads_s_dbc;var s_dca=b2ParticleSystem.UpdatePairsAndTriads_s_dca;var pos_data=this.m_positionBuffer.data;var particleFlags=0;for(var i=firstIndex;i<lastIndex;i++){particleFlags|=this.m_flagsBuffer.data[i];}if(particleFlags&b2ParticleSystem.k_pairFlags){for(var k=0;k<this.m_contactBuffer.count;k++){var contact=this.m_contactBuffer.data[k];var a=contact.indexA;var b=contact.indexB;var af=this.m_flagsBuffer.data[a];var bf=this.m_flagsBuffer.data[b];var groupA=this.m_groupBuffer[a];var 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)){var 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){var diagram=new b2VoronoiDiagram(lastIndex-firstIndex);for(var _i30=firstIndex;_i30<lastIndex;_i30++){var flags=this.m_flagsBuffer.data[_i30];var group=this.m_groupBuffer[_i30];if(!(flags&exports.b2ParticleFlag.b2_zombieParticle)&&b2ParticleSystem.ParticleCanBeConnected(flags,group)){diagram.AddGenerator(pos_data[_i30],_i30,filter.IsNecessary(_i30));}}var stride=this.GetParticleStride();diagram.Generate(stride/2,stride*2);var system=this;var callback=function callback(a,b,c){var af=system.m_flagsBuffer.data[a];var bf=system.m_flagsBuffer.data[b];var cf=system.m_flagsBuffer.data[c];if((af|bf|cf)&b2ParticleSystem.k_triadFlags&&filter.ShouldCreateTriad(a,b,c)){var pa=pos_data[a];var pb=pos_data[b];var pc=pos_data[c];var dab=b2Vec2.SubVV(pa,pb,s_dab);var dbc=b2Vec2.SubVV(pb,pc,s_dbc);var dca=b2Vec2.SubVV(pc,pa,s_dca);var maxDistanceSquared=b2_maxTriadDistanceSquared*system.m_squaredDiameter;if(b2Vec2.DotVV(dab,dab)>maxDistanceSquared||b2Vec2.DotVV(dbc,dbc)>maxDistanceSquared||b2Vec2.DotVV(dca,dca)>maxDistanceSquared){return;}var _groupA=system.m_groupBuffer[a];var _groupB=system.m_groupBuffer[b];var groupC=system.m_groupBuffer[c];var 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);var midPoint_x=(pa.x+pb.x+pc.x)/3.0;var 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);}};_proto95.UpdatePairsAndTriadsWithReactiveParticles=function UpdatePairsAndTriadsWithReactiveParticles(){var filter=new b2ParticleSystem_ReactiveFilter(this.m_flagsBuffer);this.UpdatePairsAndTriads(0,this.m_count,filter);for(var i=0;i<this.m_count;i++){this.m_flagsBuffer.data[i]&=~exports.b2ParticleFlag.b2_reactiveParticle;}this.m_allParticleFlags&=~exports.b2ParticleFlag.b2_reactiveParticle;};b2ParticleSystem.ComparePairIndices=function ComparePairIndices(a,b){var diffA=a.indexA-b.indexA;if(diffA!==0){return diffA<0;}return a.indexB<b.indexB;};b2ParticleSystem.MatchPairIndices=function MatchPairIndices(a,b){return a.indexA===b.indexA&&a.indexB===b.indexB;};b2ParticleSystem.CompareTriadIndices=function CompareTriadIndices(a,b){var diffA=a.indexA-b.indexA;if(diffA!==0){return diffA<0;}var diffB=a.indexB-b.indexB;if(diffB!==0){return diffB<0;}return a.indexC<b.indexC;};b2ParticleSystem.MatchTriadIndices=function MatchTriadIndices(a,b){return a.indexA===b.indexA&&a.indexB===b.indexB&&a.indexC===b.indexC;};b2ParticleSystem.InitializeParticleLists=function InitializeParticleLists(group,nodeBuffer){var bufferIndex=group.GetBufferIndex();var particleCount=group.GetParticleCount();for(var i=0;i<particleCount;i++){var node=nodeBuffer[i];node.list=node;node.next=null;node.count=1;node.index=i+bufferIndex;}};_proto95.MergeParticleListsInContact=function MergeParticleListsInContact(group,nodeBuffer){var bufferIndex=group.GetBufferIndex();for(var k=0;k<this.m_contactBuffer.count;k++){var contact=this.m_contactBuffer.data[k];var a=contact.indexA;var b=contact.indexB;if(!group.ContainsParticle(a)||!group.ContainsParticle(b)){continue;}var listA=nodeBuffer[a-bufferIndex].list;var listB=nodeBuffer[b-bufferIndex].list;if(listA===listB){continue;}if(listA.count<listB.count){var _tmp=listA;listA=listB;listB=_tmp;}b2ParticleSystem.MergeParticleLists(listA,listB);}};b2ParticleSystem.MergeParticleLists=function MergeParticleLists(listA,listB){for(var b=listB;;){b.list=listA;var nextB=b.next;if(nextB){b=nextB;}else {b.next=listA.next;break;}}listA.next=listB;listA.count+=listB.count;listB.count=0;};b2ParticleSystem.FindLongestParticleList=function FindLongestParticleList(group,nodeBuffer){var particleCount=group.GetParticleCount();var result=nodeBuffer[0];for(var i=0;i<particleCount;i++){var node=nodeBuffer[i];if(result.count<node.count){result=node;}}return result;};_proto95.MergeZombieParticleListNodes=function MergeZombieParticleListNodes(group,nodeBuffer,survivingList){var particleCount=group.GetParticleCount();for(var i=0;i<particleCount;i++){var node=nodeBuffer[i];if(node!==survivingList&&this.m_flagsBuffer.data[node.index]&exports.b2ParticleFlag.b2_zombieParticle){b2ParticleSystem.MergeParticleListAndNode(survivingList,node);}}};b2ParticleSystem.MergeParticleListAndNode=function MergeParticleListAndNode(list,node){node.list=list;node.next=list.next;list.next=node;list.count++;node.count=0;};_proto95.CreateParticleGroupsFromParticleList=function CreateParticleGroupsFromParticleList(group,nodeBuffer,survivingList){var particleCount=group.GetParticleCount();var def=new b2ParticleGroupDef();def.groupFlags=group.GetGroupFlags();def.userData=group.GetUserData();for(var i=0;i<particleCount;i++){var list=nodeBuffer[i];if(!list.count||list===survivingList){continue;}var newGroup=this.CreateParticleGroup(def);for(var node=list;node;node=node.next){var oldIndex=node.index;var newIndex=this.CloneParticle(oldIndex,newGroup);this.m_flagsBuffer.data[oldIndex]|=exports.b2ParticleFlag.b2_zombieParticle;node.index=newIndex;}}};_proto95.UpdatePairsAndTriadsWithParticleList=function UpdatePairsAndTriadsWithParticleList(group,nodeBuffer){var bufferIndex=group.GetBufferIndex();for(var k=0;k<this.m_pairBuffer.count;k++){var pair=this.m_pairBuffer.data[k];var a=pair.indexA;var b=pair.indexB;if(group.ContainsParticle(a)){pair.indexA=nodeBuffer[a-bufferIndex].index;}if(group.ContainsParticle(b)){pair.indexB=nodeBuffer[b-bufferIndex].index;}}for(var _k6=0;_k6<this.m_triadBuffer.count;_k6++){var triad=this.m_triadBuffer.data[_k6];var _a4=triad.indexA;var _b5=triad.indexB;var c=triad.indexC;if(group.ContainsParticle(_a4)){triad.indexA=nodeBuffer[_a4-bufferIndex].index;}if(group.ContainsParticle(_b5)){triad.indexB=nodeBuffer[_b5-bufferIndex].index;}if(group.ContainsParticle(c)){triad.indexC=nodeBuffer[c-bufferIndex].index;}}};_proto95.ComputeDepth=function ComputeDepth(){var contactGroups=[];var contactGroupsCount=0;for(var k=0;k<this.m_contactBuffer.count;k++){var contact=this.m_contactBuffer.data[k];var a=contact.indexA;var b=contact.indexB;var groupA=this.m_groupBuffer[a];var groupB=this.m_groupBuffer[b];if(groupA&&groupA===groupB&&groupA.m_groupFlags&exports.b2ParticleGroupFlag.b2_particleGroupNeedsUpdateDepth){contactGroups[contactGroupsCount++]=contact;}}var groupsToUpdate=[];var groupsToUpdateCount=0;for(var 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(var i=group.m_firstIndex;i<group.m_lastIndex;i++){this.m_accumulationBuffer[i]=0;}}}for(var _k7=0;_k7<contactGroupsCount;_k7++){var _contact=contactGroups[_k7];var _a5=_contact.indexA;var _b6=_contact.indexB;var w=_contact.weight;this.m_accumulationBuffer[_a5]+=w;this.m_accumulationBuffer[_b6]+=w;}for(var _i31=0;_i31<groupsToUpdateCount;_i31++){var _group=groupsToUpdate[_i31];for(var _i32=_group.m_firstIndex;_i32<_group.m_lastIndex;_i32++){var _w2=this.m_accumulationBuffer[_i32];this.m_depthBuffer[_i32]=_w2<0.8?0:b2_maxFloat;}}var iterationCount=b2Sqrt(this.m_count)>>0;for(var t=0;t<iterationCount;t++){var updated=false;for(var _k8=0;_k8<contactGroupsCount;_k8++){var _contact2=contactGroups[_k8];var _a6=_contact2.indexA;var _b7=_contact2.indexB;var r=1-_contact2.weight;var ap0=this.m_depthBuffer[_a6];var bp0=this.m_depthBuffer[_b7];var ap1=bp0+r;var bp1=ap0+r;if(ap0>ap1){this.m_depthBuffer[_a6]=ap1;updated=true;}if(bp0>bp1){this.m_depthBuffer[_b7]=bp1;updated=true;}}if(!updated){break;}}for(var _i33=0;_i33<groupsToUpdateCount;_i33++){var _group2=groupsToUpdate[_i33];for(var _i34=_group2.m_firstIndex;_i34<_group2.m_lastIndex;_i34++){if(this.m_depthBuffer[_i34]<b2_maxFloat){this.m_depthBuffer[_i34]*=this.m_particleDiameter;}else {this.m_depthBuffer[_i34]=0;}}}};_proto95.GetInsideBoundsEnumerator=function GetInsideBoundsEnumerator(aabb){var lowerTag=b2ParticleSystem.computeTag(this.m_inverseDiameter*aabb.lowerBound.x-1,this.m_inverseDiameter*aabb.lowerBound.y-1);var upperTag=b2ParticleSystem.computeTag(this.m_inverseDiameter*aabb.upperBound.x+1,this.m_inverseDiameter*aabb.upperBound.y+1);var beginProxy=0;var endProxy=this.m_proxyBuffer.count;var firstProxy=std_lower_bound(this.m_proxyBuffer.data,beginProxy,endProxy,lowerTag,b2ParticleSystem_Proxy.CompareProxyTag);var lastProxy=std_upper_bound(this.m_proxyBuffer.data,beginProxy,endProxy,upperTag,b2ParticleSystem_Proxy.CompareTagProxy);return new b2ParticleSystem_InsideBoundsEnumerator(this,lowerTag,upperTag,firstProxy,lastProxy);};_proto95.UpdateAllParticleFlags=function UpdateAllParticleFlags(){this.m_allParticleFlags=0;for(var i=0;i<this.m_count;i++){this.m_allParticleFlags|=this.m_flagsBuffer.data[i];}this.m_needsUpdateAllParticleFlags=false;};_proto95.UpdateAllGroupFlags=function UpdateAllGroupFlags(){this.m_allGroupFlags=0;for(var group=this.m_groupList;group;group=group.GetNext()){this.m_allGroupFlags|=group.m_groupFlags;}this.m_needsUpdateAllGroupFlags=false;};_proto95.AddContact=function AddContact(a,b,contacts){var flags_data=this.m_flagsBuffer.data;var pos_data=this.m_positionBuffer.data;var d=b2Vec2.SubVV(pos_data[b],pos_data[a],b2ParticleSystem.AddContact_s_d);var distBtParticlesSq=b2Vec2.DotVV(d,d);if(0<distBtParticlesSq&&distBtParticlesSq<this.m_squaredDiameter){var invD=b2InvSqrt(distBtParticlesSq);var 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;}};_proto95.FindContacts_Reference=function FindContacts_Reference(contacts){var beginProxy=0;var endProxy=this.m_proxyBuffer.count;this.m_contactBuffer.count=0;for(var a=beginProxy,c=beginProxy;a<endProxy;a++){var rightTag=b2ParticleSystem.computeRelativeTag(this.m_proxyBuffer.data[a].tag,1,0);for(var 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);}var bottomLeftTag=b2ParticleSystem.computeRelativeTag(this.m_proxyBuffer.data[a].tag,-1,1);for(;c<endProxy;c++){if(bottomLeftTag<=this.m_proxyBuffer.data[c].tag){break;}}var bottomRightTag=b2ParticleSystem.computeRelativeTag(this.m_proxyBuffer.data[a].tag,1,1);for(var _b8=c;_b8<endProxy;_b8++){if(bottomRightTag<this.m_proxyBuffer.data[_b8].tag){break;}this.AddContact(this.m_proxyBuffer.data[a].index,this.m_proxyBuffer.data[_b8].index,this.m_contactBuffer);}}};_proto95.FindContacts=function FindContacts(contacts){this.FindContacts_Reference(contacts);};_proto95.UpdateProxies_Reference=function UpdateProxies_Reference(proxies){var pos_data=this.m_positionBuffer.data;var inv_diam=this.m_inverseDiameter;for(var k=0;k<this.m_proxyBuffer.count;++k){var proxy=this.m_proxyBuffer.data[k];var i=proxy.index;var p=pos_data[i];proxy.tag=b2ParticleSystem.computeTag(inv_diam*p.x,inv_diam*p.y);}};_proto95.UpdateProxies=function UpdateProxies(proxies){this.UpdateProxies_Reference(proxies);};_proto95.SortProxies=function SortProxies(proxies){std_sort$1(this.m_proxyBuffer.data,0,this.m_proxyBuffer.count,b2ParticleSystem_Proxy.CompareProxyProxy);};_proto95.FilterContacts=function FilterContacts(contacts){var contactFilter=this.GetParticleContactFilter();if(contactFilter===null){return;}var system=this;var predicate=function predicate(contact){return (contact.flags&exports.b2ParticleFlag.b2_particleContactFilterParticle)!==0&&!contactFilter.ShouldCollideParticleParticle(system,contact.indexA,contact.indexB);};this.m_contactBuffer.RemoveIf(predicate);};_proto95.NotifyContactListenerPreContact=function NotifyContactListenerPreContact(particlePairs){var contactListener=this.GetParticleContactListener();if(contactListener===null){return;}particlePairs.Initialize(this.m_contactBuffer,this.m_flagsBuffer);throw new Error();};_proto95.NotifyContactListenerPostContact=function NotifyContactListenerPostContact(particlePairs){var contactListener=this.GetParticleContactListener();if(contactListener===null){return;}for(var k=0;k<this.m_contactBuffer.count;++k){var contact=this.m_contactBuffer.data[k];{contactListener.BeginContactParticleParticle(this,contact);}}throw new Error();};b2ParticleSystem.b2ParticleContactIsZombie=function b2ParticleContactIsZombie(contact){return (contact.flags&exports.b2ParticleFlag.b2_zombieParticle)===exports.b2ParticleFlag.b2_zombieParticle;};_proto95.UpdateContacts=function UpdateContacts(exceptZombie){this.UpdateProxies(this.m_proxyBuffer);this.SortProxies(this.m_proxyBuffer);var 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);}};_proto95.NotifyBodyContactListenerPreContact=function NotifyBodyContactListenerPreContact(fixtureSet){var contactListener=this.GetFixtureContactListener();if(contactListener===null){return;}fixtureSet.Initialize(this.m_bodyContactBuffer,this.m_flagsBuffer);throw new Error();};_proto95.NotifyBodyContactListenerPostContact=function NotifyBodyContactListenerPostContact(fixtureSet){var contactListener=this.GetFixtureContactListener();if(contactListener===null){return;}for(var k=0;k<this.m_bodyContactBuffer.count;k++){var contact=this.m_bodyContactBuffer.data[k];{contactListener.BeginContactFixtureParticle(this,contact);}}throw new Error();};_proto95.UpdateBodyContacts=function UpdateBodyContacts(){var s_aabb=b2ParticleSystem.UpdateBodyContacts_s_aabb;var fixtureSet=new b2ParticleSystem_FixtureParticleSet();this.NotifyBodyContactListenerPreContact(fixtureSet);if(this.m_stuckThreshold>0){var particleCount=this.GetParticleCount();for(var 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);var aabb=s_aabb;this.ComputeAABB(aabb);if(this.UpdateBodyContacts_callback===null){this.UpdateBodyContacts_callback=new b2ParticleSystem_UpdateBodyContactsCallback(this);}var 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);};_proto95.Solve=function Solve(step){var 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;var 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(var i=0;i<this.m_count;i++){this.m_positionBuffer.data[i].SelfMulAdd(subStep.dt,this.m_velocityBuffer.data[i]);}}};_proto95.SolveCollision=function SolveCollision(step){var s_aabb=b2ParticleSystem.SolveCollision_s_aabb;var pos_data=this.m_positionBuffer.data;var vel_data=this.m_velocityBuffer.data;var aabb=s_aabb;aabb.lowerBound.x=+b2_maxFloat;aabb.lowerBound.y=+b2_maxFloat;aabb.upperBound.x=-b2_maxFloat;aabb.upperBound.y=-b2_maxFloat;for(var i=0;i<this.m_count;i++){var v=vel_data[i];var p1=pos_data[i];var p2_x=p1.x+step.dt*v.x;var 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);}var callback=this.SolveCollision_callback;callback.m_step=step;this.m_world.QueryAABB(callback,aabb);};_proto95.LimitVelocity=function LimitVelocity(step){var vel_data=this.m_velocityBuffer.data;var criticalVelocitySquared=this.GetCriticalVelocitySquared(step);for(var i=0;i<this.m_count;i++){var v=vel_data[i];var v2=b2Vec2.DotVV(v,v);if(v2>criticalVelocitySquared){v.SelfMul(b2Sqrt(criticalVelocitySquared/v2));}}};_proto95.SolveGravity=function SolveGravity(step){var s_gravity=b2ParticleSystem.SolveGravity_s_gravity;var vel_data=this.m_velocityBuffer.data;var gravity=b2Vec2.MulSV(step.dt*this.m_def.gravityScale,this.m_world.GetGravity(),s_gravity);for(var i=0;i<this.m_count;i++){vel_data[i].SelfAdd(gravity);}};_proto95.SolveBarrier=function SolveBarrier(step){var s_aabb=b2ParticleSystem.SolveBarrier_s_aabb;var s_va=b2ParticleSystem.SolveBarrier_s_va;var s_vb=b2ParticleSystem.SolveBarrier_s_vb;var s_pba=b2ParticleSystem.SolveBarrier_s_pba;var s_vba=b2ParticleSystem.SolveBarrier_s_vba;var s_vc=b2ParticleSystem.SolveBarrier_s_vc;var s_pca=b2ParticleSystem.SolveBarrier_s_pca;var s_vca=b2ParticleSystem.SolveBarrier_s_vca;var s_qba=b2ParticleSystem.SolveBarrier_s_qba;var s_qca=b2ParticleSystem.SolveBarrier_s_qca;var s_dv=b2ParticleSystem.SolveBarrier_s_dv;var s_f=b2ParticleSystem.SolveBarrier_s_f;var pos_data=this.m_positionBuffer.data;var vel_data=this.m_velocityBuffer.data;for(var i=0;i<this.m_count;i++){var flags=this.m_flagsBuffer.data[i];if((flags&b2ParticleSystem.k_barrierWallFlags)!==0){vel_data[i].SetZero();}}var tmax=b2_barrierCollisionTime*step.dt;var mass=this.GetParticleMass();for(var k=0;k<this.m_pairBuffer.count;k++){var pair=this.m_pairBuffer.data[k];if(pair.flags&exports.b2ParticleFlag.b2_barrierParticle){var a=pair.indexA;var b=pair.indexB;var pa=pos_data[a];var pb=pos_data[b];var aabb=s_aabb;b2Vec2.MinV(pa,pb,aabb.lowerBound);b2Vec2.MaxV(pa,pb,aabb.upperBound);var aGroup=this.m_groupBuffer[a];var bGroup=this.m_groupBuffer[b];var va=this.GetLinearVelocity(aGroup,a,pa,s_va);var vb=this.GetLinearVelocity(bGroup,b,pb,s_vb);var pba=b2Vec2.SubVV(pb,pa,s_pba);var vba=b2Vec2.SubVV(vb,va,s_vba);var enumerator=this.GetInsideBoundsEnumerator(aabb);var c=void 0;while((c=enumerator.GetNext())>=0){var pc=pos_data[c];var cGroup=this.m_groupBuffer[c];if(aGroup!==cGroup&&bGroup!==cGroup){var vc=this.GetLinearVelocity(cGroup,c,pc,s_vc);var pca=b2Vec2.SubVV(pc,pa,s_pca);var vca=b2Vec2.SubVV(vc,va,s_vca);var e2=b2Vec2.CrossVV(vba,vca);var e1=b2Vec2.CrossVV(pba,vca)-b2Vec2.CrossVV(pca,vba);var e0=b2Vec2.CrossVV(pba,pca);var s=void 0,t=void 0;var 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 {var det=e1*e1-4*e0*e2;if(det<0){continue;}var sqrtDet=b2Sqrt(det);var t1=(-e1-sqrtDet)/(2*e2);var t2=(-e1+sqrtDet)/(2*e2);if(t1>t2){var 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;}}}var dv=s_dv;dv.x=va.x+s*vba.x-vc.x;dv.y=va.y+s*vba.y-vc.y;var f=b2Vec2.MulSV(mass,dv,s_f);if(cGroup&&this.IsRigidGroup(cGroup)){var _mass=cGroup.GetMass();var 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));}}}}};_proto95.SolveStaticPressure=function SolveStaticPressure(step){this.m_staticPressureBuffer=this.RequestBuffer(this.m_staticPressureBuffer);var criticalPressure=this.GetCriticalPressure(step);var pressurePerWeight=this.m_def.staticPressureStrength*criticalPressure;var maxPressure=b2_maxParticlePressure*criticalPressure;var relaxation=this.m_def.staticPressureRelaxation;for(var t=0;t<this.m_def.staticPressureIterations;t++){for(var i=0;i<this.m_count;i++){this.m_accumulationBuffer[i]=0;}for(var k=0;k<this.m_contactBuffer.count;k++){var contact=this.m_contactBuffer.data[k];if(contact.flags&exports.b2ParticleFlag.b2_staticPressureParticle){var a=contact.indexA;var b=contact.indexB;var w=contact.weight;this.m_accumulationBuffer[a]+=w*this.m_staticPressureBuffer[b];this.m_accumulationBuffer[b]+=w*this.m_staticPressureBuffer[a];}}for(var _i35=0;_i35<this.m_count;_i35++){var _w3=this.m_weightBuffer[_i35];if(this.m_flagsBuffer.data[_i35]&exports.b2ParticleFlag.b2_staticPressureParticle){var wh=this.m_accumulationBuffer[_i35];var h=(wh+pressurePerWeight*(_w3-b2_minParticleWeight))/(_w3+relaxation);this.m_staticPressureBuffer[_i35]=b2Clamp(h,0.0,maxPressure);}else {this.m_staticPressureBuffer[_i35]=0;}}}};_proto95.ComputeWeight=function ComputeWeight(){for(var k=0;k<this.m_count;k++){this.m_weightBuffer[k]=0;}for(var _k9=0;_k9<this.m_bodyContactBuffer.count;_k9++){var contact=this.m_bodyContactBuffer.data[_k9];var a=contact.index;var w=contact.weight;this.m_weightBuffer[a]+=w;}for(var _k10=0;_k10<this.m_contactBuffer.count;_k10++){var _contact3=this.m_contactBuffer.data[_k10];var _a7=_contact3.indexA;var b=_contact3.indexB;var _w4=_contact3.weight;this.m_weightBuffer[_a7]+=_w4;this.m_weightBuffer[b]+=_w4;}};_proto95.SolvePressure=function SolvePressure(step){var s_f=b2ParticleSystem.SolvePressure_s_f;var pos_data=this.m_positionBuffer.data;var vel_data=this.m_velocityBuffer.data;var criticalPressure=this.GetCriticalPressure(step);var pressurePerWeight=this.m_def.pressureStrength*criticalPressure;var maxPressure=b2_maxParticlePressure*criticalPressure;for(var i=0;i<this.m_count;i++){var w=this.m_weightBuffer[i];var h=pressurePerWeight*b2Max(0.0,w-b2_minParticleWeight);this.m_accumulationBuffer[i]=b2Min(h,maxPressure);}if(this.m_allParticleFlags&b2ParticleSystem.k_noPressureFlags){for(var _i36=0;_i36<this.m_count;_i36++){if(this.m_flagsBuffer.data[_i36]&b2ParticleSystem.k_noPressureFlags){this.m_accumulationBuffer[_i36]=0;}}}if(this.m_allParticleFlags&exports.b2ParticleFlag.b2_staticPressureParticle){for(var _i37=0;_i37<this.m_count;_i37++){if(this.m_flagsBuffer.data[_i37]&exports.b2ParticleFlag.b2_staticPressureParticle){this.m_accumulationBuffer[_i37]+=this.m_staticPressureBuffer[_i37];}}}var velocityPerPressure=step.dt/(this.m_def.density*this.m_particleDiameter);var inv_mass=this.GetParticleInvMass();for(var k=0;k<this.m_bodyContactBuffer.count;k++){var contact=this.m_bodyContactBuffer.data[k];var a=contact.index;var b=contact.body;var _w5=contact.weight;var m=contact.mass;var n=contact.normal;var p=pos_data[a];var _h=this.m_accumulationBuffer[a]+pressurePerWeight*_w5;var f=b2Vec2.MulSV(velocityPerPressure*_w5*m*_h,n,s_f);vel_data[a].SelfMulSub(inv_mass,f);b.ApplyLinearImpulse(f,p,true);}for(var _k11=0;_k11<this.m_contactBuffer.count;_k11++){var _contact4=this.m_contactBuffer.data[_k11];var _a8=_contact4.indexA;var _b9=_contact4.indexB;var _w6=_contact4.weight;var _n=_contact4.normal;var _h2=this.m_accumulationBuffer[_a8]+this.m_accumulationBuffer[_b9];var _f2=b2Vec2.MulSV(velocityPerPressure*_w6*_h2,_n,s_f);vel_data[_a8].SelfSub(_f2);vel_data[_b9].SelfAdd(_f2);}};_proto95.SolveDamping=function SolveDamping(step){var s_v=b2ParticleSystem.SolveDamping_s_v;var s_f=b2ParticleSystem.SolveDamping_s_f;var pos_data=this.m_positionBuffer.data;var vel_data=this.m_velocityBuffer.data;var linearDamping=this.m_def.dampingStrength;var quadraticDamping=1/this.GetCriticalVelocity(step);var inv_mass=this.GetParticleInvMass();for(var k=0;k<this.m_bodyContactBuffer.count;k++){var contact=this.m_bodyContactBuffer.data[k];var a=contact.index;var b=contact.body;var w=contact.weight;var m=contact.mass;var n=contact.normal;var p=pos_data[a];var v=b2Vec2.SubVV(b.GetLinearVelocityFromWorldPoint(p,b2Vec2.s_t0),vel_data[a],s_v);var vn=b2Vec2.DotVV(v,n);if(vn<0){var damping=b2Max(linearDamping*w,b2Min(-quadraticDamping*vn,0.5));var f=b2Vec2.MulSV(damping*m*vn,n,s_f);vel_data[a].SelfMulAdd(inv_mass,f);b.ApplyLinearImpulse(f.SelfNeg(),p,true);}}for(var _k12=0;_k12<this.m_contactBuffer.count;_k12++){var _contact5=this.m_contactBuffer.data[_k12];var _a9=_contact5.indexA;var _b10=_contact5.indexB;var _w7=_contact5.weight;var _n2=_contact5.normal;var _v4=b2Vec2.SubVV(vel_data[_b10],vel_data[_a9],s_v);var _vn=b2Vec2.DotVV(_v4,_n2);if(_vn<0){var _damping=b2Max(linearDamping*_w7,b2Min(-quadraticDamping*_vn,0.5));var _f3=b2Vec2.MulSV(_damping*_vn,_n2,s_f);vel_data[_a9].SelfAdd(_f3);vel_data[_b10].SelfSub(_f3);}}};_proto95.SolveRigidDamping=function SolveRigidDamping(){var s_t0=b2ParticleSystem.SolveRigidDamping_s_t0;var s_t1=b2ParticleSystem.SolveRigidDamping_s_t1;var s_p=b2ParticleSystem.SolveRigidDamping_s_p;var s_v=b2ParticleSystem.SolveRigidDamping_s_v;var invMassA=[0.0],invInertiaA=[0.0],tangentDistanceA=[0.0];var invMassB=[0.0],invInertiaB=[0.0],tangentDistanceB=[0.0];var pos_data=this.m_positionBuffer.data;var damping=this.m_def.dampingStrength;for(var k=0;k<this.m_bodyContactBuffer.count;k++){var contact=this.m_bodyContactBuffer.data[k];var a=contact.index;var aGroup=this.m_groupBuffer[a];if(aGroup&&this.IsRigidGroup(aGroup)){var b=contact.body;var n=contact.normal;var w=contact.weight;var p=pos_data[a];var v=b2Vec2.SubVV(b.GetLinearVelocityFromWorldPoint(p,s_t0),aGroup.GetLinearVelocityFromWorldPoint(p,s_t1),s_v);var 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);var 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(var _k13=0;_k13<this.m_contactBuffer.count;_k13++){var _contact6=this.m_contactBuffer.data[_k13];var _a10=_contact6.indexA;var _b11=_contact6.indexB;var _n3=_contact6.normal;var _w8=_contact6.weight;var _aGroup=this.m_groupBuffer[_a10];var bGroup=this.m_groupBuffer[_b11];var aRigid=this.IsRigidGroup(_aGroup);var bRigid=this.IsRigidGroup(bGroup);if(_aGroup!==bGroup&&(aRigid||bRigid)){var _p=b2Vec2.MidVV(pos_data[_a10],pos_data[_b11],s_p);var _v5=b2Vec2.SubVV(this.GetLinearVelocity(bGroup,_b11,_p,s_t0),this.GetLinearVelocity(_aGroup,_a10,_p,s_t1),s_v);var _vn2=b2Vec2.DotVV(_v5,_n3);if(_vn2<0){this.InitDampingParameterWithRigidGroupOrParticle(invMassA,invInertiaA,tangentDistanceA,aRigid,_aGroup,_a10,_p,_n3);this.InitDampingParameterWithRigidGroupOrParticle(invMassB,invInertiaB,tangentDistanceB,bRigid,bGroup,_b11,_p,_n3);var _f4=damping*_w8*this.ComputeDampingImpulse(invMassA[0],invInertiaA[0],tangentDistanceA[0],invMassB[0],invInertiaB[0],tangentDistanceB[0],_vn2);this.ApplyDamping(invMassA[0],invInertiaA[0],tangentDistanceA[0],aRigid,_aGroup,_a10,_f4,_n3);this.ApplyDamping(invMassB[0],invInertiaB[0],tangentDistanceB[0],bRigid,bGroup,_b11,-_f4,_n3);}}}};_proto95.SolveExtraDamping=function SolveExtraDamping(){var s_v=b2ParticleSystem.SolveExtraDamping_s_v;var s_f=b2ParticleSystem.SolveExtraDamping_s_f;var vel_data=this.m_velocityBuffer.data;var pos_data=this.m_positionBuffer.data;var inv_mass=this.GetParticleInvMass();for(var k=0;k<this.m_bodyContactBuffer.count;k++){var contact=this.m_bodyContactBuffer.data[k];var a=contact.index;if(this.m_flagsBuffer.data[a]&b2ParticleSystem.k_extraDampingFlags){var b=contact.body;var m=contact.mass;var n=contact.normal;var p=pos_data[a];var v=b2Vec2.SubVV(b.GetLinearVelocityFromWorldPoint(p,b2Vec2.s_t0),vel_data[a],s_v);var vn=b2Vec2.DotVV(v,n);if(vn<0){var f=b2Vec2.MulSV(0.5*m*vn,n,s_f);vel_data[a].SelfMulAdd(inv_mass,f);b.ApplyLinearImpulse(f.SelfNeg(),p,true);}}}};_proto95.SolveWall=function SolveWall(){var vel_data=this.m_velocityBuffer.data;for(var i=0;i<this.m_count;i++){if(this.m_flagsBuffer.data[i]&exports.b2ParticleFlag.b2_wallParticle){vel_data[i].SetZero();}}};_proto95.SolveRigid=function SolveRigid(step){var s_position=b2ParticleSystem.SolveRigid_s_position;var s_rotation=b2ParticleSystem.SolveRigid_s_rotation;var s_transform=b2ParticleSystem.SolveRigid_s_transform;var s_velocityTransform=b2ParticleSystem.SolveRigid_s_velocityTransform;var pos_data=this.m_positionBuffer.data;var vel_data=this.m_velocityBuffer.data;for(var group=this.m_groupList;group;group=group.GetNext()){if(group.m_groupFlags&exports.b2ParticleGroupFlag.b2_rigidParticleGroup){group.UpdateStatistics();var rotation=s_rotation;rotation.SetAngle(step.dt*group.m_angularVelocity);var 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);var transform=s_transform;transform.SetPositionRotation(position,rotation);b2Transform.MulXX(transform,group.m_transform,group.m_transform);var 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(var i=group.m_firstIndex;i<group.m_lastIndex;i++){b2Transform.MulXV(velocityTransform,pos_data[i],vel_data[i]);}}}};_proto95.SolveElastic=function SolveElastic(step){var s_pa=b2ParticleSystem.SolveElastic_s_pa;var s_pb=b2ParticleSystem.SolveElastic_s_pb;var s_pc=b2ParticleSystem.SolveElastic_s_pc;var s_r=b2ParticleSystem.SolveElastic_s_r;var s_t0=b2ParticleSystem.SolveElastic_s_t0;var pos_data=this.m_positionBuffer.data;var vel_data=this.m_velocityBuffer.data;var elasticStrength=step.inv_dt*this.m_def.elasticStrength;for(var k=0;k<this.m_triadBuffer.count;k++){var triad=this.m_triadBuffer.data[k];if(triad.flags&exports.b2ParticleFlag.b2_elasticParticle){var a=triad.indexA;var b=triad.indexB;var c=triad.indexC;var oa=triad.pa;var ob=triad.pb;var oc=triad.pc;var pa=s_pa.Copy(pos_data[a]);var pb=s_pb.Copy(pos_data[b]);var pc=s_pc.Copy(pos_data[c]);var va=vel_data[a];var vb=vel_data[b];var vc=vel_data[c];pa.SelfMulAdd(step.dt,va);pb.SelfMulAdd(step.dt,vb);pc.SelfMulAdd(step.dt,vc);var midPoint_x=(pa.x+pb.x+pc.x)/3.0;var 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;var 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);var r2=r.s*r.s+r.c*r.c;var invR=b2InvSqrt(r2);if(!isFinite(invR)){invR=1.98177537e+019;}r.s*=invR;r.c*=invR;var 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);}}};_proto95.SolveSpring=function SolveSpring(step){var s_pa=b2ParticleSystem.SolveSpring_s_pa;var s_pb=b2ParticleSystem.SolveSpring_s_pb;var s_d=b2ParticleSystem.SolveSpring_s_d;var s_f=b2ParticleSystem.SolveSpring_s_f;var pos_data=this.m_positionBuffer.data;var vel_data=this.m_velocityBuffer.data;var springStrength=step.inv_dt*this.m_def.springStrength;for(var k=0;k<this.m_pairBuffer.count;k++){var pair=this.m_pairBuffer.data[k];if(pair.flags&exports.b2ParticleFlag.b2_springParticle){var a=pair.indexA;var b=pair.indexB;var pa=s_pa.Copy(pos_data[a]);var pb=s_pb.Copy(pos_data[b]);var va=vel_data[a];var vb=vel_data[b];pa.SelfMulAdd(step.dt,va);pb.SelfMulAdd(step.dt,vb);var d=b2Vec2.SubVV(pb,pa,s_d);var r0=pair.distance;var r1=d.Length();var strength=springStrength*pair.strength;var f=b2Vec2.MulSV(strength*(r0-r1)/r1,d,s_f);va.SelfSub(f);vb.SelfAdd(f);}}};_proto95.SolveTensile=function SolveTensile(step){var s_weightedNormal=b2ParticleSystem.SolveTensile_s_weightedNormal;var s_s=b2ParticleSystem.SolveTensile_s_s;var s_f=b2ParticleSystem.SolveTensile_s_f;var vel_data=this.m_velocityBuffer.data;for(var i=0;i<this.m_count;i++){this.m_accumulation2Buffer[i]=new b2Vec2();this.m_accumulation2Buffer[i].SetZero();}for(var k=0;k<this.m_contactBuffer.count;k++){var contact=this.m_contactBuffer.data[k];if(contact.flags&exports.b2ParticleFlag.b2_tensileParticle){var a=contact.indexA;var b=contact.indexB;var w=contact.weight;var n=contact.normal;var weightedNormal=b2Vec2.MulSV((1-w)*w,n,s_weightedNormal);this.m_accumulation2Buffer[a].SelfSub(weightedNormal);this.m_accumulation2Buffer[b].SelfAdd(weightedNormal);}}var criticalVelocity=this.GetCriticalVelocity(step);var pressureStrength=this.m_def.surfaceTensionPressureStrength*criticalVelocity;var normalStrength=this.m_def.surfaceTensionNormalStrength*criticalVelocity;var maxVelocityVariation=b2_maxParticleForce*criticalVelocity;for(var _k14=0;_k14<this.m_contactBuffer.count;_k14++){var _contact7=this.m_contactBuffer.data[_k14];if(_contact7.flags&exports.b2ParticleFlag.b2_tensileParticle){var _a11=_contact7.indexA;var _b12=_contact7.indexB;var _w9=_contact7.weight;var _n4=_contact7.normal;var h=this.m_weightBuffer[_a11]+this.m_weightBuffer[_b12];var s=b2Vec2.SubVV(this.m_accumulation2Buffer[_b12],this.m_accumulation2Buffer[_a11],s_s);var fn=b2Min(pressureStrength*(h-2)+normalStrength*b2Vec2.DotVV(s,_n4),maxVelocityVariation)*_w9;var f=b2Vec2.MulSV(fn,_n4,s_f);vel_data[_a11].SelfSub(f);vel_data[_b12].SelfAdd(f);}}};_proto95.SolveViscous=function SolveViscous(){var s_v=b2ParticleSystem.SolveViscous_s_v;var s_f=b2ParticleSystem.SolveViscous_s_f;var pos_data=this.m_positionBuffer.data;var vel_data=this.m_velocityBuffer.data;var viscousStrength=this.m_def.viscousStrength;var inv_mass=this.GetParticleInvMass();for(var k=0;k<this.m_bodyContactBuffer.count;k++){var contact=this.m_bodyContactBuffer.data[k];var a=contact.index;if(this.m_flagsBuffer.data[a]&exports.b2ParticleFlag.b2_viscousParticle){var b=contact.body;var w=contact.weight;var m=contact.mass;var p=pos_data[a];var v=b2Vec2.SubVV(b.GetLinearVelocityFromWorldPoint(p,b2Vec2.s_t0),vel_data[a],s_v);var f=b2Vec2.MulSV(viscousStrength*m*w,v,s_f);vel_data[a].SelfMulAdd(inv_mass,f);b.ApplyLinearImpulse(f.SelfNeg(),p,true);}}for(var _k15=0;_k15<this.m_contactBuffer.count;_k15++){var _contact8=this.m_contactBuffer.data[_k15];if(_contact8.flags&exports.b2ParticleFlag.b2_viscousParticle){var _a12=_contact8.indexA;var _b13=_contact8.indexB;var _w10=_contact8.weight;var _v6=b2Vec2.SubVV(vel_data[_b13],vel_data[_a12],s_v);var _f5=b2Vec2.MulSV(viscousStrength*_w10,_v6,s_f);vel_data[_a12].SelfAdd(_f5);vel_data[_b13].SelfSub(_f5);}}};_proto95.SolveRepulsive=function SolveRepulsive(step){var s_f=b2ParticleSystem.SolveRepulsive_s_f;var vel_data=this.m_velocityBuffer.data;var repulsiveStrength=this.m_def.repulsiveStrength*this.GetCriticalVelocity(step);for(var k=0;k<this.m_contactBuffer.count;k++){var contact=this.m_contactBuffer.data[k];if(contact.flags&exports.b2ParticleFlag.b2_repulsiveParticle){var a=contact.indexA;var b=contact.indexB;if(this.m_groupBuffer[a]!==this.m_groupBuffer[b]){var w=contact.weight;var n=contact.normal;var f=b2Vec2.MulSV(repulsiveStrength*w,n,s_f);vel_data[a].SelfSub(f);vel_data[b].SelfAdd(f);}}}};_proto95.SolvePowder=function SolvePowder(step){var s_f=b2ParticleSystem.SolvePowder_s_f;var pos_data=this.m_positionBuffer.data;var vel_data=this.m_velocityBuffer.data;var powderStrength=this.m_def.powderStrength*this.GetCriticalVelocity(step);var minWeight=1.0-b2_particleStride;var inv_mass=this.GetParticleInvMass();for(var k=0;k<this.m_bodyContactBuffer.count;k++){var contact=this.m_bodyContactBuffer.data[k];var a=contact.index;if(this.m_flagsBuffer.data[a]&exports.b2ParticleFlag.b2_powderParticle){var w=contact.weight;if(w>minWeight){var b=contact.body;var m=contact.mass;var p=pos_data[a];var n=contact.normal;var f=b2Vec2.MulSV(powderStrength*m*(w-minWeight),n,s_f);vel_data[a].SelfMulSub(inv_mass,f);b.ApplyLinearImpulse(f,p,true);}}}for(var _k16=0;_k16<this.m_contactBuffer.count;_k16++){var _contact9=this.m_contactBuffer.data[_k16];if(_contact9.flags&exports.b2ParticleFlag.b2_powderParticle){var _w11=_contact9.weight;if(_w11>minWeight){var _a13=_contact9.indexA;var _b14=_contact9.indexB;var _n5=_contact9.normal;var _f6=b2Vec2.MulSV(powderStrength*(_w11-minWeight),_n5,s_f);vel_data[_a13].SelfSub(_f6);vel_data[_b14].SelfAdd(_f6);}}}};_proto95.SolveSolid=function SolveSolid(step){var s_f=b2ParticleSystem.SolveSolid_s_f;var vel_data=this.m_velocityBuffer.data;this.m_depthBuffer=this.RequestBuffer(this.m_depthBuffer);var ejectionStrength=step.inv_dt*this.m_def.ejectionStrength;for(var k=0;k<this.m_contactBuffer.count;k++){var contact=this.m_contactBuffer.data[k];var a=contact.indexA;var b=contact.indexB;if(this.m_groupBuffer[a]!==this.m_groupBuffer[b]){var w=contact.weight;var n=contact.normal;var h=this.m_depthBuffer[a]+this.m_depthBuffer[b];var f=b2Vec2.MulSV(ejectionStrength*h*w,n,s_f);vel_data[a].SelfSub(f);vel_data[b].SelfAdd(f);}}};_proto95.SolveForce=function SolveForce(step){var vel_data=this.m_velocityBuffer.data;var velocityPerForce=step.dt*this.GetParticleInvMass();for(var i=0;i<this.m_count;i++){vel_data[i].SelfMulAdd(velocityPerForce,this.m_forceBuffer[i]);}this.m_hasForce=false;};_proto95.SolveColorMixing=function SolveColorMixing(){var colorMixing=0.5*this.m_def.colorMixingStrength;if(colorMixing){for(var k=0;k<this.m_contactBuffer.count;k++){var contact=this.m_contactBuffer.data[k];var a=contact.indexA;var b=contact.indexB;if(this.m_flagsBuffer.data[a]&this.m_flagsBuffer.data[b]&exports.b2ParticleFlag.b2_colorMixingParticle){var colorA=this.m_colorBuffer.data[a];var colorB=this.m_colorBuffer.data[b];b2Color.MixColors(colorA,colorB,colorMixing);}}}};_proto95.SolveZombie=function SolveZombie(){var newCount=0;var newIndices=[];for(var i=0;i<this.m_count;i++){newIndices[i]=b2_invalidParticleIndex;}var allParticleFlags=0;for(var _i38=0;_i38<this.m_count;_i38++){var flags=this.m_flagsBuffer.data[_i38];if(flags&exports.b2ParticleFlag.b2_zombieParticle){var destructionListener=this.m_world.m_destructionListener;if(flags&exports.b2ParticleFlag.b2_destructionListenerParticle&&destructionListener){destructionListener.SayGoodbyeParticle(this,_i38);}if(this.m_handleIndexBuffer.data){var handle=this.m_handleIndexBuffer.data[_i38];if(handle){handle.SetIndex(b2_invalidParticleIndex);this.m_handleIndexBuffer.data[_i38]=null;}}newIndices[_i38]=b2_invalidParticleIndex;}else {newIndices[_i38]=newCount;if(_i38!==newCount){if(this.m_handleIndexBuffer.data){var _handle=this.m_handleIndexBuffer.data[_i38];if(_handle){_handle.SetIndex(newCount);}this.m_handleIndexBuffer.data[newCount]=_handle;}this.m_flagsBuffer.data[newCount]=this.m_flagsBuffer.data[_i38];if(this.m_lastBodyContactStepBuffer.data){this.m_lastBodyContactStepBuffer.data[newCount]=this.m_lastBodyContactStepBuffer.data[_i38];}if(this.m_bodyContactCountBuffer.data){this.m_bodyContactCountBuffer.data[newCount]=this.m_bodyContactCountBuffer.data[_i38];}if(this.m_consecutiveContactStepsBuffer.data){this.m_consecutiveContactStepsBuffer.data[newCount]=this.m_consecutiveContactStepsBuffer.data[_i38];}this.m_positionBuffer.data[newCount].Copy(this.m_positionBuffer.data[_i38]);this.m_velocityBuffer.data[newCount].Copy(this.m_velocityBuffer.data[_i38]);this.m_groupBuffer[newCount]=this.m_groupBuffer[_i38];if(this.m_hasForce){this.m_forceBuffer[newCount].Copy(this.m_forceBuffer[_i38]);}if(this.m_staticPressureBuffer){this.m_staticPressureBuffer[newCount]=this.m_staticPressureBuffer[_i38];}if(this.m_depthBuffer){this.m_depthBuffer[newCount]=this.m_depthBuffer[_i38];}if(this.m_colorBuffer.data){this.m_colorBuffer.data[newCount].Copy(this.m_colorBuffer.data[_i38]);}if(this.m_userDataBuffer.data){this.m_userDataBuffer.data[newCount]=this.m_userDataBuffer.data[_i38];}if(this.m_expirationTimeBuffer.data){this.m_expirationTimeBuffer.data[newCount]=this.m_expirationTimeBuffer.data[_i38];}}newCount++;allParticleFlags|=flags;}}var Test={IsProxyInvalid:function IsProxyInvalid(proxy){return proxy.index<0;},IsContactInvalid:function IsContactInvalid(contact){return contact.indexA<0||contact.indexB<0;},IsBodyContactInvalid:function IsBodyContactInvalid(contact){return contact.index<0;},IsPairInvalid:function IsPairInvalid(pair){return pair.indexA<0||pair.indexB<0;},IsTriadInvalid:function IsTriadInvalid(triad){return triad.indexA<0||triad.indexB<0||triad.indexC<0;}};for(var k=0;k<this.m_proxyBuffer.count;k++){var proxy=this.m_proxyBuffer.data[k];proxy.index=newIndices[proxy.index];}this.m_proxyBuffer.RemoveIf(Test.IsProxyInvalid);for(var _k17=0;_k17<this.m_contactBuffer.count;_k17++){var contact=this.m_contactBuffer.data[_k17];contact.indexA=newIndices[contact.indexA];contact.indexB=newIndices[contact.indexB];}this.m_contactBuffer.RemoveIf(Test.IsContactInvalid);for(var _k18=0;_k18<this.m_bodyContactBuffer.count;_k18++){var _contact10=this.m_bodyContactBuffer.data[_k18];_contact10.index=newIndices[_contact10.index];}this.m_bodyContactBuffer.RemoveIf(Test.IsBodyContactInvalid);for(var _k19=0;_k19<this.m_pairBuffer.count;_k19++){var pair=this.m_pairBuffer.data[_k19];pair.indexA=newIndices[pair.indexA];pair.indexB=newIndices[pair.indexB];}this.m_pairBuffer.RemoveIf(Test.IsPairInvalid);for(var _k20=0;_k20<this.m_triadBuffer.count;_k20++){var triad=this.m_triadBuffer.data[_k20];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){var writeOffset=0;for(var readOffset=0;readOffset<this.m_count;readOffset++){var newIndex=newIndices[this.m_indexByExpirationTimeBuffer.data[readOffset]];if(newIndex!==b2_invalidParticleIndex){this.m_indexByExpirationTimeBuffer.data[writeOffset++]=newIndex;}}}for(var group=this.m_groupList;group;group=group.GetNext()){var firstIndex=newCount;var lastIndex=0;var modified=false;for(var _i39=group.m_firstIndex;_i39<group.m_lastIndex;_i39++){var j=newIndices[_i39];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(var _group3=this.m_groupList;_group3;){var next=_group3.GetNext();if(_group3.m_groupFlags&exports.b2ParticleGroupFlag.b2_particleGroupWillBeDestroyed){this.DestroyParticleGroup(_group3);}_group3=next;}};_proto95.SolveLifetimes=function SolveLifetimes(step){this.m_timeElapsed=this.LifetimeToExpirationTime(step.dt);var quantizedTimeElapsed=this.GetQuantizedTimeElapsed();var expirationTimes=this.m_expirationTimeBuffer.data;var expirationTimeIndices=this.m_indexByExpirationTimeBuffer.data;var particleCount=this.GetParticleCount();if(this.m_expirationTimeBufferRequiresSorting){var ExpirationTimeComparator=function ExpirationTimeComparator(particleIndexA,particleIndexB){var expirationTimeA=expirationTimes[particleIndexA];var expirationTimeB=expirationTimes[particleIndexB];var infiniteExpirationTimeA=expirationTimeA<=0.0;var infiniteExpirationTimeB=expirationTimeB<=0.0;return infiniteExpirationTimeA===infiniteExpirationTimeB?expirationTimeA>expirationTimeB:infiniteExpirationTimeA;};std_sort$1(expirationTimeIndices,0,particleCount,ExpirationTimeComparator);this.m_expirationTimeBufferRequiresSorting=false;}for(var i=particleCount-1;i>=0;--i){var particleIndex=expirationTimeIndices[i];var expirationTime=expirationTimes[particleIndex];if(quantizedTimeElapsed<expirationTime||expirationTime<=0){break;}this.DestroyParticle(particleIndex);}};_proto95.RotateBuffer=function 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(var i=start;i<end;++i){var 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);var particleCount=this.GetParticleCount();var indexByExpirationTime=this.m_indexByExpirationTimeBuffer.data;for(var _i40=0;_i40<particleCount;++_i40){indexByExpirationTime[_i40]=newIndices(indexByExpirationTime[_i40]);}}for(var k=0;k<this.m_proxyBuffer.count;k++){var proxy=this.m_proxyBuffer.data[k];proxy.index=newIndices(proxy.index);}for(var _k21=0;_k21<this.m_contactBuffer.count;_k21++){var contact=this.m_contactBuffer.data[_k21];contact.indexA=newIndices(contact.indexA);contact.indexB=newIndices(contact.indexB);}for(var _k22=0;_k22<this.m_bodyContactBuffer.count;_k22++){var _contact11=this.m_bodyContactBuffer.data[_k22];_contact11.index=newIndices(_contact11.index);}for(var _k23=0;_k23<this.m_pairBuffer.count;_k23++){var pair=this.m_pairBuffer.data[_k23];pair.indexA=newIndices(pair.indexA);pair.indexB=newIndices(pair.indexB);}for(var _k24=0;_k24<this.m_triadBuffer.count;_k24++){var triad=this.m_triadBuffer.data[_k24];triad.indexA=newIndices(triad.indexA);triad.indexB=newIndices(triad.indexB);triad.indexC=newIndices(triad.indexC);}for(var group=this.m_groupList;group;group=group.GetNext()){group.m_firstIndex=newIndices(group.m_firstIndex);group.m_lastIndex=newIndices(group.m_lastIndex-1)+1;}};_proto95.GetCriticalVelocity=function GetCriticalVelocity(step){return this.m_particleDiameter*step.inv_dt;};_proto95.GetCriticalVelocitySquared=function GetCriticalVelocitySquared(step){var velocity=this.GetCriticalVelocity(step);return velocity*velocity;};_proto95.GetCriticalPressure=function GetCriticalPressure(step){return this.m_def.density*this.GetCriticalVelocitySquared(step);};_proto95.GetParticleStride=function GetParticleStride(){return b2_particleStride*this.m_particleDiameter;};_proto95.GetParticleMass=function GetParticleMass(){var stride=this.GetParticleStride();return this.m_def.density*stride*stride;};_proto95.GetParticleInvMass=function GetParticleInvMass(){var inverseStride=this.m_inverseDiameter*(1.0/b2_particleStride);return this.m_inverseDensity*inverseStride*inverseStride;};_proto95.GetFixtureContactFilter=function GetFixtureContactFilter(){return this.m_allParticleFlags&exports.b2ParticleFlag.b2_fixtureContactFilterParticle?this.m_world.m_contactManager.m_contactFilter:null;};_proto95.GetParticleContactFilter=function GetParticleContactFilter(){return this.m_allParticleFlags&exports.b2ParticleFlag.b2_particleContactFilterParticle?this.m_world.m_contactManager.m_contactFilter:null;};_proto95.GetFixtureContactListener=function GetFixtureContactListener(){return this.m_allParticleFlags&exports.b2ParticleFlag.b2_fixtureContactListenerParticle?this.m_world.m_contactManager.m_contactListener:null;};_proto95.GetParticleContactListener=function GetParticleContactListener(){return this.m_allParticleFlags&exports.b2ParticleFlag.b2_particleContactListenerParticle?this.m_world.m_contactManager.m_contactListener:null;};_proto95.SetUserOverridableBuffer=function SetUserOverridableBuffer(buffer,data){buffer.data=data;buffer.userSuppliedCapacity=data.length;};_proto95.SetGroupFlags=function SetGroupFlags(group,newFlags){var 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;};b2ParticleSystem.BodyContactCompare=function BodyContactCompare(lhs,rhs){if(lhs.index===rhs.index){return lhs.weight>rhs.weight;}return lhs.index<rhs.index;};_proto95.RemoveSpuriousBodyContacts=function RemoveSpuriousBodyContacts(){std_sort$1(this.m_bodyContactBuffer.data,0,this.m_bodyContactBuffer.count,b2ParticleSystem.BodyContactCompare);var s_n=b2ParticleSystem.RemoveSpuriousBodyContacts_s_n;var s_pos=b2ParticleSystem.RemoveSpuriousBodyContacts_s_pos;var s_normal=b2ParticleSystem.RemoveSpuriousBodyContacts_s_normal;var k_maxContactsPerPoint=3;var system=this;var lastIndex=-1;var currentContacts=0;var b2ParticleBodyContactRemovePredicate=function b2ParticleBodyContactRemovePredicate(contact){if(contact.index!==lastIndex){currentContacts=0;lastIndex=contact.index;}if(currentContacts++>k_maxContactsPerPoint){return true;}var n=s_n.Copy(contact.normal);n.SelfMul(system.m_particleDiameter*(1-contact.weight));var pos=b2Vec2.AddVV(system.m_positionBuffer.data[contact.index],n,s_pos);if(!contact.fixture.TestPoint(pos)){var childCount=contact.fixture.GetShape().GetChildCount();for(var childIndex=0;childIndex<childCount;childIndex++){var normal=s_normal;var 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);};_proto95.DetectStuckParticle=function 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;};_proto95.ValidateParticleIndex=function ValidateParticleIndex(index){return index>=0&&index<this.GetParticleCount()&&index!==b2_invalidParticleIndex;};_proto95.GetQuantizedTimeElapsed=function GetQuantizedTimeElapsed(){return Math.floor(this.m_timeElapsed/0x100000000);};_proto95.LifetimeToExpirationTime=function LifetimeToExpirationTime(lifetime){return this.m_timeElapsed+Math.floor(lifetime/this.m_def.lifetimeGranularity*0x100000000);};_proto95.ForceCanBeApplied=function ForceCanBeApplied(flags){return !(flags&exports.b2ParticleFlag.b2_wallParticle);};_proto95.PrepareForceBuffer=function PrepareForceBuffer(){if(!this.m_hasForce){for(var i=0;i<this.m_count;i++){this.m_forceBuffer[i].SetZero();}this.m_hasForce=true;}};_proto95.IsRigidGroup=function IsRigidGroup(group){return group!==null&&(group.m_groupFlags&exports.b2ParticleGroupFlag.b2_rigidParticleGroup)!==0;};_proto95.GetLinearVelocity=function GetLinearVelocity(group,particleIndex,point,out){if(group&&this.IsRigidGroup(group)){return group.GetLinearVelocityFromWorldPoint(point,out);}else {return out.Copy(this.m_velocityBuffer.data[particleIndex]);}};_proto95.InitDampingParameter=function 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);};_proto95.InitDampingParameterWithRigidGroupOrParticle=function 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 {var flags=this.m_flagsBuffer.data[particleIndex];this.InitDampingParameter(invMass,invInertia,tangentDistance,flags&exports.b2ParticleFlag.b2_wallParticle?0:this.GetParticleMass(),0,point,point,normal);}};_proto95.ComputeDampingImpulse=function ComputeDampingImpulse(invMassA,invInertiaA,tangentDistanceA,invMassB,invInertiaB,tangentDistanceB,normalVelocity){var invMass=invMassA+invInertiaA*tangentDistanceA*tangentDistanceA+invMassB+invInertiaB*tangentDistanceB*tangentDistanceB;return invMass>0?normalVelocity/invMass:0;};_proto95.ApplyDamping=function 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);}};return b2ParticleSystem;}();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();var b2ParticleSystem_UserOverridableBuffer=function(){function b2ParticleSystem_UserOverridableBuffer(){this._data=null;this.userSuppliedCapacity=0;}_createClass(b2ParticleSystem_UserOverridableBuffer,[{key:"data",get:function get(){return this._data;},set:function set(value){this._data=value;}}]);return b2ParticleSystem_UserOverridableBuffer;}();var b2ParticleSystem_Proxy=function(){function b2ParticleSystem_Proxy(){this.index=b2_invalidParticleIndex;this.tag=0;}b2ParticleSystem_Proxy.CompareProxyProxy=function CompareProxyProxy(a,b){return a.tag<b.tag;};b2ParticleSystem_Proxy.CompareTagProxy=function CompareTagProxy(a,b){return a<b.tag;};b2ParticleSystem_Proxy.CompareProxyTag=function CompareProxyTag(a,b){return a.tag<b;};return b2ParticleSystem_Proxy;}();var b2ParticleSystem_InsideBoundsEnumerator=function(){function b2ParticleSystem_InsideBoundsEnumerator(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;}var _proto96=b2ParticleSystem_InsideBoundsEnumerator.prototype;_proto96.GetNext=function GetNext(){while(this.m_first<this.m_last){var 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;};return b2ParticleSystem_InsideBoundsEnumerator;}();var b2ParticleSystem_ParticleListNode=function b2ParticleSystem_ParticleListNode(){this.next=null;this.count=0;this.index=0;};var b2ParticleSystem_FixedSetAllocator=function(){function b2ParticleSystem_FixedSetAllocator(){}var _proto97=b2ParticleSystem_FixedSetAllocator.prototype;_proto97.Allocate=function Allocate(itemSize,count){return count;};_proto97.Clear=function Clear(){};_proto97.GetCount=function GetCount(){return 0;};_proto97.Invalidate=function Invalidate(itemIndex){};_proto97.GetValidBuffer=function GetValidBuffer(){return [];};_proto97.GetBuffer=function GetBuffer(){return [];};_proto97.SetCount=function SetCount(count){};return b2ParticleSystem_FixedSetAllocator;}();var b2ParticleSystem_FixtureParticle=function b2ParticleSystem_FixtureParticle(fixture,particle){this.second=b2_invalidParticleIndex;this.first=fixture;this.second=particle;};var b2ParticleSystem_FixtureParticleSet=function(_b2ParticleSystem_Fix){_inheritsLoose(b2ParticleSystem_FixtureParticleSet,_b2ParticleSystem_Fix);function b2ParticleSystem_FixtureParticleSet(){return _b2ParticleSystem_Fix.apply(this,arguments)||this;}var _proto98=b2ParticleSystem_FixtureParticleSet.prototype;_proto98.Initialize=function Initialize(bodyContactBuffer,flagsBuffer){};_proto98.Find=function Find(pair){return b2_invalidParticleIndex;};return b2ParticleSystem_FixtureParticleSet;}(b2ParticleSystem_FixedSetAllocator);var b2ParticleSystem_ParticlePair=function b2ParticleSystem_ParticlePair(particleA,particleB){this.first=b2_invalidParticleIndex;this.second=b2_invalidParticleIndex;this.first=particleA;this.second=particleB;};var b2ParticlePairSet=function(_b2ParticleSystem_Fix2){_inheritsLoose(b2ParticlePairSet,_b2ParticleSystem_Fix2);function b2ParticlePairSet(){return _b2ParticleSystem_Fix2.apply(this,arguments)||this;}var _proto99=b2ParticlePairSet.prototype;_proto99.Initialize=function Initialize(contactBuffer,flagsBuffer){};_proto99.Find=function Find(pair){return b2_invalidParticleIndex;};return b2ParticlePairSet;}(b2ParticleSystem_FixedSetAllocator);var b2ParticleSystem_ConnectionFilter=function(){function b2ParticleSystem_ConnectionFilter(){}var _proto100=b2ParticleSystem_ConnectionFilter.prototype;_proto100.IsNecessary=function IsNecessary(index){return true;};_proto100.ShouldCreatePair=function ShouldCreatePair(a,b){return true;};_proto100.ShouldCreateTriad=function ShouldCreateTriad(a,b,c){return true;};return b2ParticleSystem_ConnectionFilter;}();var b2ParticleSystem_DestroyParticlesInShapeCallback=function(_b2QueryCallback2){_inheritsLoose(b2ParticleSystem_DestroyParticlesInShapeCallback,_b2QueryCallback2);function b2ParticleSystem_DestroyParticlesInShapeCallback(system,shape,xf,callDestructionListener){var _this32;_this32=_b2QueryCallback2.call(this)||this;_this32.m_callDestructionListener=false;_this32.m_destroyed=0;_this32.m_system=system;_this32.m_shape=shape;_this32.m_xf=xf;_this32.m_callDestructionListener=callDestructionListener;_this32.m_destroyed=0;return _this32;}var _proto101=b2ParticleSystem_DestroyParticlesInShapeCallback.prototype;_proto101.ReportFixture=function ReportFixture(fixture){return false;};_proto101.ReportParticle=function 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;};_proto101.Destroyed=function Destroyed(){return this.m_destroyed;};return b2ParticleSystem_DestroyParticlesInShapeCallback;}(b2QueryCallback);var b2ParticleSystem_JoinParticleGroupsFilter=function(_b2ParticleSystem_Con){_inheritsLoose(b2ParticleSystem_JoinParticleGroupsFilter,_b2ParticleSystem_Con);function b2ParticleSystem_JoinParticleGroupsFilter(threshold){var _this33;_this33=_b2ParticleSystem_Con.call(this)||this;_this33.m_threshold=0;_this33.m_threshold=threshold;return _this33;}var _proto102=b2ParticleSystem_JoinParticleGroupsFilter.prototype;_proto102.ShouldCreatePair=function ShouldCreatePair(a,b){return a<this.m_threshold&&this.m_threshold<=b||b<this.m_threshold&&this.m_threshold<=a;};_proto102.ShouldCreateTriad=function 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);};return b2ParticleSystem_JoinParticleGroupsFilter;}(b2ParticleSystem_ConnectionFilter);var b2ParticleSystem_CompositeShape=function(_b2Shape5){_inheritsLoose(b2ParticleSystem_CompositeShape,_b2Shape5);function b2ParticleSystem_CompositeShape(shapes,shapeCount){var _this34;if(shapeCount===void 0){shapeCount=shapes.length;}_this34=_b2Shape5.call(this,exports.b2ShapeType.e_unknown,0)||this;_this34.m_shapeCount=0;_this34.m_shapes=shapes;_this34.m_shapeCount=shapeCount;return _this34;}var _proto103=b2ParticleSystem_CompositeShape.prototype;_proto103.Clone=function Clone(){throw new Error();};_proto103.GetChildCount=function GetChildCount(){return 1;};_proto103.TestPoint=function TestPoint(xf,p){for(var i=0;i<this.m_shapeCount;i++){if(this.m_shapes[i].TestPoint(xf,p)){return true;}}return false;};_proto103.ComputeDistance=function ComputeDistance(xf,p,normal,childIndex){return 0;};_proto103.RayCast=function RayCast(output,input,xf,childIndex){return false;};_proto103.ComputeAABB=function ComputeAABB(aabb,xf,childIndex){var 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(var i=0;i<this.m_shapeCount;i++){var childCount=this.m_shapes[i].GetChildCount();for(var j=0;j<childCount;j++){var subaabb=s_subaabb;this.m_shapes[i].ComputeAABB(subaabb,xf,j);aabb.Combine1(subaabb);}}};_proto103.ComputeMass=function ComputeMass(massData,density){};_proto103.SetupDistanceProxy=function SetupDistanceProxy(proxy,index){};_proto103.ComputeSubmergedArea=function ComputeSubmergedArea(normal,offset,xf,c){return 0;};_proto103.Dump=function Dump(log){};return b2ParticleSystem_CompositeShape;}(b2Shape);var b2ParticleSystem_ReactiveFilter=function(_b2ParticleSystem_Con2){_inheritsLoose(b2ParticleSystem_ReactiveFilter,_b2ParticleSystem_Con2);function b2ParticleSystem_ReactiveFilter(flagsBuffer){var _this35;_this35=_b2ParticleSystem_Con2.call(this)||this;_this35.m_flagsBuffer=flagsBuffer;return _this35;}var _proto104=b2ParticleSystem_ReactiveFilter.prototype;_proto104.IsNecessary=function IsNecessary(index){return (this.m_flagsBuffer.data[index]&exports.b2ParticleFlag.b2_reactiveParticle)!==0;};return b2ParticleSystem_ReactiveFilter;}(b2ParticleSystem_ConnectionFilter);var b2ParticleSystem_UpdateBodyContactsCallback=function(_b2FixtureParticleQue){_inheritsLoose(b2ParticleSystem_UpdateBodyContactsCallback,_b2FixtureParticleQue);function b2ParticleSystem_UpdateBodyContactsCallback(system,contactFilter){var _this36;if(contactFilter===void 0){contactFilter=null;}_this36=_b2FixtureParticleQue.call(this,system)||this;_this36.m_contactFilter=null;_this36.m_contactFilter=contactFilter;return _this36;}var _proto105=b2ParticleSystem_UpdateBodyContactsCallback.prototype;_proto105.ShouldCollideFixtureParticle=function ShouldCollideFixtureParticle(fixture,particleSystem,particleIndex){if(this.m_contactFilter){var flags=this.m_system.GetFlagsBuffer();if(flags[particleIndex]&exports.b2ParticleFlag.b2_fixtureContactFilterParticle){return this.m_contactFilter.ShouldCollideFixtureParticle(fixture,this.m_system,particleIndex);}}return true;};_proto105.ReportFixtureAndParticle=function ReportFixtureAndParticle(fixture,childIndex,a){var s_n=b2ParticleSystem_UpdateBodyContactsCallback.ReportFixtureAndParticle_s_n;var s_rp=b2ParticleSystem_UpdateBodyContactsCallback.ReportFixtureAndParticle_s_rp;var ap=this.m_system.m_positionBuffer.data[a];var n=s_n;var d=fixture.ComputeDistance(ap,n,childIndex);if(d<this.m_system.m_particleDiameter&&this.ShouldCollideFixtureParticle(fixture,this.m_system,a)){var b=fixture.GetBody();var bp=b.GetWorldCenter();var bm=b.GetMass();var bI=b.GetInertia()-bm*b.GetLocalCenter().LengthSquared();var invBm=bm>0?1/bm:0;var invBI=bI>0?1/bI:0;var invAm=this.m_system.m_flagsBuffer.data[a]&exports.b2ParticleFlag.b2_wallParticle?0:this.m_system.GetParticleInvMass();var rp=b2Vec2.SubVV(ap,bp,s_rp);var rpn=b2Vec2.CrossVV(rp,n);var invM=invAm+invBm+invBI*rpn*rpn;var 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);}};return b2ParticleSystem_UpdateBodyContactsCallback;}(b2FixtureParticleQueryCallback);b2ParticleSystem_UpdateBodyContactsCallback.ReportFixtureAndParticle_s_n=new b2Vec2();b2ParticleSystem_UpdateBodyContactsCallback.ReportFixtureAndParticle_s_rp=new b2Vec2();var b2ParticleSystem_SolveCollisionCallback=function(_b2FixtureParticleQue2){_inheritsLoose(b2ParticleSystem_SolveCollisionCallback,_b2FixtureParticleQue2);function b2ParticleSystem_SolveCollisionCallback(system,step){var _this37;_this37=_b2FixtureParticleQue2.call(this,system)||this;_this37.m_step=step;return _this37;}var _proto106=b2ParticleSystem_SolveCollisionCallback.prototype;_proto106.ReportFixtureAndParticle=function ReportFixtureAndParticle(fixture,childIndex,a){var s_p1=b2ParticleSystem_SolveCollisionCallback.ReportFixtureAndParticle_s_p1;var s_output=b2ParticleSystem_SolveCollisionCallback.ReportFixtureAndParticle_s_output;var s_input=b2ParticleSystem_SolveCollisionCallback.ReportFixtureAndParticle_s_input;var s_p=b2ParticleSystem_SolveCollisionCallback.ReportFixtureAndParticle_s_p;var s_v=b2ParticleSystem_SolveCollisionCallback.ReportFixtureAndParticle_s_v;var s_f=b2ParticleSystem_SolveCollisionCallback.ReportFixtureAndParticle_s_f;var body=fixture.GetBody();var ap=this.m_system.m_positionBuffer.data[a];var av=this.m_system.m_velocityBuffer.data[a];var output=s_output;var input=s_input;if(this.m_system.m_iterationIndex===0){var 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)){var n=output.normal;var 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;var 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);var 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);}};_proto106.ReportParticle=function ReportParticle(system,index){return false;};return b2ParticleSystem_SolveCollisionCallback;}(b2FixtureParticleQueryCallback);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();var b2World=function(){function b2World(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);}var _proto107=b2World.prototype;_proto107.SetDestructionListener=function SetDestructionListener(listener){this.m_destructionListener=listener;};_proto107.SetContactFilter=function SetContactFilter(filter){this.m_contactManager.m_contactFilter=filter;};_proto107.SetContactListener=function SetContactListener(listener){this.m_contactManager.m_contactListener=listener;};_proto107.SetDebugDraw=function SetDebugDraw(debugDraw){this.m_debugDraw=debugDraw;};_proto107.CreateBody=function CreateBody(def){if(def===void 0){def={};}if(this.IsLocked()){throw new Error();}var 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;};_proto107.DestroyBody=function DestroyBody(b){if(this.IsLocked()){throw new Error();}var je=b.m_jointList;while(je){var 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;var coe=b.m_controllerList;while(coe){var coe0=coe;coe=coe.nextController;coe0.controller.RemoveBody(b);}var ce=b.m_contactList;while(ce){var ce0=ce;ce=ce.next;this.m_contactManager.Destroy(ce0.contact);}b.m_contactList=null;var f=b.m_fixtureList;while(f){var 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;};b2World._Joint_Create=function _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();};b2World._Joint_Destroy=function _Joint_Destroy(joint){};_proto107.CreateJoint=function CreateJoint(def){if(this.IsLocked()){throw new Error();}var 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;var bodyA=j.m_bodyA;var bodyB=j.m_bodyB;var collideConnected=j.m_collideConnected;if(!collideConnected){var edge=bodyB.GetContactList();while(edge){if(edge.other===bodyA){edge.contact.FlagForFiltering();}edge=edge.next;}}return j;};_proto107.DestroyJoint=function 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;}var bodyA=j.m_bodyA;var bodyB=j.m_bodyB;var 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){var edge=bodyB.GetContactList();while(edge){if(edge.other===bodyA){edge.contact.FlagForFiltering();}edge=edge.next;}}};_proto107.CreateParticleSystem=function CreateParticleSystem(def){if(this.IsLocked()){throw new Error();}var 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;};_proto107.DestroyParticleSystem=function 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;}};_proto107.CalculateReasonableParticleIterations=function CalculateReasonableParticleIterations(timeStep){if(this.m_particleSystemList===null){return 1;}function GetSmallestRadius(world){var smallestRadius=b2_maxFloat;for(var 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);};_proto107.Step=function Step(dt,velocityIterations,positionIterations,particleIterations){if(particleIterations===void 0){particleIterations=this.CalculateReasonableParticleIterations(dt);}var stepTimer=b2World.Step_s_stepTimer.Reset();if(this.m_newFixture){this.m_contactManager.FindNewContacts();this.m_newFixture=false;}this.m_locked=true;var 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;var timer=b2World.Step_s_timer.Reset();this.m_contactManager.Collide();this.m_profile.collide=timer.GetMilliseconds();if(this.m_stepComplete&&step.dt>0){var _timer=b2World.Step_s_timer.Reset();for(var 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){var _timer2=b2World.Step_s_timer.Reset();this.SolveTOI(step);this.m_profile.solveTOI=_timer2.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();};_proto107.ClearForces=function ClearForces(){for(var body=this.m_bodyList;body;body=body.m_next){body.m_force.SetZero();body.m_torque=0;}};_proto107.DrawParticleSystem=function DrawParticleSystem(system){if(this.m_debugDraw===null){return;}var particleCount=system.GetParticleCount();if(particleCount){var radius=system.GetRadius();var positionBuffer=system.GetPositionBuffer();if(system.m_colorBuffer.data){var colorBuffer=system.GetColorBuffer();this.m_debugDraw.DrawParticles(positionBuffer,radius,colorBuffer,particleCount);}else {this.m_debugDraw.DrawParticles(positionBuffer,radius,null,particleCount);}}};_proto107.DrawDebugData=function DrawDebugData(){if(this.m_debugDraw===null){return;}var flags=this.m_debugDraw.GetFlags();var color=b2World.DrawDebugData_s_color.SetRGB(0,0,0);if(flags&exports.b2DrawFlags.e_shapeBit){for(var b=this.m_bodyList;b;b=b.m_next){var xf=b.m_xf;this.m_debugDraw.PushTransform(xf);for(var 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(var p=this.m_particleSystemList;p;p=p.m_next){this.DrawParticleSystem(p);}}if(flags&exports.b2DrawFlags.e_jointBit){for(var 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);var vs=b2World.DrawDebugData_s_vs;for(var _b15=this.m_bodyList;_b15;_b15=_b15.m_next){if(!_b15.IsActive()){continue;}for(var _f7=_b15.GetFixtureList();_f7;_f7=_f7.m_next){for(var i=0;i<_f7.m_proxyCount;++i){var proxy=_f7.m_proxies[i];var 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(var _b16=this.m_bodyList;_b16;_b16=_b16.m_next){var _xf=b2World.DrawDebugData_s_xf;_xf.q.Copy(_b16.m_xf.q);_xf.p.Copy(_b16.GetWorldCenter());this.m_debugDraw.DrawTransform(_xf);}}if(flags&exports.b2DrawFlags.e_controllerBit){for(var c=this.m_controllerList;c;c=c.m_next){c.Draw(this.m_debugDraw);}}};_proto107.QueryAABB=function QueryAABB(){if((arguments.length<=0?undefined:arguments[0])instanceof b2QueryCallback){this._QueryAABB(arguments.length<=0?undefined:arguments[0],arguments.length<=1?undefined:arguments[1]);}else {this._QueryAABB(null,arguments.length<=0?undefined:arguments[0],arguments.length<=1?undefined:arguments[1]);}};_proto107._QueryAABB=function _QueryAABB(callback,aabb,fn){this.m_contactManager.m_broadPhase.Query(aabb,function(proxy){var fixture_proxy=proxy.userData;var fixture=fixture_proxy.fixture;if(callback){return callback.ReportFixture(fixture);}else if(fn){return fn(fixture);}return true;});if(callback instanceof b2QueryCallback){for(var p=this.m_particleSystemList;p;p=p.m_next){if(callback.ShouldQueryParticleSystem(p)){p.QueryAABB(callback,aabb);}}}};_proto107.QueryAllAABB=function QueryAllAABB(aabb,out){if(out===void 0){out=[];}this.QueryAABB(aabb,function(fixture){out.push(fixture);return true;});return out;};_proto107.QueryPointAABB=function QueryPointAABB(){if((arguments.length<=0?undefined:arguments[0])instanceof b2QueryCallback){this._QueryPointAABB(arguments.length<=0?undefined:arguments[0],arguments.length<=1?undefined:arguments[1]);}else {this._QueryPointAABB(null,arguments.length<=0?undefined:arguments[0],arguments.length<=1?undefined:arguments[1]);}};_proto107._QueryPointAABB=function _QueryPointAABB(callback,point,fn){this.m_contactManager.m_broadPhase.QueryPoint(point,function(proxy){var fixture_proxy=proxy.userData;var fixture=fixture_proxy.fixture;if(callback){return callback.ReportFixture(fixture);}else if(fn){return fn(fixture);}return true;});if(callback instanceof b2QueryCallback){for(var p=this.m_particleSystemList;p;p=p.m_next){if(callback.ShouldQueryParticleSystem(p)){p.QueryPointAABB(callback,point);}}}};_proto107.QueryAllPointAABB=function QueryAllPointAABB(point,out){if(out===void 0){out=[];}this.QueryPointAABB(point,function(fixture){out.push(fixture);return true;});return out;};_proto107.QueryFixtureShape=function QueryFixtureShape(){if((arguments.length<=0?undefined:arguments[0])instanceof b2QueryCallback){this._QueryFixtureShape(arguments.length<=0?undefined:arguments[0],arguments.length<=1?undefined:arguments[1],arguments.length<=2?undefined:arguments[2],arguments.length<=3?undefined:arguments[3]);}else {this._QueryFixtureShape(null,arguments.length<=0?undefined:arguments[0],arguments.length<=1?undefined:arguments[1],arguments.length<=2?undefined:arguments[2],arguments.length<=3?undefined:arguments[3]);}};_proto107._QueryFixtureShape=function _QueryFixtureShape(callback,shape,index,transform,fn){var aabb=b2World.QueryFixtureShape_s_aabb;shape.ComputeAABB(aabb,transform,index);this.m_contactManager.m_broadPhase.Query(aabb,function(proxy){var fixture_proxy=proxy.userData;var 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(var p=this.m_particleSystemList;p;p=p.m_next){if(callback.ShouldQueryParticleSystem(p)){p.QueryAABB(callback,aabb);}}}};_proto107.QueryAllFixtureShape=function QueryAllFixtureShape(shape,index,transform,out){if(out===void 0){out=[];}this.QueryFixtureShape(shape,index,transform,function(fixture){out.push(fixture);return true;});return out;};_proto107.QueryFixturePoint=function QueryFixturePoint(){if((arguments.length<=0?undefined:arguments[0])instanceof b2QueryCallback){this._QueryFixturePoint(arguments.length<=0?undefined:arguments[0],arguments.length<=1?undefined:arguments[1]);}else {this._QueryFixturePoint(null,arguments.length<=0?undefined:arguments[0],arguments.length<=1?undefined:arguments[1]);}};_proto107._QueryFixturePoint=function _QueryFixturePoint(callback,point,fn){this.m_contactManager.m_broadPhase.QueryPoint(point,function(proxy){var fixture_proxy=proxy.userData;var 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(var p=this.m_particleSystemList;p;p=p.m_next){if(callback.ShouldQueryParticleSystem(p)){p.QueryPointAABB(callback,point);}}}};_proto107.QueryAllFixturePoint=function QueryAllFixturePoint(point,out){if(out===void 0){out=[];}this.QueryFixturePoint(point,function(fixture){out.push(fixture);return true;});return out;};_proto107.RayCast=function RayCast(){if((arguments.length<=0?undefined:arguments[0])instanceof b2RayCastCallback){this._RayCast(arguments.length<=0?undefined:arguments[0],arguments.length<=1?undefined:arguments[1],arguments.length<=2?undefined:arguments[2]);}else {this._RayCast(null,arguments.length<=0?undefined:arguments[0],arguments.length<=1?undefined:arguments[1],arguments.length<=2?undefined:arguments[2]);}};_proto107._RayCast=function _RayCast(callback,point1,point2,fn){var input=b2World.RayCast_s_input;input.maxFraction=1;input.p1.Copy(point1);input.p2.Copy(point2);this.m_contactManager.m_broadPhase.RayCast(input,function(input,proxy){var fixture_proxy=proxy.userData;var fixture=fixture_proxy.fixture;var index=fixture_proxy.childIndex;var output=b2World.RayCast_s_output;var hit=fixture.RayCast(output,input,index);if(hit){var fraction=output.fraction;var 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(var p=this.m_particleSystemList;p;p=p.m_next){if(callback.ShouldQueryParticleSystem(p)){p.RayCast(callback,point1,point2);}}}};_proto107.RayCastOne=function RayCastOne(point1,point2){var result=null;var min_fraction=1;this.RayCast(point1,point2,function(fixture,point,normal,fraction){if(fraction<min_fraction){min_fraction=fraction;result=fixture;}return min_fraction;});return result;};_proto107.RayCastAll=function RayCastAll(point1,point2,out){if(out===void 0){out=[];}this.RayCast(point1,point2,function(fixture,point,normal,fraction){out.push(fixture);return 1;});return out;};_proto107.GetBodyList=function GetBodyList(){return this.m_bodyList;};_proto107.GetJointList=function GetJointList(){return this.m_jointList;};_proto107.GetParticleSystemList=function GetParticleSystemList(){return this.m_particleSystemList;};_proto107.GetContactList=function GetContactList(){return this.m_contactManager.m_contactList;};_proto107.SetAllowSleeping=function SetAllowSleeping(flag){if(flag===this.m_allowSleep){return;}this.m_allowSleep=flag;if(!this.m_allowSleep){for(var b=this.m_bodyList;b;b=b.m_next){b.SetAwake(true);}}};_proto107.GetAllowSleeping=function GetAllowSleeping(){return this.m_allowSleep;};_proto107.SetWarmStarting=function SetWarmStarting(flag){this.m_warmStarting=flag;};_proto107.GetWarmStarting=function GetWarmStarting(){return this.m_warmStarting;};_proto107.SetContinuousPhysics=function SetContinuousPhysics(flag){this.m_continuousPhysics=flag;};_proto107.GetContinuousPhysics=function GetContinuousPhysics(){return this.m_continuousPhysics;};_proto107.SetSubStepping=function SetSubStepping(flag){this.m_subStepping=flag;};_proto107.GetSubStepping=function GetSubStepping(){return this.m_subStepping;};_proto107.GetProxyCount=function GetProxyCount(){return this.m_contactManager.m_broadPhase.GetProxyCount();};_proto107.GetBodyCount=function GetBodyCount(){return this.m_bodyCount;};_proto107.GetJointCount=function GetJointCount(){return this.m_jointCount;};_proto107.GetContactCount=function GetContactCount(){return this.m_contactManager.m_contactCount;};_proto107.GetTreeHeight=function GetTreeHeight(){return this.m_contactManager.m_broadPhase.GetTreeHeight();};_proto107.GetTreeBalance=function GetTreeBalance(){return this.m_contactManager.m_broadPhase.GetTreeBalance();};_proto107.GetTreeQuality=function GetTreeQuality(){return this.m_contactManager.m_broadPhase.GetTreeQuality();};_proto107.SetGravity=function SetGravity(gravity,wake){if(wake===void 0){wake=true;}if(!b2Vec2.IsEqualToV(this.m_gravity,gravity)){this.m_gravity.Copy(gravity);if(wake){for(var b=this.m_bodyList;b;b=b.m_next){b.SetAwake(true);}}}};_proto107.GetGravity=function GetGravity(){return this.m_gravity;};_proto107.IsLocked=function IsLocked(){return this.m_locked;};_proto107.SetAutoClearForces=function SetAutoClearForces(flag){this.m_clearForces=flag;};_proto107.GetAutoClearForces=function GetAutoClearForces(){return this.m_clearForces;};_proto107.ShiftOrigin=function ShiftOrigin(newOrigin){if(this.IsLocked()){throw new Error();}for(var 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(var j=this.m_jointList;j;j=j.m_next){j.ShiftOrigin(newOrigin);}this.m_contactManager.m_broadPhase.ShiftOrigin(newOrigin);};_proto107.GetContactManager=function GetContactManager(){return this.m_contactManager;};_proto107.GetProfile=function GetProfile(){return this.m_profile;};_proto107.Dump=function 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");var i=0;for(var b=this.m_bodyList;b;b=b.m_next){b.m_islandIndex=i;b.Dump(log);++i;}i=0;for(var j=this.m_jointList;j;j=j.m_next){j.m_index=i;++i;}for(var _j5=this.m_jointList;_j5;_j5=_j5.m_next){if(_j5.m_type===exports.b2JointType.e_gearJoint){continue;}log("{\n");_j5.Dump(log);log("}\n");}for(var _j6=this.m_jointList;_j6;_j6=_j6.m_next){if(_j6.m_type!==exports.b2JointType.e_gearJoint){continue;}log("{\n");_j6.Dump(log);log("}\n");}};_proto107.DrawJoint=function DrawJoint(joint){if(this.m_debugDraw===null){return;}var bodyA=joint.GetBodyA();var bodyB=joint.GetBodyB();var xf1=bodyA.m_xf;var xf2=bodyB.m_xf;var x1=xf1.p;var x2=xf2.p;var p1=joint.GetAnchorA(b2World.DrawJoint_s_p1);var p2=joint.GetAnchorB(b2World.DrawJoint_s_p2);var 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:{var pulley=joint;var s1=pulley.GetGroundAnchorA();var 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:{var 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);}};_proto107.DrawShape=function DrawShape(fixture,color){if(this.m_debugDraw===null){return;}var shape=fixture.GetShape();switch(shape.m_type){case exports.b2ShapeType.e_circleShape:{var circle=shape;var center=circle.m_p;var radius=circle.m_radius;var axis=b2Vec2.UNITX;this.m_debugDraw.DrawSolidCircle(center,radius,axis,color);break;}case exports.b2ShapeType.e_edgeShape:{var edge=shape;var v1=edge.m_vertex1;var v2=edge.m_vertex2;this.m_debugDraw.DrawSegment(v1,v2,color);break;}case exports.b2ShapeType.e_chainShape:{var chain=shape;var count=chain.m_count;var vertices=chain.m_vertices;var ghostColor=b2World.DrawShape_s_ghostColor.SetRGBA(0.75*color.r,0.75*color.g,0.75*color.b,color.a);var _v7=vertices[0];this.m_debugDraw.DrawPoint(_v7,4.0,color);if(chain.m_hasPrevVertex){var vp=chain.m_prevVertex;this.m_debugDraw.DrawSegment(vp,_v7,ghostColor);this.m_debugDraw.DrawCircle(vp,0.1,ghostColor);}for(var i=1;i<count;++i){var _v8=vertices[i];this.m_debugDraw.DrawSegment(_v7,_v8,color);this.m_debugDraw.DrawPoint(_v8,4.0,color);_v7=_v8;}if(chain.m_hasNextVertex){var vn=chain.m_nextVertex;this.m_debugDraw.DrawSegment(vn,_v7,ghostColor);this.m_debugDraw.DrawCircle(vn,0.1,ghostColor);}break;}case exports.b2ShapeType.e_polygonShape:{var poly=shape;var vertexCount=poly.m_count;var _vertices4=poly.m_vertices;this.m_debugDraw.DrawSolidPolygon(_vertices4,vertexCount,color);break;}}};_proto107.Solve=function Solve(step){for(var b=this.m_bodyList;b;b=b.m_next){b.m_xf0.Copy(b.m_xf);}for(var 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;var island=this.m_island;island.Initialize(this.m_bodyCount,this.m_contactManager.m_contactCount,this.m_jointCount,this.m_contactManager.m_contactListener);for(var _b17=this.m_bodyList;_b17;_b17=_b17.m_next){_b17.m_islandFlag=false;}for(var c=this.m_contactManager.m_contactList;c;c=c.m_next){c.m_islandFlag=false;}for(var j=this.m_jointList;j;j=j.m_next){j.m_islandFlag=false;}var stack=this.s_stack;for(var 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();var stackCount=0;stack[stackCount++]=seed;seed.m_islandFlag=true;while(stackCount>0){var _b18=stack[--stackCount];if(!_b18){throw new Error();}island.AddBody(_b18);_b18.m_awakeFlag=true;if(_b18.GetType()===exports.b2BodyType.b2_staticBody){continue;}for(var ce=_b18.m_contactList;ce;ce=ce.next){var contact=ce.contact;if(contact.m_islandFlag){continue;}if(!contact.IsEnabled()||!contact.IsTouching()){continue;}var sensorA=contact.m_fixtureA.m_isSensor;var sensorB=contact.m_fixtureB.m_isSensor;if(sensorA||sensorB){continue;}island.AddContact(contact);contact.m_islandFlag=true;var other=ce.other;if(other.m_islandFlag){continue;}stack[stackCount++]=other;other.m_islandFlag=true;}for(var je=_b18.m_jointList;je;je=je.next){if(je.joint.m_islandFlag){continue;}var _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;}}var 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(var i=0;i<island.m_bodyCount;++i){var _b19=island.m_bodies[i];if(_b19.GetType()===exports.b2BodyType.b2_staticBody){_b19.m_islandFlag=false;}}}for(var _i41=0;_i41<stack.length;++_i41){if(!stack[_i41]){break;}stack[_i41]=null;}var timer=new b2Timer();for(var _b20=this.m_bodyList;_b20;_b20=_b20.m_next){if(!_b20.m_islandFlag){continue;}if(_b20.GetType()===exports.b2BodyType.b2_staticBody){continue;}_b20.SynchronizeFixtures();}this.m_contactManager.FindNewContacts();this.m_profile.broadphase=timer.GetMilliseconds();};_proto107.SolveTOI=function SolveTOI(step){var island=this.m_island;island.Initialize(2*b2_maxTOIContacts,b2_maxTOIContacts,0,this.m_contactManager.m_contactListener);if(this.m_stepComplete){for(var b=this.m_bodyList;b;b=b.m_next){b.m_islandFlag=false;b.m_sweep.alpha0=0;}for(var 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(;;){var minContact=null;var minAlpha=1;for(var _c=this.m_contactManager.m_contactList;_c;_c=_c.m_next){if(!_c.IsEnabled()){continue;}if(_c.m_toiCount>b2_maxSubSteps){continue;}var alpha=1;if(_c.m_toiFlag){alpha=_c.m_toi;}else {var _fA=_c.GetFixtureA();var _fB=_c.GetFixtureB();if(_fA.IsSensor()||_fB.IsSensor()){continue;}var _bA=_fA.GetBody();var _bB=_fB.GetBody();var typeA=_bA.m_type;var typeB=_bB.m_type;var activeA=_bA.IsAwake()&&typeA!==exports.b2BodyType.b2_staticBody;var activeB=_bB.IsAwake()&&typeB!==exports.b2BodyType.b2_staticBody;if(!activeA&&!activeB){continue;}var collideA=_bA.IsBullet()||typeA!==exports.b2BodyType.b2_dynamicBody;var collideB=_bB.IsBullet()||typeB!==exports.b2BodyType.b2_dynamicBody;if(!collideA&&!collideB){continue;}var 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);}var indexA=_c.GetChildIndexA();var indexB=_c.GetChildIndexB();var 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;var output=b2World.SolveTOI_s_toi_output;b2TimeOfImpact(output,input);var 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;}var fA=minContact.GetFixtureA();var fB=minContact.GetFixtureB();var bA=fA.GetBody();var bB=fB.GetBody();var backup1=b2World.SolveTOI_s_backup1.Copy(bA.m_sweep);var 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(var i=0;i<2;++i){var body=i===0?bA:bB;if(body.m_type===exports.b2BodyType.b2_dynamicBody){for(var ce=body.m_contactList;ce;ce=ce.next){if(island.m_bodyCount===island.m_bodyCapacity){break;}if(island.m_contactCount===island.m_contactCapacity){break;}var contact=ce.contact;if(contact.m_islandFlag){continue;}var other=ce.other;if(other.m_type===exports.b2BodyType.b2_dynamicBody&&!body.IsBullet()&&!other.IsBullet()){continue;}var sensorA=contact.m_fixtureA.m_isSensor;var sensorB=contact.m_fixtureB.m_isSensor;if(sensorA||sensorB){continue;}var 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);}}}var 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(var _i42=0;_i42<island.m_bodyCount;++_i42){var _body3=island.m_bodies[_i42];_body3.m_islandFlag=false;if(_body3.m_type!==exports.b2BodyType.b2_dynamicBody){continue;}_body3.SynchronizeFixtures();for(var _ce=_body3.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;}}};_proto107.AddController=function 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;};_proto107.RemoveController=function 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;};return b2World;}();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();var b2ControllerEdge=function b2ControllerEdge(controller,body){this.prevBody=null;this.nextBody=null;this.prevController=null;this.nextController=null;this.controller=controller;this.body=body;};var b2Controller=function(){function b2Controller(){this.m_bodyList=null;this.m_bodyCount=0;this.m_prev=null;this.m_next=null;}var _proto108=b2Controller.prototype;_proto108.GetNext=function GetNext(){return this.m_next;};_proto108.GetPrev=function GetPrev(){return this.m_prev;};_proto108.GetBodyList=function GetBodyList(){return this.m_bodyList;};_proto108.AddBody=function AddBody(body){var 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;};_proto108.RemoveBody=function RemoveBody(body){if(this.m_bodyCount<=0){throw new Error();}var 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;};_proto108.Clear=function Clear(){while(this.m_bodyList){this.RemoveBody(this.m_bodyList.body);}this.m_bodyCount=0;};return b2Controller;}();var b2BuoyancyController=function(_b2Controller){_inheritsLoose(b2BuoyancyController,_b2Controller);function b2BuoyancyController(){var _this38;_this38=_b2Controller.apply(this,arguments)||this;_this38.normal=new b2Vec2(0,1);_this38.offset=0;_this38.density=0;_this38.velocity=new b2Vec2(0,0);_this38.linearDrag=0;_this38.angularDrag=0;_this38.useDensity=false;_this38.useWorldGravity=true;_this38.gravity=new b2Vec2(0,0);return _this38;}var _proto109=b2BuoyancyController.prototype;_proto109.Step=function Step(step){if(!this.m_bodyList){return;}if(this.useWorldGravity){this.gravity.Copy(this.m_bodyList.body.GetWorld().GetGravity());}for(var i=this.m_bodyList;i;i=i.nextBody){var body=i.body;if(!body.IsAwake()){continue;}var areac=new b2Vec2();var massc=new b2Vec2();var area=0;var mass=0;for(var fixture=body.GetFixtureList();fixture;fixture=fixture.m_next){var sc=new b2Vec2();var sarea=fixture.GetShape().ComputeSubmergedArea(this.normal,this.offset,body.GetTransform(),sc);area+=sarea;areac.x+=sarea*sc.x;areac.y+=sarea*sc.y;var 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;}var buoyancyForce=this.gravity.Clone().SelfNeg();buoyancyForce.SelfMul(this.density*area);body.ApplyForce(buoyancyForce,massc);var 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);}};_proto109.Draw=function Draw(debugDraw){var r=100;var p1=new b2Vec2();var 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;var color=new b2Color(0,0,0.8);debugDraw.DrawSegment(p1,p2,color);};return b2BuoyancyController;}(b2Controller);var b2ConstantAccelController=function(_b2Controller2){_inheritsLoose(b2ConstantAccelController,_b2Controller2);function b2ConstantAccelController(){var _this39;_this39=_b2Controller2.apply(this,arguments)||this;_this39.A=new b2Vec2(0,0);return _this39;}var _proto110=b2ConstantAccelController.prototype;_proto110.Step=function Step(step){var dtA=b2Vec2.MulSV(step.dt,this.A,b2ConstantAccelController.Step_s_dtA);for(var i=this.m_bodyList;i;i=i.nextBody){var body=i.body;if(!body.IsAwake()){continue;}body.SetLinearVelocity(b2Vec2.AddVV(body.GetLinearVelocity(),dtA,b2Vec2.s_t0));}};_proto110.Draw=function Draw(draw){};return b2ConstantAccelController;}(b2Controller);b2ConstantAccelController.Step_s_dtA=new b2Vec2();var b2ConstantForceController=function(_b2Controller3){_inheritsLoose(b2ConstantForceController,_b2Controller3);function b2ConstantForceController(){var _this40;_this40=_b2Controller3.apply(this,arguments)||this;_this40.F=new b2Vec2(0,0);return _this40;}var _proto111=b2ConstantForceController.prototype;_proto111.Step=function Step(step){for(var i=this.m_bodyList;i;i=i.nextBody){var body=i.body;if(!body.IsAwake()){continue;}body.ApplyForce(this.F,body.GetWorldCenter());}};_proto111.Draw=function Draw(draw){};return b2ConstantForceController;}(b2Controller);var b2GravityController=function(_b2Controller4){_inheritsLoose(b2GravityController,_b2Controller4);function b2GravityController(){var _this41;_this41=_b2Controller4.apply(this,arguments)||this;_this41.G=1;_this41.invSqr=true;return _this41;}var _proto112=b2GravityController.prototype;_proto112.Step=function Step(step){if(this.invSqr){for(var i=this.m_bodyList;i;i=i.nextBody){var body1=i.body;var p1=body1.GetWorldCenter();var mass1=body1.GetMass();for(var j=this.m_bodyList;j&&j!==i;j=j.nextBody){var body2=j.body;var p2=body2.GetWorldCenter();var mass2=body2.GetMass();var dx=p2.x-p1.x;var dy=p2.y-p1.y;var r2=dx*dx+dy*dy;if(r2<b2_epsilon){continue;}var 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(var _i43=this.m_bodyList;_i43;_i43=_i43.nextBody){var _body4=_i43.body;var _p2=_body4.GetWorldCenter();var _mass2=_body4.GetMass();for(var _j7=this.m_bodyList;_j7&&_j7!==_i43;_j7=_j7.nextBody){var _body5=_j7.body;var _p3=_body5.GetWorldCenter();var _mass3=_body5.GetMass();var _dx=_p3.x-_p2.x;var _dy=_p3.y-_p2.y;var _r=_dx*_dx+_dy*_dy;if(_r<b2_epsilon){continue;}var _f8=b2GravityController.Step_s_f.Set(_dx,_dy);_f8.SelfMul(this.G/_r*_mass2*_mass3);if(_body4.IsAwake()){_body4.ApplyForce(_f8,_p2);}if(_body5.IsAwake()){_body5.ApplyForce(_f8.SelfMul(-1),_p3);}}}}};_proto112.Draw=function Draw(draw){};return b2GravityController;}(b2Controller);b2GravityController.Step_s_f=new b2Vec2();var b2TensorDampingController=function(_b2Controller5){_inheritsLoose(b2TensorDampingController,_b2Controller5);function b2TensorDampingController(){var _this42;_this42=_b2Controller5.apply(this,arguments)||this;_this42.T=new b2Mat22();_this42.maxTimestep=0;return _this42;}var _proto113=b2TensorDampingController.prototype;_proto113.Step=function Step(step){var timestep=step.dt;if(timestep<=b2_epsilon){return;}if(timestep>this.maxTimestep&&this.maxTimestep>0){timestep=this.maxTimestep;}for(var i=this.m_bodyList;i;i=i.nextBody){var body=i.body;if(!body.IsAwake()){continue;}var 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));}};_proto113.Draw=function Draw(draw){};_proto113.SetAxisAligned=function 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;}};return b2TensorDampingController;}(b2Controller);b2TensorDampingController.Step_s_damping=new b2Vec2();var b2RopeDef=function b2RopeDef(){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;};var b2Rope=function(){function b2Rope(){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;}var _proto114=b2Rope.prototype;_proto114.GetVertexCount=function GetVertexCount(){return this.m_count;};_proto114.GetVertices=function GetVertices(){return this.m_ps;};_proto114.Initialize=function 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(var 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();var m=def.masses[i];if(m>0){this.m_ims[i]=1/m;}else {this.m_ims[i]=0;}}var count2=this.m_count-1;var count3=this.m_count-2;this.m_Ls=b2MakeNumberArray(count2);this.m_as=b2MakeNumberArray(count3);for(var _i44=0;_i44<count2;++_i44){var p1=this.m_ps[_i44];var p2=this.m_ps[_i44+1];this.m_Ls[_i44]=b2Vec2.DistanceVV(p1,p2);}for(var _i45=0;_i45<count3;++_i45){var _p4=this.m_ps[_i45];var _p5=this.m_ps[_i45+1];var p3=this.m_ps[_i45+2];var d1=b2Vec2.SubVV(_p5,_p4,b2Vec2.s_t0);var d2=b2Vec2.SubVV(p3,_p5,b2Vec2.s_t1);var a=b2Vec2.CrossVV(d1,d2);var b=b2Vec2.DotVV(d1,d2);this.m_as[_i45]=b2Atan2(a,b);}this.m_gravity.Copy(def.gravity);this.m_damping=def.damping;this.m_k2=def.k2;this.m_k3=def.k3;};_proto114.Step=function Step(h,iterations){if(h===0){return;}var d=Math.exp(-h*this.m_damping);for(var 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(var _i46=0;_i46<iterations;++_i46){this.SolveC2();this.SolveC3();this.SolveC2();}var inv_h=1/h;for(var _i47=0;_i47<this.m_count;++_i47){b2Vec2.MulSV(inv_h,b2Vec2.SubVV(this.m_ps[_i47],this.m_p0s[_i47],b2Vec2.s_t0),this.m_vs[_i47]);}};_proto114.SolveC2=function SolveC2(){var count2=this.m_count-1;for(var i=0;i<count2;++i){var p1=this.m_ps[i];var p2=this.m_ps[i+1];var d=b2Vec2.SubVV(p2,p1,b2Rope.s_d);var L=d.Normalize();var im1=this.m_ims[i];var im2=this.m_ims[i+1];if(im1+im2===0){continue;}var s1=im1/(im1+im2);var 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);}};_proto114.SetAngle=function SetAngle(angle){var count3=this.m_count-2;for(var i=0;i<count3;++i){this.m_as[i]=angle;}};_proto114.SolveC3=function SolveC3(){var count3=this.m_count-2;for(var i=0;i<count3;++i){var p1=this.m_ps[i];var p2=this.m_ps[i+1];var p3=this.m_ps[i+2];var m1=this.m_ims[i];var m2=this.m_ims[i+1];var m3=this.m_ims[i+2];var d1=b2Vec2.SubVV(p2,p1,b2Rope.s_d1);var d2=b2Vec2.SubVV(p3,p2,b2Rope.s_d2);var L1sqr=d1.LengthSquared();var L2sqr=d2.LengthSquared();if(L1sqr*L2sqr===0){continue;}var a=b2Vec2.CrossVV(d1,d2);var b=b2Vec2.DotVV(d1,d2);var angle=b2Atan2(a,b);var Jd1=b2Vec2.MulSV(-1/L1sqr,d1.SelfSkew(),b2Rope.s_Jd1);var Jd2=b2Vec2.MulSV(1/L2sqr,d2.SelfSkew(),b2Rope.s_Jd2);var J1=b2Vec2.NegV(Jd1,b2Rope.s_J1);var J2=b2Vec2.SubVV(Jd1,Jd2,b2Rope.s_J2);var J3=Jd2;var mass=m1*b2Vec2.DotVV(J1,J1)+m2*b2Vec2.DotVV(J2,J2)+m3*b2Vec2.DotVV(J3,J3);if(mass===0){continue;}mass=1/mass;var 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];}var impulse=-this.m_k3*mass*C;p1.SelfMulAdd(m1*impulse,J1);p2.SelfMulAdd(m2*impulse,J2);p3.SelfMulAdd(m3*impulse,J3);}};_proto114.Draw=function Draw(draw){var c=new b2Color(0.4,0.5,0.7);for(var i=0;i<this.m_count-1;++i){draw.DrawSegment(this.m_ps[i],this.m_ps[i+1],c);}};return b2Rope;}();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});});});unwrapExports(box2d_umd);

            var b2={};for(var key in box2d_umd){if(key.indexOf('b2_')!==-1){continue;}var newKey=key.replace('b2','');b2[newKey]=box2d_umd[key];}var box2d_1=b2;

            var ERigidBody2DType;

            (function (ERigidBody2DType) {
              ERigidBody2DType[ERigidBody2DType["Static"] = 0] = "Static";
              ERigidBody2DType[ERigidBody2DType["Kinematic"] = 1] = "Kinematic";
              ERigidBody2DType[ERigidBody2DType["Dynamic"] = 2] = "Dynamic";
              ERigidBody2DType[ERigidBody2DType["Animated"] = 3] = "Animated";
            })(ERigidBody2DType || (ERigidBody2DType = exports('ERigidBody2DType', {})));

            Enum(ERigidBody2DType);
            var ECollider2DType;

            (function (ECollider2DType) {
              ECollider2DType[ECollider2DType["None"] = 0] = "None";
              ECollider2DType[ECollider2DType["BOX"] = 1] = "BOX";
              ECollider2DType[ECollider2DType["CIRCLE"] = 2] = "CIRCLE";
              ECollider2DType[ECollider2DType["POLYGON"] = 3] = "POLYGON";
            })(ECollider2DType || (ECollider2DType = exports('ECollider2DType', {})));

            Enum(ECollider2DType);
            var EJoint2DType;

            (function (EJoint2DType) {
              EJoint2DType[EJoint2DType["None"] = 0] = "None";
              EJoint2DType[EJoint2DType["DISTANCE"] = 1] = "DISTANCE";
              EJoint2DType[EJoint2DType["SPRING"] = 2] = "SPRING";
              EJoint2DType[EJoint2DType["WHEEL"] = 3] = "WHEEL";
              EJoint2DType[EJoint2DType["MOUSE"] = 4] = "MOUSE";
              EJoint2DType[EJoint2DType["FIXED"] = 5] = "FIXED";
              EJoint2DType[EJoint2DType["SLIDER"] = 6] = "SLIDER";
              EJoint2DType[EJoint2DType["RELATIVE"] = 7] = "RELATIVE";
              EJoint2DType[EJoint2DType["HINGE"] = 8] = "HINGE";
            })(EJoint2DType || (EJoint2DType = exports('EJoint2DType', {})));

            Enum(EJoint2DType);
            var ERaycast2DType;

            (function (ERaycast2DType) {
              ERaycast2DType[ERaycast2DType["Closest"] = 0] = "Closest";
              ERaycast2DType[ERaycast2DType["Any"] = 1] = "Any";
              ERaycast2DType[ERaycast2DType["AllClosest"] = 2] = "AllClosest";
              ERaycast2DType[ERaycast2DType["All"] = 3] = "All";
            })(ERaycast2DType || (ERaycast2DType = exports('ERaycast2DType', {})));

            var Contact2DType = exports('Contact2DType', {
              None: 'none-contact',
              BEGIN_CONTACT: 'begin-contact',
              END_CONTACT: 'end-contact',
              PRE_SOLVE: 'pre-solve',
              POST_SOLVE: 'post-solve'
            });
            var EPhysics2DDrawFlags;

            (function (EPhysics2DDrawFlags) {
              EPhysics2DDrawFlags[EPhysics2DDrawFlags["None"] = 0] = "None";
              EPhysics2DDrawFlags[EPhysics2DDrawFlags["Shape"] = 1] = "Shape";
              EPhysics2DDrawFlags[EPhysics2DDrawFlags["Joint"] = 2] = "Joint";
              EPhysics2DDrawFlags[EPhysics2DDrawFlags["Aabb"] = 4] = "Aabb";
              EPhysics2DDrawFlags[EPhysics2DDrawFlags["Pair"] = 8] = "Pair";
              EPhysics2DDrawFlags[EPhysics2DDrawFlags["CenterOfMass"] = 16] = "CenterOfMass";
              EPhysics2DDrawFlags[EPhysics2DDrawFlags["Particle"] = 32] = "Particle";
              EPhysics2DDrawFlags[EPhysics2DDrawFlags["Controller"] = 64] = "Controller";
              EPhysics2DDrawFlags[EPhysics2DDrawFlags["All"] = 63] = "All";
            })(EPhysics2DDrawFlags || (EPhysics2DDrawFlags = exports('EPhysics2DDrawFlags', {})));

            var PHYSICS_2D_PTM_RATIO = exports('PHYSICS_2D_PTM_RATIO', 32);

            var PhysicsContactListener = function (_b2$ContactListener) {
              _inheritsLoose(PhysicsContactListener, _b2$ContactListener);

              function PhysicsContactListener() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _b2$ContactListener.call.apply(_b2$ContactListener, [this].concat(args)) || this;
                _this._contactFixtures = [];
                _this._BeginContact = null;
                _this._EndContact = null;
                _this._PreSolve = null;
                _this._PostSolve = null;
                return _this;
              }

              var _proto = PhysicsContactListener.prototype;

              _proto.setBeginContact = function setBeginContact(cb) {
                this._BeginContact = cb;
              };

              _proto.setEndContact = function setEndContact(cb) {
                this._EndContact = cb;
              };

              _proto.setPreSolve = function setPreSolve(cb) {
                this._PreSolve = cb;
              };

              _proto.setPostSolve = function setPostSolve(cb) {
                this._PostSolve = cb;
              };

              _proto.BeginContact = function BeginContact(contact) {
                if (!this._BeginContact) return;
                var fixtureA = contact.GetFixtureA();
                var fixtureB = contact.GetFixtureB();
                var fixtures = this._contactFixtures;
                contact._shouldReport = false;

                if (fixtures.indexOf(fixtureA) !== -1 || fixtures.indexOf(fixtureB) !== -1) {
                  contact._shouldReport = true;

                  this._BeginContact(contact);
                }
              };

              _proto.EndContact = function EndContact(contact) {
                if (this._EndContact && contact._shouldReport) {
                  contact._shouldReport = false;

                  this._EndContact(contact);
                }
              };

              _proto.PreSolve = function PreSolve(contact, oldManifold) {
                if (this._PreSolve && contact._shouldReport) {
                  this._PreSolve(contact, oldManifold);
                }
              };

              _proto.PostSolve = function PostSolve(contact, impulse) {
                if (this._PostSolve && contact._shouldReport) {
                  this._PostSolve(contact, impulse);
                }
              };

              _proto.registerContactFixture = function registerContactFixture(fixture) {
                this._contactFixtures.push(fixture);
              };

              _proto.unregisterContactFixture = function unregisterContactFixture(fixture) {
                remove(this._contactFixtures, fixture);
              };

              return PhysicsContactListener;
            }(box2d_1.ContactListener);

            var PhysicsAABBQueryCallback = function (_b2$QueryCallback) {
              _inheritsLoose(PhysicsAABBQueryCallback, _b2$QueryCallback);

              function PhysicsAABBQueryCallback() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _b2$QueryCallback.call.apply(_b2$QueryCallback, [this].concat(args)) || this;
                _this._point = new box2d_1.Vec2();
                _this._isPoint = false;
                _this._fixtures = [];
                return _this;
              }

              var _proto = PhysicsAABBQueryCallback.prototype;

              _proto.init = function 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;
              };

              _proto.ReportFixture = function ReportFixture(fixture) {
                if (this._isPoint) {
                  if (fixture.TestPoint(this._point)) {
                    this._fixtures.push(fixture);
                  }
                } else {
                  this._fixtures.push(fixture);
                }

                return true;
              };

              _proto.getFixture = function getFixture() {
                return this._fixtures[0];
              };

              _proto.getFixtures = function getFixtures() {
                return this._fixtures;
              };

              return PhysicsAABBQueryCallback;
            }(box2d_1.QueryCallback);

            function At(i, vertices) {
              var s = vertices.length;
              return vertices[i < 0 ? s - -i % s : i % s];
            }

            function Copy(i, j, vertices) {
              var p = [];

              while (j < i) {
                j += vertices.length;
              }

              for (; i <= j; ++i) {
                p.push(At(i, vertices));
              }

              return p;
            }

            function ConvexPartition(vertices) {
              ForceCounterClockWise(vertices);
              var list = [];
              var d;
              var lowerDist;
              var upperDist;
              var p;
              var lowerInt = new Vec2();
              var upperInt = new Vec2();
              var lowerIndex = 0;
              var upperIndex = 0;
              var lowerPoly;
              var upperPoly;

              for (var i = 0; i < vertices.length; ++i) {
                if (Reflex(i, vertices)) {
                  lowerDist = upperDist = 10e7;

                  for (var 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) {
                    var sp = lowerInt.add(upperInt).multiplyScalar(1 / 2);
                    lowerPoly = Copy(i, upperIndex, vertices);
                    lowerPoly.push(sp);
                    upperPoly = Copy(lowerIndex, i, vertices);
                    upperPoly.push(sp);
                  } else {
                    var highestScore = 0;
                    var bestIndex = lowerIndex;

                    while (upperIndex < lowerIndex) {
                      upperIndex += vertices.length;
                    }

                    for (var _j = lowerIndex; _j <= upperIndex; ++_j) {
                      if (CanSee(i, _j, vertices)) {
                        var 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(lowerPoly));
                  list = list.concat(ConvexPartition(upperPoly));
                  return list;
                }
              }

              list.push(vertices);

              for (var _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 (var k = 0; k < vertices.length; ++k) {
                if ((k + 1) % vertices.length == i || k == i || (k + 1) % vertices.length == j || k == j) {
                  continue;
                }

                var 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') {
                var i = a;
                var vertices = b;
                a = At(i - 1, vertices);
                b = At(i, vertices);
                c = At(i + 1, vertices);
              }

              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) {
              var dx = b.x - a.x;
              var dy = b.y - a.y;
              return dx * dx + dy * dy;
            }

            function ForceCounterClockWise(vertices) {
              if (!IsCounterClockWise(vertices)) {
                vertices.reverse();
              }
            }
            function IsCounterClockWise(vertices) {
              if (vertices.length < 3) return true;
              return GetSignedArea(vertices) > 0;
            }

            function GetSignedArea(vertices) {
              var i;
              var area = 0;

              for (i = 0; i < vertices.length; i++) {
                var 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) {
              var i = new Vec2();
              var a1 = p2.y - p1.y;
              var b1 = p1.x - p2.x;
              var c1 = a1 * p1.x + b1 * p1.y;
              var a2 = q2.y - q1.y;
              var b2 = q1.x - q2.x;
              var c2 = a2 * q1.x + b2 * q1.y;
              var 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;
              var x1 = a0.x;
              var y1 = a0.y;
              var x2 = a1.x;
              var y2 = a1.y;
              var x3 = b0.x;
              var y3 = b0.y;
              var x4 = b1.x;
              var 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;
              var ua = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3);
              var ub = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3);
              var 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,
                ForceCounterClockWise: ForceCounterClockWise,
                IsCounterClockWise: IsCounterClockWise
            });

            var FUNC = function FUNC() {
              return 0;
            };

            function checkPhysicsModule(obj) {
              if ( obj == null) {
                errorID(9600);
                return true;
              }

              return false;
            }
            function createPhysicsWorld() {
              if ( checkPhysicsModule(WRAPPER.PhysicsWorld)) {
                return null;
              }

              return new WRAPPER.PhysicsWorld();
            }
            var 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() {
              var PHYSICS_2D_BUILTIN = legacyCC._global.CC_PHYSICS_2D_BUILTIN;

              if (PHYSICS_2D_BUILTIN) {
                return EntireBody;
              } else {
                if ( checkPhysicsModule(WRAPPER.RigidBody)) {
                  return null;
                }

                return new WRAPPER.RigidBody();
              }
            }
            var CREATE_COLLIDER_PROXY = {
              INITED: false
            };
            var 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[ECollider2DType.BOX] = function createBoxShape() {
                if ( checkPhysicsModule(WRAPPER.BoxShape)) {
                  return ENTIRE_SHAPE;
                }

                return new WRAPPER.BoxShape();
              };

              CREATE_COLLIDER_PROXY[ECollider2DType.CIRCLE] = function createCircleShape() {
                if ( checkPhysicsModule(WRAPPER.CircleShape)) {
                  return ENTIRE_SHAPE;
                }

                return new WRAPPER.CircleShape();
              };

              CREATE_COLLIDER_PROXY[ECollider2DType.POLYGON] = function createPolygonShape() {
                if ( checkPhysicsModule(WRAPPER.PolygonShape)) {
                  return ENTIRE_SHAPE;
                }

                return new WRAPPER.PolygonShape();
              };
            }

            var CREATE_JOINT_PROXY = {
              INITED: false
            };
            var ENTIRE_JOINT = {
              impl: null,
              initialize: 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;
              var PHYSICS_2D_BUILTIN = legacyCC._global.CC_PHYSICS_2D_BUILTIN;

              CREATE_JOINT_PROXY[EJoint2DType.SPRING] = function createSpringJoint() {
                if (PHYSICS_2D_BUILTIN) {
                  return ENTIRE_JOINT;
                } else {
                  if ( checkPhysicsModule(WRAPPER.SpringJoint)) {
                    return ENTIRE_JOINT;
                  }

                  return new WRAPPER.SpringJoint();
                }
              };

              CREATE_JOINT_PROXY[EJoint2DType.DISTANCE] = function createDistanceJoint() {
                if (PHYSICS_2D_BUILTIN) {
                  return ENTIRE_JOINT;
                } else {
                  if ( checkPhysicsModule(WRAPPER.DistanceJoint)) {
                    return ENTIRE_JOINT;
                  }

                  return new WRAPPER.DistanceJoint();
                }
              };

              CREATE_JOINT_PROXY[EJoint2DType.FIXED] = function createFixedJoint() {
                if (PHYSICS_2D_BUILTIN) {
                  return ENTIRE_JOINT;
                } else {
                  if ( checkPhysicsModule(WRAPPER.FixedJoint)) {
                    return ENTIRE_JOINT;
                  }

                  return new WRAPPER.FixedJoint();
                }
              };

              CREATE_JOINT_PROXY[EJoint2DType.MOUSE] = function createMouseJoint() {
                if (PHYSICS_2D_BUILTIN) {
                  return ENTIRE_JOINT;
                } else {
                  if ( checkPhysicsModule(WRAPPER.MouseJoint)) {
                    return ENTIRE_JOINT;
                  }

                  return new WRAPPER.MouseJoint();
                }
              };

              CREATE_JOINT_PROXY[EJoint2DType.RELATIVE] = function createRelativeJoint() {
                if (PHYSICS_2D_BUILTIN) {
                  return ENTIRE_JOINT;
                } else {
                  if ( checkPhysicsModule(WRAPPER.RelativeJoint)) {
                    return ENTIRE_JOINT;
                  }

                  return new WRAPPER.RelativeJoint();
                }
              };

              CREATE_JOINT_PROXY[EJoint2DType.SLIDER] = function createSliderJoint() {
                if (PHYSICS_2D_BUILTIN) {
                  return ENTIRE_JOINT;
                } else {
                  if ( checkPhysicsModule(WRAPPER.SliderJoint)) {
                    return ENTIRE_JOINT;
                  }

                  return new WRAPPER.SliderJoint();
                }
              };

              CREATE_JOINT_PROXY[EJoint2DType.WHEEL] = function createWheelJoint() {
                if (PHYSICS_2D_BUILTIN) {
                  return ENTIRE_JOINT;
                } else {
                  if ( checkPhysicsModule(WRAPPER.WheelJoint)) {
                    return ENTIRE_JOINT;
                  }

                  return new WRAPPER.WheelJoint();
                }
              };

              CREATE_JOINT_PROXY[EJoint2DType.HINGE] = function createHingeJoint() {
                if (PHYSICS_2D_BUILTIN) {
                  return ENTIRE_JOINT;
                } else {
                  if ( checkPhysicsModule(WRAPPER.HingeJoint)) {
                    return ENTIRE_JOINT;
                  }

                  return new WRAPPER.HingeJoint();
                }
              };
            }

            var ERigidBodyType;

            (function (ERigidBodyType) {
              ERigidBodyType[ERigidBodyType["DYNAMIC"] = 1] = "DYNAMIC";
              ERigidBodyType[ERigidBodyType["STATIC"] = 2] = "STATIC";
              ERigidBodyType[ERigidBodyType["KINEMATIC"] = 4] = "KINEMATIC";
            })(ERigidBodyType || (ERigidBodyType = {}));

            Enum(ERigidBodyType);
            var EAxisDirection;

            (function (EAxisDirection) {
              EAxisDirection[EAxisDirection["X_AXIS"] = 0] = "X_AXIS";
              EAxisDirection[EAxisDirection["Y_AXIS"] = 1] = "Y_AXIS";
              EAxisDirection[EAxisDirection["Z_AXIS"] = 2] = "Z_AXIS";
            })(EAxisDirection || (EAxisDirection = {}));

            Enum(EAxisDirection);
            var ESimplexType;

            (function (ESimplexType) {
              ESimplexType[ESimplexType["VERTEX"] = 1] = "VERTEX";
              ESimplexType[ESimplexType["LINE"] = 2] = "LINE";
              ESimplexType[ESimplexType["TRIANGLE"] = 3] = "TRIANGLE";
              ESimplexType[ESimplexType["TETRAHEDRON"] = 4] = "TETRAHEDRON";
            })(ESimplexType || (ESimplexType = {}));

            Enum(ESimplexType);
            var EColliderType;

            (function (EColliderType) {
              EColliderType[EColliderType["BOX"] = 0] = "BOX";
              EColliderType[EColliderType["SPHERE"] = 1] = "SPHERE";
              EColliderType[EColliderType["CAPSULE"] = 2] = "CAPSULE";
              EColliderType[EColliderType["CYLINDER"] = 3] = "CYLINDER";
              EColliderType[EColliderType["CONE"] = 4] = "CONE";
              EColliderType[EColliderType["MESH"] = 5] = "MESH";
              EColliderType[EColliderType["PLANE"] = 6] = "PLANE";
              EColliderType[EColliderType["SIMPLEX"] = 7] = "SIMPLEX";
              EColliderType[EColliderType["TERRAIN"] = 8] = "TERRAIN";
            })(EColliderType || (EColliderType = {}));

            Enum(EColliderType);
            var EConstraintType;

            (function (EConstraintType) {
              EConstraintType[EConstraintType["POINT_TO_POINT"] = 0] = "POINT_TO_POINT";
              EConstraintType[EConstraintType["HINGE"] = 1] = "HINGE";
              EConstraintType[EConstraintType["CONE_TWIST"] = 2] = "CONE_TWIST";
            })(EConstraintType || (EConstraintType = {}));

            Enum(EConstraintType);
            var PhysicsGroup;

            (function (PhysicsGroup) {
              PhysicsGroup[PhysicsGroup["DEFAULT"] = 1] = "DEFAULT";
            })(PhysicsGroup || (PhysicsGroup = {}));

            Enum(PhysicsGroup);

            var CollisionMatrix = function CollisionMatrix(strategy) {
              if (strategy === 1) {
                var self = this;

                var _loop = function _loop(i) {
                  var key = "_" + (1 << i);
                  self[key] = 0;
                  self.updateArray = [];
                  Object.defineProperty(self, 1 << i, {
                    get: function get() {
                      return this[key];
                    },
                    set: function set(v) {
                      if (this[key] !== v) {
                        this[key] = v;

                        if (this.updateArray.indexOf(i) < 0) {
                          this.updateArray.push(i);
                        }
                      }
                    }
                  });
                };

                for (var i = 0; i < 32; i++) {
                  _loop(i);
                }

                this['_1'] = PhysicsGroup.DEFAULT;
              } else {
                for (var _i = 0; _i < 32; _i++) {
                  var key = 1 << _i;
                  this["" + key] = 0;
                }

                this['1'] = PhysicsGroup.DEFAULT;
              }
            };

            var instance = null;
            var PhysicsSystem2D = exports('PhysicsSystem2D', function (_Eventify) {
              _inheritsLoose(PhysicsSystem2D, _Eventify);

              function PhysicsSystem2D() {
                var _this;

                _this = _Eventify.call(this) || this;
                _this.velocityIterations = 10;
                _this.positionIterations = 10;
                _this.physicsWorld = void 0;
                _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 = [];
                var config = game.config ? game.config.physics : null;

                if (config) {
                  Vec2.copy(_this._gravity, config.gravity);

                  _this._gravity.multiplyScalar(PHYSICS_2D_PTM_RATIO);

                  _this._allowSleep = config.allowSleep;
                  _this._fixedTimeStep = config.fixedTimeStep;
                  _this._maxSubSteps = config.maxSubSteps;
                  _this._autoSimulation = config.autoSimulation;

                  if (config.collisionMatrix) {
                    for (var i in config.collisionMatrix) {
                      var bit = parseInt(i);
                      var value = 1 << parseInt(i);
                      _this.collisionMatrix["" + value] = config.collisionMatrix[bit];
                    }
                  }
                }

                _this.physicsWorld = createPhysicsWorld();
                _this.gravity = _this._gravity;
                _this.allowSleep = _this._allowSleep;
                return _this;
              }

              var _proto = PhysicsSystem2D.prototype;

              _proto.postUpdate = function postUpdate(deltaTime) {
                if (!this._enable) {
                  return;
                }

                if (!this._autoSimulation) {
                  return;
                }

                director.emit(Director.EVENT_BEFORE_PHYSICS);
                this._steping = true;
                var fixedTimeStep = this._fixedTimeStep;
                var velocityIterations = this.velocityIterations;
                var positionIterations = this.positionIterations;
                this._accumulator += deltaTime;
                var substepIndex = 0;

                while (substepIndex++ < this._maxSubSteps && this._accumulator > fixedTimeStep) {
                  this.physicsWorld.step(fixedTimeStep, velocityIterations, positionIterations);
                  this._accumulator -= fixedTimeStep;
                }

                var events = this._delayEvents;

                for (var i = 0, l = events.length; i < l; i++) {
                  var 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.EVENT_AFTER_PHYSICS);
              };

              _proto._callAfterStep = function _callAfterStep(target, func) {
                if (this._steping) {
                  this._delayEvents.push({
                    target: target,
                    func: func
                  });
                } else {
                  func.call(target);
                }
              };

              _proto.resetAccumulator = function resetAccumulator(time) {
                if (time === void 0) {
                  time = 0;
                }

                this._accumulator = time;
              };

              _proto.step = function step(fixedTimeStep) {
                this.physicsWorld.step(fixedTimeStep, this.velocityIterations, this.positionIterations);
              };

              _proto.raycast = function raycast(p1, p2, type, mask) {
                if (type === void 0) {
                  type = ERaycast2DType.Closest;
                }

                if (mask === void 0) {
                  mask = 0xffffffff;
                }

                return this.physicsWorld.raycast(p1, p2, type, mask);
              };

              _proto.testPoint = function testPoint(p) {
                return this.physicsWorld.testPoint(p);
              };

              _proto.testAABB = function testAABB(rect) {
                return this.physicsWorld.testAABB(rect);
              };

              _createClass(PhysicsSystem2D, [{
                key: "enable",
                get: function get() {
                  return this._enable;
                },
                set: function set(value) {
                  this._enable = value;
                }
              }, {
                key: "allowSleep",
                get: function get() {
                  return this._allowSleep;
                },
                set: function set(v) {
                  this._allowSleep = v;

                  {
                    this.physicsWorld.setAllowSleep(v);
                  }
                }
              }, {
                key: "gravity",
                get: function get() {
                  return this._gravity;
                },
                set: function set(gravity) {
                  this._gravity.set(gravity);

                  {
                    this.physicsWorld.setGravity(new Vec2(gravity.x / PHYSICS_2D_PTM_RATIO, gravity.y / PHYSICS_2D_PTM_RATIO));
                  }
                }
              }, {
                key: "maxSubSteps",
                get: function get() {
                  return this._maxSubSteps;
                },
                set: function set(value) {
                  this._maxSubSteps = value;
                }
              }, {
                key: "fixedTimeStep",
                get: function get() {
                  return this._fixedTimeStep;
                },
                set: function set(value) {
                  this._fixedTimeStep = value;
                }
              }, {
                key: "autoSimulation",
                get: function get() {
                  return this._autoSimulation;
                },
                set: function set(value) {
                  this._autoSimulation = value;
                }
              }, {
                key: "debugDrawFlags",
                get: function get() {
                  return this.physicsWorld.debugDrawFlags;
                },
                set: function set(v) {
                  this.physicsWorld.debugDrawFlags = v;
                }
              }, {
                key: "stepping",
                get: function get() {
                  return this._steping;
                }
              }], [{
                key: "PHYSICS_NONE",
                get: function get() {
                  return !physicsEngineId;
                }
              }, {
                key: "PHYSICS_BUILTIN",
                get: function get() {
                  return physicsEngineId === 'builtin';
                }
              }, {
                key: "PHYSICS_BOX2D",
                get: function get() {
                  return physicsEngineId === 'box2d';
                }
              }, {
                key: "instance",
                get: function get() {
                  if (!instance) {
                    instance = new PhysicsSystem2D();
                  }

                  return instance;
                }
              }]);

              return PhysicsSystem2D;
            }(Eventify(System$1)));
            PhysicsSystem2D.ID = 'PHYSICS_2D';
            director.once(Director.EVENT_INIT, function () {
              initPhysicsSystem();
            });

            function initPhysicsSystem() {
              if (!PhysicsSystem2D.PHYSICS_NONE && !EDITOR) {
                director.registerSystem(PhysicsSystem2D.ID, PhysicsSystem2D.instance, 0);
              }
            }

            var Physics2DManifoldType;

            (function (Physics2DManifoldType) {
              Physics2DManifoldType[Physics2DManifoldType["Circles"] = 0] = "Circles";
              Physics2DManifoldType[Physics2DManifoldType["FaceA"] = 1] = "FaceA";
              Physics2DManifoldType[Physics2DManifoldType["FaceB"] = 2] = "FaceB";
            })(Physics2DManifoldType || (Physics2DManifoldType = exports('Physics2DManifoldType', {})));

            var _dec$1o, _dec2$Z, _dec3$Q, _dec4$J, _class$1p, _class2$1d, _descriptor$12, _descriptor2$P, _descriptor3$B, _descriptor4$w, _descriptor5$q, _descriptor6$h, _descriptor7$f, _descriptor8$f, _descriptor9$e, _descriptor10$e, _descriptor11$d, _descriptor12$b, _temp$1g;
            var property$1 = property,
                type$1 = type,
                menu$1 = menu;
            var RigidBody2D = exports('RigidBody2D', (_dec$1o = ccclass('cc.RigidBody2D'), _dec2$Z = menu$1(), _dec3$Q = type$1(PhysicsGroup), _dec4$J = type$1(ERigidBody2DType), _dec$1o(_class$1p = _dec2$Z(_class$1p = (_class2$1d = (_temp$1g = function (_Component) {
              _inheritsLoose(RigidBody2D, _Component);

              function RigidBody2D() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Component.call.apply(_Component, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "enabledContactListener", _descriptor$12, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "bullet", _descriptor2$P, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "awakeOnLoad", _descriptor3$B, _assertThisInitialized(_this));

                _this._body = null;

                _initializerDefineProperty(_this, "_group", _descriptor4$w, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_type", _descriptor5$q, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_allowSleep", _descriptor6$h, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_gravityScale", _descriptor7$f, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_linearDamping", _descriptor8$f, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_angularDamping", _descriptor9$e, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_linearVelocity", _descriptor10$e, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_angularVelocity", _descriptor11$d, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_fixedRotation", _descriptor12$b, _assertThisInitialized(_this));

                return _this;
              }

              var _proto = RigidBody2D.prototype;

              _proto.isAwake = function isAwake() {
                if (this._body) {
                  return this._body.isAwake;
                }

                return false;
              };

              _proto.wakeUp = function wakeUp() {
                if (this._body) {
                  this._body.wakeUp();
                }
              };

              _proto.sleep = function sleep() {
                if (this._body) {
                  this._body.sleep();
                }
              };

              _proto.getMass = function getMass() {
                if (this._body) {
                  return this._body.getMass();
                }

                return 0;
              };

              _proto.applyForce = function applyForce(force, point, wake) {
                if (this._body) {
                  this._body.applyForce(force, point, wake);
                }
              };

              _proto.applyForceToCenter = function applyForceToCenter(force, wake) {
                if (this._body) {
                  this._body.applyForceToCenter(force, wake);
                }
              };

              _proto.applyTorque = function applyTorque(torque, wake) {
                if (this._body) {
                  this._body.applyTorque(torque, wake);
                }
              };

              _proto.applyLinearImpulse = function applyLinearImpulse(impulse, point, wake) {
                if (this._body) {
                  this._body.applyLinearImpulse(impulse, point, wake);
                }
              };

              _proto.applyLinearImpulseToCenter = function applyLinearImpulseToCenter(impulse, wake) {
                if (this._body) {
                  this._body.applyLinearImpulseToCenter(impulse, wake);
                }
              };

              _proto.applyAngularImpulse = function applyAngularImpulse(impulse, wake) {
                if (this._body) {
                  this._body.applyAngularImpulse(impulse, wake);
                }
              };

              _proto.getLinearVelocityFromWorldPoint = function getLinearVelocityFromWorldPoint(worldPoint, out) {
                if (this._body) {
                  return this._body.getLinearVelocityFromWorldPoint(worldPoint, out);
                }

                return out;
              };

              _proto.getLocalVector = function getLocalVector(worldVector, out) {
                if (this._body) {
                  return this._body.getLocalVector(worldVector, out);
                }

                return out;
              };

              _proto.getWorldVector = function getWorldVector(localVector, out) {
                if (this._body) {
                  return this._body.getWorldVector(localVector, out);
                }

                return out;
              };

              _proto.getLocalPoint = function getLocalPoint(worldPoint, out) {
                if (this._body) {
                  return this._body.getLocalPoint(worldPoint, out);
                }

                return out;
              };

              _proto.getWorldPoint = function getWorldPoint(localPoint, out) {
                if (this._body) {
                  return this._body.getWorldPoint(localPoint, out);
                }

                return out;
              };

              _proto.getLocalCenter = function getLocalCenter(out) {
                if (this._body) {
                  return this._body.getLocalCenter(out);
                }

                return out;
              };

              _proto.getWorldCenter = function getWorldCenter(out) {
                if (this._body) {
                  return this._body.getWorldCenter(out);
                }

                return out;
              };

              _proto.getInertia = function getInertia() {
                if (this._body) {
                  this._body.getInertia();
                }

                return 0;
              };

              _proto.onLoad = function onLoad() {
                {
                  this._body = createRigidBody();

                  this._body.initialize(this);
                }
              };

              _proto.onEnable = function onEnable() {
                if (this._body) {
                  this._body.onEnable();
                }
              };

              _proto.onDisable = function onDisable() {
                if (this._body) {
                  this._body.onDisable();
                }
              };

              _proto.onDestroy = function onDestroy() {
                if (this._body) {
                  this._body.onDestroy();
                }
              };

              _createClass(RigidBody2D, [{
                key: "group",
                get: function get() {
                  return this._group;
                },
                set: function set(v) {
                  this._group = v;
                }
              }, {
                key: "type",
                get: function get() {
                  return this._type;
                },
                set: function set(v) {
                  this._type = v;

                  if (this._body) {
                    if (v === ERigidBody2DType.Animated) {
                      this._body.setType(ERigidBody2DType.Kinematic);
                    } else {
                      this._body.setType(v);
                    }
                  }
                }
              }, {
                key: "allowSleep",
                get: function get() {
                  return this._allowSleep;
                },
                set: function set(v) {
                  this._allowSleep = v;

                  if (this._body) {
                    this._body.setAllowSleep(v);
                  }
                }
              }, {
                key: "gravityScale",
                get: function get() {
                  return this._gravityScale;
                },
                set: function set(v) {
                  this._gravityScale = v;

                  if (this._body) {
                    this._body.setGravityScale(v);
                  }
                }
              }, {
                key: "linearDamping",
                get: function get() {
                  return this._linearDamping;
                },
                set: function set(v) {
                  this._linearDamping = v;

                  if (this._body) {
                    this._body.setLinearDamping(v);
                  }
                }
              }, {
                key: "angularDamping",
                get: function get() {
                  return this._angularDamping;
                },
                set: function set(v) {
                  this._angularDamping = v;

                  if (this._body) {
                    this._body.setAngularDamping(v);
                  }
                }
              }, {
                key: "linearVelocity",
                get: function get() {
                  if (this._body) {
                    this._body.getLinearVelocity(this._linearVelocity);
                  }

                  return this._linearVelocity;
                },
                set: function set(v) {
                  this._linearVelocity = v;

                  if (this._body) {
                    this._body.setLinearVelocity(v);
                  }
                }
              }, {
                key: "angularVelocity",
                get: function get() {
                  if (this._body) {
                    this._angularVelocity = this._body.getAngularVelocity();
                  }

                  return this._angularVelocity;
                },
                set: function set(v) {
                  this._angularVelocity = v;

                  if (this._body) {
                    this._body.setAngularVelocity(v);
                  }
                }
              }, {
                key: "fixedRotation",
                get: function get() {
                  return this._fixedRotation;
                },
                set: function set(v) {
                  this._fixedRotation = v;

                  if (this._body) {
                    this._body.setFixedRotation(v);
                  }
                }
              }, {
                key: "impl",
                get: function get() {
                  return this._body;
                }
              }]);

              return RigidBody2D;
            }(Component), _temp$1g), (_applyDecoratedDescriptor(_class2$1d.prototype, "group", [_dec3$Q], Object.getOwnPropertyDescriptor(_class2$1d.prototype, "group"), _class2$1d.prototype), _descriptor$12 = _applyDecoratedDescriptor(_class2$1d.prototype, "enabledContactListener", [property$1], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor2$P = _applyDecoratedDescriptor(_class2$1d.prototype, "bullet", [property$1], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _applyDecoratedDescriptor(_class2$1d.prototype, "type", [_dec4$J], Object.getOwnPropertyDescriptor(_class2$1d.prototype, "type"), _class2$1d.prototype), _applyDecoratedDescriptor(_class2$1d.prototype, "allowSleep", [property$1], Object.getOwnPropertyDescriptor(_class2$1d.prototype, "allowSleep"), _class2$1d.prototype), _applyDecoratedDescriptor(_class2$1d.prototype, "gravityScale", [property$1], Object.getOwnPropertyDescriptor(_class2$1d.prototype, "gravityScale"), _class2$1d.prototype), _applyDecoratedDescriptor(_class2$1d.prototype, "linearDamping", [property$1], Object.getOwnPropertyDescriptor(_class2$1d.prototype, "linearDamping"), _class2$1d.prototype), _applyDecoratedDescriptor(_class2$1d.prototype, "angularDamping", [property$1], Object.getOwnPropertyDescriptor(_class2$1d.prototype, "angularDamping"), _class2$1d.prototype), _applyDecoratedDescriptor(_class2$1d.prototype, "linearVelocity", [property$1], Object.getOwnPropertyDescriptor(_class2$1d.prototype, "linearVelocity"), _class2$1d.prototype), _applyDecoratedDescriptor(_class2$1d.prototype, "angularVelocity", [property$1], Object.getOwnPropertyDescriptor(_class2$1d.prototype, "angularVelocity"), _class2$1d.prototype), _applyDecoratedDescriptor(_class2$1d.prototype, "fixedRotation", [property$1], Object.getOwnPropertyDescriptor(_class2$1d.prototype, "fixedRotation"), _class2$1d.prototype), _descriptor3$B = _applyDecoratedDescriptor(_class2$1d.prototype, "awakeOnLoad", [property$1], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _descriptor4$w = _applyDecoratedDescriptor(_class2$1d.prototype, "_group", [property$1], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return PhysicsGroup.DEFAULT;
              }
            }), _descriptor5$q = _applyDecoratedDescriptor(_class2$1d.prototype, "_type", [property$1], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return ERigidBody2DType.Dynamic;
              }
            }), _descriptor6$h = _applyDecoratedDescriptor(_class2$1d.prototype, "_allowSleep", [property$1], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _descriptor7$f = _applyDecoratedDescriptor(_class2$1d.prototype, "_gravityScale", [property$1], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1;
              }
            }), _descriptor8$f = _applyDecoratedDescriptor(_class2$1d.prototype, "_linearDamping", [property$1], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor9$e = _applyDecoratedDescriptor(_class2$1d.prototype, "_angularDamping", [property$1], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor10$e = _applyDecoratedDescriptor(_class2$1d.prototype, "_linearVelocity", [property$1], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new Vec2();
              }
            }), _descriptor11$d = _applyDecoratedDescriptor(_class2$1d.prototype, "_angularVelocity", [property$1], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor12$b = _applyDecoratedDescriptor(_class2$1d.prototype, "_fixedRotation", [property$1], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            })), _class2$1d)) || _class$1p) || _class$1p));

            var _dec$1p, _dec2$_, _class$1q, _class2$1e, _descriptor$13, _descriptor2$Q, _descriptor3$C, _descriptor4$x, _descriptor5$r, _descriptor6$i, _descriptor7$g, _descriptor8$g, _temp$1h;
            var Collider2D = exports('Collider2D', (_dec$1p = ccclass('cc.Collider2D'), _dec2$_ = type(PhysicsGroup), _dec$1p(_class$1q = (_class2$1e = (_temp$1h = function (_Eventify) {
              _inheritsLoose(Collider2D, _Eventify);

              function Collider2D() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Eventify.call.apply(_Eventify, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "editing", _descriptor$13, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "tag", _descriptor2$Q, _assertThisInitialized(_this));

                _this.TYPE = ECollider2DType.None;
                _this._shape = null;
                _this._body = null;

                _initializerDefineProperty(_this, "_group", _descriptor3$C, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_density", _descriptor4$x, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_sensor", _descriptor5$r, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_friction", _descriptor6$i, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_restitution", _descriptor7$g, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_offset", _descriptor8$g, _assertThisInitialized(_this));

                return _this;
              }

              var _proto = Collider2D.prototype;

              _proto.onLoad = function onLoad() {
                {
                  this._shape = createShape(this.TYPE);

                  this._shape.initialize(this);

                  if (this._shape.onLoad) {
                    this._shape.onLoad();
                  }

                  this._body = this.getComponent(RigidBody2D);
                }
              };

              _proto.onEnable = function onEnable() {
                if (this._shape) {
                  this._shape.onEnable();
                }
              };

              _proto.onDisable = function onDisable() {
                if (this._shape && this._shape.onDisable) {
                  this._shape.onDisable();
                }
              };

              _proto.onDestroy = function onDestroy() {
                if (this._shape && this._shape.onDestroy) {
                  this._shape.onDestroy();
                }
              };

              _proto.apply = function apply() {
                if (this._shape && this._shape.apply) {
                  this._shape.apply();
                }
              };

              _createClass(Collider2D, [{
                key: "group",
                get: function get() {
                  return this._group;
                },
                set: function set(v) {
                  this._group = v;

                  if (this._shape && this._shape.onGroupChanged) {
                    this._shape.onGroupChanged();
                  }
                }
              }, {
                key: "density",
                get: function get() {
                  return this._density;
                },
                set: function set(v) {
                  this._density = v;
                }
              }, {
                key: "sensor",
                get: function get() {
                  return this._sensor;
                },
                set: function set(v) {
                  this._sensor = v;
                }
              }, {
                key: "friction",
                get: function get() {
                  return this._friction;
                },
                set: function set(v) {
                  this._friction = v;
                }
              }, {
                key: "restitution",
                get: function get() {
                  return this._restitution;
                },
                set: function set(v) {
                  this._restitution = v;
                }
              }, {
                key: "offset",
                get: function get() {
                  return this._offset;
                },
                set: function set(v) {
                  this._offset = v;
                }
              }, {
                key: "body",
                get: function get() {
                  return this._body;
                }
              }, {
                key: "impl",
                get: function get() {
                  return this._shape;
                }
              }, {
                key: "worldAABB",
                get: function get() {
                  if (this._shape) {
                    return this._shape.worldAABB;
                  }

                  return new Rect();
                }
              }]);

              return Collider2D;
            }(Eventify(Component)), _temp$1h), (_descriptor$13 = _applyDecoratedDescriptor(_class2$1e.prototype, "editing", [editable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor2$Q = _applyDecoratedDescriptor(_class2$1e.prototype, "tag", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _applyDecoratedDescriptor(_class2$1e.prototype, "group", [_dec2$_], Object.getOwnPropertyDescriptor(_class2$1e.prototype, "group"), _class2$1e.prototype), _applyDecoratedDescriptor(_class2$1e.prototype, "density", [property], Object.getOwnPropertyDescriptor(_class2$1e.prototype, "density"), _class2$1e.prototype), _applyDecoratedDescriptor(_class2$1e.prototype, "sensor", [property], Object.getOwnPropertyDescriptor(_class2$1e.prototype, "sensor"), _class2$1e.prototype), _applyDecoratedDescriptor(_class2$1e.prototype, "friction", [property], Object.getOwnPropertyDescriptor(_class2$1e.prototype, "friction"), _class2$1e.prototype), _applyDecoratedDescriptor(_class2$1e.prototype, "restitution", [property], Object.getOwnPropertyDescriptor(_class2$1e.prototype, "restitution"), _class2$1e.prototype), _applyDecoratedDescriptor(_class2$1e.prototype, "offset", [property], Object.getOwnPropertyDescriptor(_class2$1e.prototype, "offset"), _class2$1e.prototype), _descriptor3$C = _applyDecoratedDescriptor(_class2$1e.prototype, "_group", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return PhysicsGroup.DEFAULT;
              }
            }), _descriptor4$x = _applyDecoratedDescriptor(_class2$1e.prototype, "_density", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1.0;
              }
            }), _descriptor5$r = _applyDecoratedDescriptor(_class2$1e.prototype, "_sensor", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor6$i = _applyDecoratedDescriptor(_class2$1e.prototype, "_friction", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0.2;
              }
            }), _descriptor7$g = _applyDecoratedDescriptor(_class2$1e.prototype, "_restitution", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor8$g = _applyDecoratedDescriptor(_class2$1e.prototype, "_offset", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new Vec2();
              }
            })), _class2$1e)) || _class$1q));

            var _dec$1q, _dec2$$, _class$1r, _class2$1f, _descriptor$14, _temp$1i;
            var BoxCollider2D = exports('BoxCollider2D', (_dec$1q = ccclass('cc.BoxCollider2D'), _dec2$$ = menu(), _dec$1q(_class$1r = _dec2$$(_class$1r = (_class2$1f = (_temp$1i = function (_Collider2D) {
              _inheritsLoose(BoxCollider2D, _Collider2D);

              function BoxCollider2D() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Collider2D.call.apply(_Collider2D, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "_size", _descriptor$14, _assertThisInitialized(_this));

                _this.TYPE = ECollider2DType.BOX;
                return _this;
              }

              _createClass(BoxCollider2D, [{
                key: "size",
                get: function get() {
                  return this._size;
                },
                set: function set(v) {
                  this._size = v;
                }
              }, {
                key: "worldPoints",
                get: function get() {
                  if (this._shape) {
                    return this._shape.worldPoints;
                  }

                  return [];
                }
              }]);

              return BoxCollider2D;
            }(Collider2D), _temp$1i), (_descriptor$14 = _applyDecoratedDescriptor(_class2$1f.prototype, "_size", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new Size(1, 1);
              }
            }), _applyDecoratedDescriptor(_class2$1f.prototype, "size", [property], Object.getOwnPropertyDescriptor(_class2$1f.prototype, "size"), _class2$1f.prototype)), _class2$1f)) || _class$1r) || _class$1r));

            var _dec$1r, _dec2$10, _class$1s, _class2$1g, _descriptor$15, _temp$1j;
            var CircleCollider2D = exports('CircleCollider2D', (_dec$1r = ccclass('cc.CircleCollider2D'), _dec2$10 = menu(), _dec$1r(_class$1s = _dec2$10(_class$1s = (_class2$1g = (_temp$1j = function (_Collider2D) {
              _inheritsLoose(CircleCollider2D, _Collider2D);

              function CircleCollider2D() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Collider2D.call.apply(_Collider2D, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "_radius", _descriptor$15, _assertThisInitialized(_this));

                _this.TYPE = ECollider2DType.CIRCLE;
                return _this;
              }

              _createClass(CircleCollider2D, [{
                key: "radius",
                get: function get() {
                  return this._radius;
                },
                set: function set(v) {
                  this._radius = v < 0 ? 0 : v;
                }
              }, {
                key: "worldPosition",
                get: function get() {
                  if (this._shape) {
                    return this._shape.worldPosition;
                  }

                  return new Vec2();
                }
              }, {
                key: "worldRadius",
                get: function get() {
                  if (this._shape) {
                    return this._shape.worldRadius;
                  }

                  return 0;
                }
              }]);

              return CircleCollider2D;
            }(Collider2D), _temp$1j), (_descriptor$15 = _applyDecoratedDescriptor(_class2$1g.prototype, "_radius", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1;
              }
            }), _applyDecoratedDescriptor(_class2$1g.prototype, "radius", [property], Object.getOwnPropertyDescriptor(_class2$1g.prototype, "radius"), _class2$1g.prototype)), _class2$1g)) || _class$1s) || _class$1s));

            var _dec$1s, _dec2$11, _dec3$R, _dec4$K, _class$1t, _class2$1h, _descriptor$16, _descriptor2$R, _temp$1k;
            var PolygonCollider2D = exports('PolygonCollider2D', (_dec$1s = ccclass('cc.PolygonCollider2D'), _dec2$11 = menu(), _dec3$R = property({
              serializable: false
            }), _dec4$K = property({
              type: Vec2
            }), _dec$1s(_class$1t = _dec2$11(_class$1t = (_class2$1h = (_temp$1k = function (_Collider2D) {
              _inheritsLoose(PolygonCollider2D, _Collider2D);

              function PolygonCollider2D() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Collider2D.call.apply(_Collider2D, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "threshold", _descriptor$16, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_points", _descriptor2$R, _assertThisInitialized(_this));

                _this.TYPE = ECollider2DType.POLYGON;
                return _this;
              }

              _createClass(PolygonCollider2D, [{
                key: "points",
                get: function get() {
                  return this._points;
                },
                set: function set(v) {
                  this._points = v;
                }
              }, {
                key: "worldPoints",
                get: function get() {
                  if (this._shape) {
                    return this._shape.worldPoints;
                  }

                  return [];
                }
              }]);

              return PolygonCollider2D;
            }(Collider2D), _temp$1k), (_descriptor$16 = _applyDecoratedDescriptor(_class2$1h.prototype, "threshold", [_dec3$R], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1;
              }
            }), _descriptor2$R = _applyDecoratedDescriptor(_class2$1h.prototype, "_points", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [new Vec2(-1, -1), new Vec2(1, -1), new Vec2(1, 1), new Vec2(-1, 1)];
              }
            }), _applyDecoratedDescriptor(_class2$1h.prototype, "points", [_dec4$K], Object.getOwnPropertyDescriptor(_class2$1h.prototype, "points"), _class2$1h.prototype)), _class2$1h)) || _class$1t) || _class$1t));

            var _dec$1t, _dec2$12, _class$1u, _class2$1i, _descriptor$17, _descriptor2$S, _descriptor3$D, _descriptor4$y, _temp$1l;
            var Joint2D = exports('Joint2D', (_dec$1t = ccclass('cc.Joint2D'), _dec2$12 = type(RigidBody2D), _dec$1t(_class$1u = (_class2$1i = (_temp$1l = function (_Component) {
              _inheritsLoose(Joint2D, _Component);

              function Joint2D() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Component.call.apply(_Component, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "anchor", _descriptor$17, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "connectedAnchor", _descriptor2$S, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "collideConnected", _descriptor3$D, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "connectedBody", _descriptor4$y, _assertThisInitialized(_this));

                _this._body = null;
                _this._joint = null;
                _this.TYPE = EJoint2DType.None;
                return _this;
              }

              var _proto = Joint2D.prototype;

              _proto.onLoad = function onLoad() {
                {
                  this._joint = createJoint(this.TYPE);

                  this._joint.initialize(this);

                  this._body = this.getComponent(RigidBody2D);
                }
              };

              _proto.onEnable = function onEnable() {
                if (this._joint && this._joint.onEnable) {
                  this._joint.onEnable();
                }
              };

              _proto.onDisable = function onDisable() {
                if (this._joint && this._joint.onDisable) {
                  this._joint.onDisable();
                }
              };

              _proto.start = function start() {
                if (this._joint && this._joint.start) {
                  this._joint.start();
                }
              };

              _proto.onDestroy = function onDestroy() {
                if (this._joint && this._joint.onDestroy) {
                  this._joint.onDestroy();
                }
              };

              _createClass(Joint2D, [{
                key: "body",
                get: function get() {
                  return this._body;
                }
              }, {
                key: "impl",
                get: function get() {
                  return this._joint;
                }
              }]);

              return Joint2D;
            }(Component), _temp$1l), (_descriptor$17 = _applyDecoratedDescriptor(_class2$1i.prototype, "anchor", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new Vec2();
              }
            }), _descriptor2$S = _applyDecoratedDescriptor(_class2$1i.prototype, "connectedAnchor", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new Vec2();
              }
            }), _descriptor3$D = _applyDecoratedDescriptor(_class2$1i.prototype, "collideConnected", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor4$y = _applyDecoratedDescriptor(_class2$1i.prototype, "connectedBody", [_dec2$12], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            })), _class2$1i)) || _class$1u));

            var _dec$1u, _dec2$13, _class$1v, _class2$1j, _descriptor$18, _descriptor2$T, _temp$1m;
            var DistanceJoint2D = exports('DistanceJoint2D', (_dec$1u = ccclass('cc.DistanceJoint2D'), _dec2$13 = menu(), _dec$1u(_class$1v = _dec2$13(_class$1v = (_class2$1j = (_temp$1m = function (_Joint2D) {
              _inheritsLoose(DistanceJoint2D, _Joint2D);

              function DistanceJoint2D() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Joint2D.call.apply(_Joint2D, [this].concat(args)) || this;
                _this.TYPE = EJoint2DType.DISTANCE;

                _initializerDefineProperty(_this, "_maxLength", _descriptor$18, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_autoCalcDistance", _descriptor2$T, _assertThisInitialized(_this));

                return _this;
              }

              _createClass(DistanceJoint2D, [{
                key: "maxLength",
                get: function get() {
                  if (this._autoCalcDistance && this.connectedBody) {
                    return Vec3.distance(this.node.worldPosition, this.connectedBody.node.worldPosition);
                  }

                  return this._maxLength;
                },
                set: function set(v) {
                  this._maxLength = v;

                  if (this._joint) {
                    this._joint.setMaxLength(v);
                  }
                }
              }, {
                key: "autoCalcDistance",
                get: function get() {
                  return this._autoCalcDistance;
                },
                set: function set(v) {
                  this._autoCalcDistance = v;
                }
              }]);

              return DistanceJoint2D;
            }(Joint2D), _temp$1m), (_applyDecoratedDescriptor(_class2$1j.prototype, "maxLength", [property], Object.getOwnPropertyDescriptor(_class2$1j.prototype, "maxLength"), _class2$1j.prototype), _applyDecoratedDescriptor(_class2$1j.prototype, "autoCalcDistance", [property], Object.getOwnPropertyDescriptor(_class2$1j.prototype, "autoCalcDistance"), _class2$1j.prototype), _descriptor$18 = _applyDecoratedDescriptor(_class2$1j.prototype, "_maxLength", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 5;
              }
            }), _descriptor2$T = _applyDecoratedDescriptor(_class2$1j.prototype, "_autoCalcDistance", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            })), _class2$1j)) || _class$1v) || _class$1v));

            var _dec$1v, _dec2$14, _class$1w, _class2$1k, _descriptor$19, _descriptor2$U, _descriptor3$E, _descriptor4$z, _temp$1n;
            var SpringJoint2D = exports('SpringJoint2D', (_dec$1v = ccclass('cc.SpringJoint2D'), _dec2$14 = menu(), _dec$1v(_class$1w = _dec2$14(_class$1w = (_class2$1k = (_temp$1n = function (_Joint2D) {
              _inheritsLoose(SpringJoint2D, _Joint2D);

              function SpringJoint2D() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Joint2D.call.apply(_Joint2D, [this].concat(args)) || this;
                _this.TYPE = EJoint2DType.SPRING;

                _initializerDefineProperty(_this, "_frequency", _descriptor$19, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_dampingRatio", _descriptor2$U, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_distance", _descriptor3$E, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_autoCalcDistance", _descriptor4$z, _assertThisInitialized(_this));

                return _this;
              }

              _createClass(SpringJoint2D, [{
                key: "frequency",
                get: function get() {
                  return this._frequency;
                },
                set: function set(v) {
                  this._frequency = v;

                  if (this._joint) {
                    this._joint.setFrequency(v);
                  }
                }
              }, {
                key: "dampingRatio",
                get: function get() {
                  return this._dampingRatio;
                },
                set: function set(v) {
                  this._dampingRatio = v;

                  if (this._joint) {
                    this._joint.setDampingRatio(v);
                  }
                }
              }, {
                key: "distance",
                get: function get() {
                  if (this._autoCalcDistance && this.connectedBody) {
                    return Vec3.distance(this.node.worldPosition, this.connectedBody.node.worldPosition);
                  }

                  return this._distance;
                },
                set: function set(v) {
                  this._distance = v;

                  if (this._joint) {
                    this._joint.setDistance(v);
                  }
                }
              }, {
                key: "autoCalcDistance",
                get: function get() {
                  return this._autoCalcDistance;
                },
                set: function set(v) {
                  this._autoCalcDistance = v;
                }
              }]);

              return SpringJoint2D;
            }(Joint2D), _temp$1n), (_applyDecoratedDescriptor(_class2$1k.prototype, "frequency", [property], Object.getOwnPropertyDescriptor(_class2$1k.prototype, "frequency"), _class2$1k.prototype), _applyDecoratedDescriptor(_class2$1k.prototype, "dampingRatio", [property], Object.getOwnPropertyDescriptor(_class2$1k.prototype, "dampingRatio"), _class2$1k.prototype), _applyDecoratedDescriptor(_class2$1k.prototype, "distance", [property], Object.getOwnPropertyDescriptor(_class2$1k.prototype, "distance"), _class2$1k.prototype), _applyDecoratedDescriptor(_class2$1k.prototype, "autoCalcDistance", [property], Object.getOwnPropertyDescriptor(_class2$1k.prototype, "autoCalcDistance"), _class2$1k.prototype), _descriptor$19 = _applyDecoratedDescriptor(_class2$1k.prototype, "_frequency", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 5;
              }
            }), _descriptor2$U = _applyDecoratedDescriptor(_class2$1k.prototype, "_dampingRatio", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0.7;
              }
            }), _descriptor3$E = _applyDecoratedDescriptor(_class2$1k.prototype, "_distance", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 10;
              }
            }), _descriptor4$z = _applyDecoratedDescriptor(_class2$1k.prototype, "_autoCalcDistance", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            })), _class2$1k)) || _class$1w) || _class$1w));

            var _dec$1w, _dec2$15, _class$1x, _class2$1l, _descriptor$1a, _descriptor2$V, _descriptor3$F, _temp$1o;
            var MouseJoint2D = exports('MouseJoint2D', (_dec$1w = ccclass('cc.MouseJoint2D'), _dec2$15 = menu(), _dec$1w(_class$1x = _dec2$15(_class$1x = (_class2$1l = (_temp$1o = function (_Joint2D) {
              _inheritsLoose(MouseJoint2D, _Joint2D);

              function MouseJoint2D() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Joint2D.call.apply(_Joint2D, [this].concat(args)) || this;
                _this.TYPE = EJoint2DType.MOUSE;

                _initializerDefineProperty(_this, "_maxForce", _descriptor$1a, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_dampingRatio", _descriptor2$V, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_frequency", _descriptor3$F, _assertThisInitialized(_this));

                _this._target = new Vec2();
                return _this;
              }

              var _proto = MouseJoint2D.prototype;

              _proto.update = function update(dt) {
                this._joint.update(dt);
              };

              _createClass(MouseJoint2D, [{
                key: "target",
                get: function get() {
                  return this._target;
                },
                set: function set(v) {
                  this._target = v;

                  if (this._joint) {
                    this._joint.setTarget(v);
                  }
                }
              }, {
                key: "frequency",
                get: function get() {
                  return this._frequency;
                },
                set: function set(v) {
                  this._frequency = v;

                  if (this._joint) {
                    this._joint.setFrequency(v);
                  }
                }
              }, {
                key: "dampingRatio",
                get: function get() {
                  return this._dampingRatio;
                },
                set: function set(v) {
                  this._dampingRatio = v;

                  if (this._joint) {
                    this._joint.setDampingRatio(v);
                  }
                }
              }, {
                key: "maxForce",
                get: function get() {
                  return this._maxForce;
                },
                set: function set(v) {
                  this._maxForce = v;

                  if (this._joint) {
                    this._joint.setMaxForce(v);
                  }
                }
              }]);

              return MouseJoint2D;
            }(Joint2D), _temp$1o), (_applyDecoratedDescriptor(_class2$1l.prototype, "frequency", [property], Object.getOwnPropertyDescriptor(_class2$1l.prototype, "frequency"), _class2$1l.prototype), _applyDecoratedDescriptor(_class2$1l.prototype, "dampingRatio", [property], Object.getOwnPropertyDescriptor(_class2$1l.prototype, "dampingRatio"), _class2$1l.prototype), _applyDecoratedDescriptor(_class2$1l.prototype, "maxForce", [property], Object.getOwnPropertyDescriptor(_class2$1l.prototype, "maxForce"), _class2$1l.prototype), _descriptor$1a = _applyDecoratedDescriptor(_class2$1l.prototype, "_maxForce", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1000;
              }
            }), _descriptor2$V = _applyDecoratedDescriptor(_class2$1l.prototype, "_dampingRatio", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0.7;
              }
            }), _descriptor3$F = _applyDecoratedDescriptor(_class2$1l.prototype, "_frequency", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 5;
              }
            })), _class2$1l)) || _class$1x) || _class$1x));

            var _dec$1x, _dec2$16, _class$1y, _class2$1m, _descriptor$1b, _descriptor2$W, _descriptor3$G, _descriptor4$A, _descriptor5$s, _descriptor6$j, _temp$1p;
            var tempVec3_1 = new Vec3();
            var tempVec3_2 = new Vec3();
            var RelativeJoint2D = exports('RelativeJoint2D', (_dec$1x = ccclass('cc.RelativeJoint2D'), _dec2$16 = menu(), _dec$1x(_class$1y = _dec2$16(_class$1y = (_class2$1m = (_temp$1p = function (_Joint2D) {
              _inheritsLoose(RelativeJoint2D, _Joint2D);

              function RelativeJoint2D() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Joint2D.call.apply(_Joint2D, [this].concat(args)) || this;
                _this.TYPE = EJoint2DType.RELATIVE;

                _initializerDefineProperty(_this, "_maxForce", _descriptor$1b, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_maxTorque", _descriptor2$W, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_correctionFactor", _descriptor3$G, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_angularOffset", _descriptor4$A, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_linearOffset", _descriptor5$s, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_autoCalcOffset", _descriptor6$j, _assertThisInitialized(_this));

                return _this;
              }

              _createClass(RelativeJoint2D, [{
                key: "maxForce",
                get: function get() {
                  return this._maxForce;
                },
                set: function set(v) {
                  this._maxForce = v;

                  if (this._joint) {
                    this._joint.setMaxForce(v);
                  }
                }
              }, {
                key: "maxTorque",
                get: function get() {
                  return this._maxTorque;
                },
                set: function set(v) {
                  this._maxTorque = v;

                  if (this._joint) {
                    this._joint.setMaxTorque(v);
                  }
                }
              }, {
                key: "correctionFactor",
                get: function get() {
                  return this._correctionFactor;
                },
                set: function set(v) {
                  this._correctionFactor = v;

                  if (this._joint) {
                    this._joint.setCorrectionFactor(v);
                  }
                }
              }, {
                key: "linearOffset",
                get: function get() {
                  if (this._autoCalcOffset && this.connectedBody) {
                    return Vec2.subtract(this._linearOffset, this.connectedBody.node.worldPosition, this.node.worldPosition);
                  }

                  return this._linearOffset;
                },
                set: function set(v) {
                  this._linearOffset.set(v);

                  if (this._joint) {
                    this._joint.setLinearOffset(v);
                  }
                }
              }, {
                key: "angularOffset",
                get: function get() {
                  if (this._autoCalcOffset && this.connectedBody) {
                    Quat.toEuler(tempVec3_1, this.node.worldRotation);
                    Quat.toEuler(tempVec3_2, this.connectedBody.node.worldRotation);
                    this._angularOffset = tempVec3_2.z - tempVec3_1.z;
                  }

                  return this._angularOffset;
                },
                set: function set(v) {
                  this._angularOffset = v;

                  if (this._joint) {
                    this._joint.setAngularOffset(v);
                  }
                }
              }, {
                key: "autoCalcOffset",
                get: function get() {
                  return this._autoCalcOffset;
                },
                set: function set(v) {
                  this._autoCalcOffset = v;
                }
              }]);

              return RelativeJoint2D;
            }(Joint2D), _temp$1p), (_applyDecoratedDescriptor(_class2$1m.prototype, "maxForce", [property], Object.getOwnPropertyDescriptor(_class2$1m.prototype, "maxForce"), _class2$1m.prototype), _applyDecoratedDescriptor(_class2$1m.prototype, "maxTorque", [property], Object.getOwnPropertyDescriptor(_class2$1m.prototype, "maxTorque"), _class2$1m.prototype), _applyDecoratedDescriptor(_class2$1m.prototype, "correctionFactor", [property], Object.getOwnPropertyDescriptor(_class2$1m.prototype, "correctionFactor"), _class2$1m.prototype), _applyDecoratedDescriptor(_class2$1m.prototype, "linearOffset", [property], Object.getOwnPropertyDescriptor(_class2$1m.prototype, "linearOffset"), _class2$1m.prototype), _applyDecoratedDescriptor(_class2$1m.prototype, "angularOffset", [property], Object.getOwnPropertyDescriptor(_class2$1m.prototype, "angularOffset"), _class2$1m.prototype), _applyDecoratedDescriptor(_class2$1m.prototype, "autoCalcOffset", [property], Object.getOwnPropertyDescriptor(_class2$1m.prototype, "autoCalcOffset"), _class2$1m.prototype), _descriptor$1b = _applyDecoratedDescriptor(_class2$1m.prototype, "_maxForce", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 5;
              }
            }), _descriptor2$W = _applyDecoratedDescriptor(_class2$1m.prototype, "_maxTorque", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0.7;
              }
            }), _descriptor3$G = _applyDecoratedDescriptor(_class2$1m.prototype, "_correctionFactor", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0.3;
              }
            }), _descriptor4$A = _applyDecoratedDescriptor(_class2$1m.prototype, "_angularOffset", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor5$s = _applyDecoratedDescriptor(_class2$1m.prototype, "_linearOffset", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new Vec2();
              }
            }), _descriptor6$j = _applyDecoratedDescriptor(_class2$1m.prototype, "_autoCalcOffset", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            })), _class2$1m)) || _class$1y) || _class$1y));

            var _dec$1y, _dec2$17, _class$1z, _class2$1n, _descriptor$1c, _descriptor2$X, _descriptor3$H, _descriptor4$B, _descriptor5$t, _descriptor6$k, _descriptor7$h, _descriptor8$h, _temp$1q;
            var tempVec2 = new Vec2();
            var SliderJoint2D = exports('SliderJoint2D', (_dec$1y = ccclass('cc.SliderJoint2D'), _dec2$17 = menu(), _dec$1y(_class$1z = _dec2$17(_class$1z = (_class2$1n = (_temp$1q = function (_Joint2D) {
              _inheritsLoose(SliderJoint2D, _Joint2D);

              function SliderJoint2D() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Joint2D.call.apply(_Joint2D, [this].concat(args)) || this;
                _this.TYPE = EJoint2DType.SLIDER;

                _initializerDefineProperty(_this, "_angle", _descriptor$1c, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_autoCalcAngle", _descriptor2$X, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_enableMotor", _descriptor3$H, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_maxMotorForce", _descriptor4$B, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_motorSpeed", _descriptor5$t, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_enableLimit", _descriptor6$k, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_lowerLimit", _descriptor7$h, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_upperLimit", _descriptor8$h, _assertThisInitialized(_this));

                return _this;
              }

              _createClass(SliderJoint2D, [{
                key: "angle",
                get: function get() {
                  if (this._autoCalcAngle && this.connectedBody) {
                    Vec2.subtract(tempVec2, this.connectedBody.node.worldPosition, this.node.worldPosition);
                    this._angle = toDegree(Math.atan2(tempVec2.y, tempVec2.x));
                  }

                  return this._angle;
                },
                set: function set(v) {
                  this._angle = v;
                }
              }, {
                key: "autoCalcAngle",
                get: function get() {
                  return this._autoCalcAngle;
                },
                set: function set(v) {
                  this._autoCalcAngle = v;
                }
              }, {
                key: "enableMotor",
                get: function get() {
                  return this._enableMotor;
                },
                set: function set(v) {
                  this._enableMotor = v;
                }
              }, {
                key: "maxMotorForce",
                get: function get() {
                  return this._maxMotorForce;
                },
                set: function set(v) {
                  this._maxMotorForce = v;

                  if (this._joint) {
                    this._joint.setMaxMotorForce(v);
                  }
                }
              }, {
                key: "motorSpeed",
                get: function get() {
                  return this._motorSpeed;
                },
                set: function set(v) {
                  this._motorSpeed = v;

                  if (this._joint) {
                    this._joint.setMotorSpeed(v);
                  }
                }
              }, {
                key: "enableLimit",
                get: function get() {
                  return this._enableLimit;
                },
                set: function set(v) {
                  this._enableLimit = v;
                }
              }, {
                key: "lowerLimit",
                get: function get() {
                  return this._lowerLimit;
                },
                set: function set(v) {
                  this._lowerLimit = v;

                  if (this._joint) {
                    this._joint.setLowerLimit(v);
                  }
                }
              }, {
                key: "upperLimit",
                get: function get() {
                  return this._upperLimit;
                },
                set: function set(v) {
                  this._upperLimit = v;

                  if (this._joint) {
                    this._joint.setUpperLimit(v);
                  }
                }
              }]);

              return SliderJoint2D;
            }(Joint2D), _temp$1q), (_applyDecoratedDescriptor(_class2$1n.prototype, "angle", [property], Object.getOwnPropertyDescriptor(_class2$1n.prototype, "angle"), _class2$1n.prototype), _applyDecoratedDescriptor(_class2$1n.prototype, "autoCalcAngle", [property], Object.getOwnPropertyDescriptor(_class2$1n.prototype, "autoCalcAngle"), _class2$1n.prototype), _applyDecoratedDescriptor(_class2$1n.prototype, "enableMotor", [property], Object.getOwnPropertyDescriptor(_class2$1n.prototype, "enableMotor"), _class2$1n.prototype), _applyDecoratedDescriptor(_class2$1n.prototype, "maxMotorForce", [property], Object.getOwnPropertyDescriptor(_class2$1n.prototype, "maxMotorForce"), _class2$1n.prototype), _applyDecoratedDescriptor(_class2$1n.prototype, "motorSpeed", [property], Object.getOwnPropertyDescriptor(_class2$1n.prototype, "motorSpeed"), _class2$1n.prototype), _applyDecoratedDescriptor(_class2$1n.prototype, "enableLimit", [property], Object.getOwnPropertyDescriptor(_class2$1n.prototype, "enableLimit"), _class2$1n.prototype), _applyDecoratedDescriptor(_class2$1n.prototype, "lowerLimit", [property], Object.getOwnPropertyDescriptor(_class2$1n.prototype, "lowerLimit"), _class2$1n.prototype), _applyDecoratedDescriptor(_class2$1n.prototype, "upperLimit", [property], Object.getOwnPropertyDescriptor(_class2$1n.prototype, "upperLimit"), _class2$1n.prototype), _descriptor$1c = _applyDecoratedDescriptor(_class2$1n.prototype, "_angle", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor2$X = _applyDecoratedDescriptor(_class2$1n.prototype, "_autoCalcAngle", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _descriptor3$H = _applyDecoratedDescriptor(_class2$1n.prototype, "_enableMotor", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor4$B = _applyDecoratedDescriptor(_class2$1n.prototype, "_maxMotorForce", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1000;
              }
            }), _descriptor5$t = _applyDecoratedDescriptor(_class2$1n.prototype, "_motorSpeed", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1000;
              }
            }), _descriptor6$k = _applyDecoratedDescriptor(_class2$1n.prototype, "_enableLimit", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor7$h = _applyDecoratedDescriptor(_class2$1n.prototype, "_lowerLimit", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor8$h = _applyDecoratedDescriptor(_class2$1n.prototype, "_upperLimit", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            })), _class2$1n)) || _class$1z) || _class$1z));

            var _dec$1z, _dec2$18, _class$1A, _class2$1o, _descriptor$1d, _descriptor2$Y, _temp$1r;
            var FixedJoint2D = exports('FixedJoint2D', (_dec$1z = ccclass('cc.FixedJoint2D'), _dec2$18 = menu(), _dec$1z(_class$1A = _dec2$18(_class$1A = (_class2$1o = (_temp$1r = function (_Joint2D) {
              _inheritsLoose(FixedJoint2D, _Joint2D);

              function FixedJoint2D() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Joint2D.call.apply(_Joint2D, [this].concat(args)) || this;
                _this.TYPE = EJoint2DType.FIXED;

                _initializerDefineProperty(_this, "_frequency", _descriptor$1d, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_dampingRatio", _descriptor2$Y, _assertThisInitialized(_this));

                return _this;
              }

              _createClass(FixedJoint2D, [{
                key: "frequency",
                get: function get() {
                  return this._frequency;
                },
                set: function set(v) {
                  this._frequency = v;

                  if (this._joint) {
                    this._joint.setFrequency(v);
                  }
                }
              }, {
                key: "dampingRatio",
                get: function get() {
                  return this._dampingRatio;
                },
                set: function set(v) {
                  this._dampingRatio = v;

                  if (this._joint) {
                    this._joint.setDampingRatio(v);
                  }
                }
              }]);

              return FixedJoint2D;
            }(Joint2D), _temp$1r), (_applyDecoratedDescriptor(_class2$1o.prototype, "frequency", [property], Object.getOwnPropertyDescriptor(_class2$1o.prototype, "frequency"), _class2$1o.prototype), _applyDecoratedDescriptor(_class2$1o.prototype, "dampingRatio", [property], Object.getOwnPropertyDescriptor(_class2$1o.prototype, "dampingRatio"), _class2$1o.prototype), _descriptor$1d = _applyDecoratedDescriptor(_class2$1o.prototype, "_frequency", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0.7;
              }
            }), _descriptor2$Y = _applyDecoratedDescriptor(_class2$1o.prototype, "_dampingRatio", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0.5;
              }
            })), _class2$1o)) || _class$1A) || _class$1A));

            var _dec$1A, _dec2$19, _class$1B, _class2$1p, _descriptor$1e, _descriptor2$Z, _descriptor3$I, _descriptor4$C, _descriptor5$u, _descriptor6$l, _temp$1s;
            var WheelJoint2D = exports('WheelJoint2D', (_dec$1A = ccclass('cc.WheelJoint2D'), _dec2$19 = menu(), _dec$1A(_class$1B = _dec2$19(_class$1B = (_class2$1p = (_temp$1s = function (_Joint2D) {
              _inheritsLoose(WheelJoint2D, _Joint2D);

              function WheelJoint2D() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Joint2D.call.apply(_Joint2D, [this].concat(args)) || this;
                _this.TYPE = EJoint2DType.WHEEL;

                _initializerDefineProperty(_this, "_angle", _descriptor$1e, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_enableMotor", _descriptor2$Z, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_maxMotorTorque", _descriptor3$I, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_motorSpeed", _descriptor4$C, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_frequency", _descriptor5$u, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_dampingRatio", _descriptor6$l, _assertThisInitialized(_this));

                return _this;
              }

              _createClass(WheelJoint2D, [{
                key: "angle",
                get: function get() {
                  return this._angle;
                },
                set: function set(v) {
                  this._angle = v;
                }
              }, {
                key: "enableMotor",
                get: function get() {
                  return this._enableMotor;
                },
                set: function set(v) {
                  this._enableMotor = v;

                  if (this._joint) {
                    this._joint.enableMotor(v);
                  }
                }
              }, {
                key: "maxMotorTorque",
                get: function get() {
                  return this._maxMotorTorque;
                },
                set: function set(v) {
                  this._maxMotorTorque = v;

                  if (this._joint) {
                    this._joint.setMaxMotorTorque(v);
                  }
                }
              }, {
                key: "motorSpeed",
                get: function get() {
                  return this._motorSpeed;
                },
                set: function set(v) {
                  this._motorSpeed = v;

                  if (this._joint) {
                    this._joint.setMotorSpeed(v);
                  }
                }
              }, {
                key: "frequency",
                get: function get() {
                  return this._frequency;
                },
                set: function set(v) {
                  this._frequency = v;

                  if (this._joint) {
                    this._joint.setFrequency(v);
                  }
                }
              }, {
                key: "dampingRatio",
                get: function get() {
                  return this._dampingRatio;
                },
                set: function set(v) {
                  this._dampingRatio = v;

                  if (this._joint) {
                    this._joint.setDampingRatio(v);
                  }
                }
              }]);

              return WheelJoint2D;
            }(Joint2D), _temp$1s), (_applyDecoratedDescriptor(_class2$1p.prototype, "angle", [property], Object.getOwnPropertyDescriptor(_class2$1p.prototype, "angle"), _class2$1p.prototype), _applyDecoratedDescriptor(_class2$1p.prototype, "enableMotor", [property], Object.getOwnPropertyDescriptor(_class2$1p.prototype, "enableMotor"), _class2$1p.prototype), _applyDecoratedDescriptor(_class2$1p.prototype, "maxMotorTorque", [property], Object.getOwnPropertyDescriptor(_class2$1p.prototype, "maxMotorTorque"), _class2$1p.prototype), _applyDecoratedDescriptor(_class2$1p.prototype, "motorSpeed", [property], Object.getOwnPropertyDescriptor(_class2$1p.prototype, "motorSpeed"), _class2$1p.prototype), _applyDecoratedDescriptor(_class2$1p.prototype, "frequency", [property], Object.getOwnPropertyDescriptor(_class2$1p.prototype, "frequency"), _class2$1p.prototype), _applyDecoratedDescriptor(_class2$1p.prototype, "dampingRatio", [property], Object.getOwnPropertyDescriptor(_class2$1p.prototype, "dampingRatio"), _class2$1p.prototype), _descriptor$1e = _applyDecoratedDescriptor(_class2$1p.prototype, "_angle", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 90;
              }
            }), _descriptor2$Z = _applyDecoratedDescriptor(_class2$1p.prototype, "_enableMotor", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor3$I = _applyDecoratedDescriptor(_class2$1p.prototype, "_maxMotorTorque", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1000;
              }
            }), _descriptor4$C = _applyDecoratedDescriptor(_class2$1p.prototype, "_motorSpeed", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor5$u = _applyDecoratedDescriptor(_class2$1p.prototype, "_frequency", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 5;
              }
            }), _descriptor6$l = _applyDecoratedDescriptor(_class2$1p.prototype, "_dampingRatio", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0.7;
              }
            })), _class2$1p)) || _class$1B) || _class$1B));

            var _dec$1B, _dec2$1a, _class$1C, _class2$1q, _descriptor$1f, _descriptor2$_, _descriptor3$J, _descriptor4$D, _descriptor5$v, _descriptor6$m, _temp$1t;
            var HingeJoint2D = exports('HingeJoint2D', (_dec$1B = ccclass('cc.HingeJoint2D'), _dec2$1a = menu(), _dec$1B(_class$1C = _dec2$1a(_class$1C = (_class2$1q = (_temp$1t = function (_Joint2D) {
              _inheritsLoose(HingeJoint2D, _Joint2D);

              function HingeJoint2D() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Joint2D.call.apply(_Joint2D, [this].concat(args)) || this;
                _this.TYPE = EJoint2DType.HINGE;

                _initializerDefineProperty(_this, "_enableLimit", _descriptor$1f, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_lowerAngle", _descriptor2$_, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_upperAngle", _descriptor3$J, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_enableMotor", _descriptor4$D, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_maxMotorTorque", _descriptor5$v, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_motorSpeed", _descriptor6$m, _assertThisInitialized(_this));

                return _this;
              }

              _createClass(HingeJoint2D, [{
                key: "enableLimit",
                get: function get() {
                  return this._enableLimit;
                },
                set: function set(v) {
                  this._enableLimit = v;
                }
              }, {
                key: "lowerAngle",
                get: function get() {
                  return this._lowerAngle;
                },
                set: function set(v) {
                  this._lowerAngle = v;

                  if (this._joint) {
                    this._joint.setLowerAngle(v);
                  }
                }
              }, {
                key: "upperAngle",
                get: function get() {
                  return this._upperAngle;
                },
                set: function set(v) {
                  this._upperAngle = v;

                  if (this._joint) {
                    this._joint.setUpperAngle(v);
                  }
                }
              }, {
                key: "enableMotor",
                get: function get() {
                  return this._enableMotor;
                },
                set: function set(v) {
                  this._enableMotor = v;

                  if (this._joint) {
                    this._joint.enableMotor(v);
                  }
                }
              }, {
                key: "maxMotorTorque",
                get: function get() {
                  return this._maxMotorTorque;
                },
                set: function set(v) {
                  this._maxMotorTorque = v;

                  if (this._joint) {
                    this._joint.setMaxMotorTorque(v);
                  }
                }
              }, {
                key: "motorSpeed",
                get: function get() {
                  return this._motorSpeed;
                },
                set: function set(v) {
                  this._motorSpeed = v;

                  if (this._joint) {
                    this._joint.setMotorSpeed(v);
                  }
                }
              }]);

              return HingeJoint2D;
            }(Joint2D), _temp$1t), (_applyDecoratedDescriptor(_class2$1q.prototype, "enableLimit", [property], Object.getOwnPropertyDescriptor(_class2$1q.prototype, "enableLimit"), _class2$1q.prototype), _applyDecoratedDescriptor(_class2$1q.prototype, "lowerAngle", [property], Object.getOwnPropertyDescriptor(_class2$1q.prototype, "lowerAngle"), _class2$1q.prototype), _applyDecoratedDescriptor(_class2$1q.prototype, "upperAngle", [property], Object.getOwnPropertyDescriptor(_class2$1q.prototype, "upperAngle"), _class2$1q.prototype), _applyDecoratedDescriptor(_class2$1q.prototype, "enableMotor", [property], Object.getOwnPropertyDescriptor(_class2$1q.prototype, "enableMotor"), _class2$1q.prototype), _applyDecoratedDescriptor(_class2$1q.prototype, "maxMotorTorque", [property], Object.getOwnPropertyDescriptor(_class2$1q.prototype, "maxMotorTorque"), _class2$1q.prototype), _applyDecoratedDescriptor(_class2$1q.prototype, "motorSpeed", [property], Object.getOwnPropertyDescriptor(_class2$1q.prototype, "motorSpeed"), _class2$1q.prototype), _descriptor$1f = _applyDecoratedDescriptor(_class2$1q.prototype, "_enableLimit", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor2$_ = _applyDecoratedDescriptor(_class2$1q.prototype, "_lowerAngle", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor3$J = _applyDecoratedDescriptor(_class2$1q.prototype, "_upperAngle", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor4$D = _applyDecoratedDescriptor(_class2$1q.prototype, "_enableMotor", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor5$v = _applyDecoratedDescriptor(_class2$1q.prototype, "_maxMotorTorque", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1000;
              }
            }), _descriptor6$m = _applyDecoratedDescriptor(_class2$1q.prototype, "_motorSpeed", [property], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            })), _class2$1q)) || _class$1C) || _class$1C));

            var Physics2DUtils = exports('Physics2DUtils', {
              PolygonSeparator: PolygonSeparator
            });

            var PhysicsRayCastCallback = function (_b2$RayCastCallback) {
              _inheritsLoose(PhysicsRayCastCallback, _b2$RayCastCallback);

              function PhysicsRayCastCallback() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _b2$RayCastCallback.call.apply(_b2$RayCastCallback, [this].concat(args)) || this;
                _this._type = ERaycast2DType.Closest;
                _this._fixtures = [];
                _this._points = [];
                _this._normals = [];
                _this._fractions = [];
                _this._mask = 0xffffffff;
                return _this;
              }

              var _proto = PhysicsRayCastCallback.prototype;

              _proto.init = function 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;
              };

              _proto.ReportFixture = function ReportFixture(fixture, point, normal, fraction) {
                if ((fixture.GetFilterData().categoryBits & this._mask) === 0) {
                  return 0;
                }

                if (this._type === ERaycast2DType.Closest) {
                  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 === ERaycast2DType.Any) {
                  return 0;
                } else if (this._type >= ERaycast2DType.All) {
                  return 1;
                }

                return fraction;
              };

              _proto.getFixtures = function getFixtures() {
                return this._fixtures;
              };

              _proto.getPoints = function getPoints() {
                return this._points;
              };

              _proto.getNormals = function getNormals() {
                return this._normals;
              };

              _proto.getFractions = function getFractions() {
                return this._fractions;
              };

              return PhysicsRayCastCallback;
            }(box2d_1.RayCastCallback);

            var pools = [];
            var pointCache = [new Vec2(), new Vec2()];
            var b2worldmanifold = new box2d_1.WorldManifold();
            var worldmanifold = {
              points: [],
              separations: [],
              normal: new Vec2()
            };

            var ManifoldPoint = function ManifoldPoint() {
              this.localPoint = new Vec2();
              this.normalImpulse = 0;
              this.tangentImpulse = 0;
            };

            var manifoldPointCache = [new ManifoldPoint(), new ManifoldPoint()];
            var manifold = {
              type: 0,
              localPoint: new Vec2(),
              localNormal: new Vec2(),
              points: []
            };
            var impulse = {
              normalImpulses: [],
              tangentImpulses: []
            };
            var PhysicsContact = function () {
              function PhysicsContact() {
                this.colliderA = null;
                this.colliderB = null;
                this.disabled = false;
                this.disabledOnce = false;
                this._impulse = null;
                this._inverted = false;
                this._b2contact = null;
              }

              PhysicsContact.get = function get(b2contact) {
                var c = pools.pop();

                if (!c) {
                  c = new PhysicsContact();
                }

                c.init(b2contact);
                return c;
              };

              PhysicsContact.put = function put(b2contact) {
                var c = b2contact.m_userData;
                if (!c) return;
                pools.push(c);
                c.reset();
              };

              var _proto = PhysicsContact.prototype;

              _proto._setImpulse = function _setImpulse(impulse) {
                this._impulse = impulse;
              };

              _proto.init = function 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;
              };

              _proto.reset = function 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;
              };

              _proto.getWorldManifold = function getWorldManifold() {
                var points = worldmanifold.points;
                var separations = worldmanifold.separations;
                var normal = worldmanifold.normal;

                this._b2contact.GetWorldManifold(b2worldmanifold);

                var b2points = b2worldmanifold.points;
                var b2separations = b2worldmanifold.separations;

                var count = this._b2contact.GetManifold().pointCount;

                points.length = separations.length = count;

                for (var i = 0; i < count; i++) {
                  var 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;
              };

              _proto.getManifold = function getManifold() {
                var points = manifold.points;
                var localNormal = manifold.localNormal;
                var localPoint = manifold.localPoint;

                var b2manifold = this._b2contact.GetManifold();

                var b2points = b2manifold.points;
                var count = points.length = b2manifold.pointCount;

                for (var i = 0; i < count; i++) {
                  var p = manifoldPointCache[i];
                  var 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;
              };

              _proto.getImpulse = function getImpulse() {
                var b2impulse = this._impulse;
                if (!b2impulse) return null;
                var normalImpulses = impulse.normalImpulses;
                var tangentImpulses = impulse.tangentImpulses;
                var count = b2impulse.count;

                for (var 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;
              };

              _proto.emit = function emit(contactType) {

                var colliderA = this.colliderA;
                var colliderB = this.colliderB;
                var bodyA = colliderA.body;
                var bodyB = colliderB.body;

                if (bodyA.enabledContactListener) {
                  colliderA === null || colliderA === void 0 ? void 0 : colliderA.emit(contactType, colliderA, colliderB, this);
                }

                if (bodyB.enabledContactListener) {
                  colliderB === null || colliderB === void 0 ? void 0 : colliderB.emit(contactType, colliderB, colliderA, this);
                }

                if (bodyA.enabledContactListener || bodyB.enabledContactListener) {
                  PhysicsSystem2D.instance.emit(contactType, colliderA, colliderB);
                }

                if (this.disabled || this.disabledOnce) {
                  this.setEnabled(false);
                  this.disabledOnce = false;
                }
              };

              _proto.setEnabled = function setEnabled(value) {
                this._b2contact.SetEnabled(value);
              };

              _proto.isTouching = function isTouching() {
                return this._b2contact.IsTouching();
              };

              _proto.setTangentSpeed = function setTangentSpeed(value) {
                this._b2contact.SetTangentSpeed(value);
              };

              _proto.getTangentSpeed = function getTangentSpeed() {
                return this._b2contact.GetTangentSpeed();
              };

              _proto.setFriction = function setFriction(value) {
                this._b2contact.SetFriction(value);
              };

              _proto.getFriction = function getFriction() {
                return this._b2contact.GetFriction();
              };

              _proto.resetFriction = function resetFriction() {
                return this._b2contact.ResetFriction();
              };

              _proto.setRestitution = function setRestitution(value) {
                this._b2contact.SetRestitution(value);
              };

              _proto.getRestitution = function getRestitution() {
                return this._b2contact.GetRestitution();
              };

              _proto.resetRestitution = function resetRestitution() {
                return this._b2contact.ResetRestitution();
              };

              return PhysicsContact;
            }();

            var _tmp_vec2 = new box2d_1.Vec2();

            var _tmp_color = new Color();

            var GREEN_COLOR = Color.GREEN;
            var RED_COLOR = Color.RED;
            var PhysicsDebugDraw = function (_b2$Draw) {
              _inheritsLoose(PhysicsDebugDraw, _b2$Draw);

              function PhysicsDebugDraw(drawer) {
                var _this;

                _this = _b2$Draw.call(this) || this;
                _this._drawer = null;
                _this._xf = new box2d_1.Transform();
                _this._dxf = new box2d_1.Transform();
                _this._drawer = drawer;
                return _this;
              }

              var _proto = PhysicsDebugDraw.prototype;

              _proto._DrawPolygon = function _DrawPolygon(vertices, vertexCount) {
                var drawer = this._drawer;

                for (var i = 0; i < vertexCount; i++) {
                  box2d_1.Transform.MulXV(this._xf, vertices[i], _tmp_vec2);
                  var x = _tmp_vec2.x * PHYSICS_2D_PTM_RATIO;
                  var y = _tmp_vec2.y * PHYSICS_2D_PTM_RATIO;
                  if (i === 0) drawer.moveTo(x, y);else {
                    drawer.lineTo(x, y);
                  }
                }

                drawer.close();
              };

              _proto.DrawPolygon = function DrawPolygon(vertices, vertexCount, color) {
                this._applyStrokeColor(color);

                this._DrawPolygon(vertices, vertexCount);

                this._drawer.stroke();
              };

              _proto.DrawSolidPolygon = function DrawSolidPolygon(vertices, vertexCount, color) {
                this._applyFillColor(color);

                this._DrawPolygon(vertices, vertexCount);

                this._drawer.fill();

                this._drawer.stroke();
              };

              _proto._DrawCircle = function _DrawCircle(center, radius) {
                var p = this._xf.p;

                this._drawer.circle((center.x + p.x) * PHYSICS_2D_PTM_RATIO, (center.y + p.y) * PHYSICS_2D_PTM_RATIO, radius * PHYSICS_2D_PTM_RATIO);
              };

              _proto.DrawCircle = function DrawCircle(center, radius, color) {
                this._applyStrokeColor(color);

                this._DrawCircle(center, radius);

                this._drawer.stroke();
              };

              _proto.DrawSolidCircle = function DrawSolidCircle(center, radius, axis, color) {
                this._applyFillColor(color);

                this._DrawCircle(center, radius);

                this._drawer.fill();
              };

              _proto.DrawSegment = function DrawSegment(p1, p2, color) {
                var 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);

                box2d_1.Transform.MulXV(this._xf, p1, _tmp_vec2);
                drawer.moveTo(_tmp_vec2.x * PHYSICS_2D_PTM_RATIO, _tmp_vec2.y * PHYSICS_2D_PTM_RATIO);
                box2d_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();
              };

              _proto.DrawTransform = function DrawTransform(xf) {
                var drawer = this._drawer;
                drawer.strokeColor = RED_COLOR;
                _tmp_vec2.x = _tmp_vec2.y = 0;
                box2d_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;
                box2d_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;
                box2d_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;
                box2d_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();
              };

              _proto.DrawPoint = function DrawPoint(center, radius, color) {};

              _proto.DrawParticles = function DrawParticles() {};

              _proto._applyStrokeColor = function _applyStrokeColor(color) {
                this._drawer.strokeColor = _tmp_color.set(color.r * 255, color.g * 255, color.b * 255, 150);
              };

              _proto._applyFillColor = function _applyFillColor(color) {
                this._drawer.fillColor = _tmp_color.set(color.r * 255, color.g * 255, color.b * 255, 150);
              };

              _proto.PushTransform = function PushTransform(xf) {
                this._xf = xf;
              };

              _proto.PopTransform = function PopTransform() {
                this._xf = this._dxf;
              };

              return PhysicsDebugDraw;
            }(box2d_1.Draw);

            var tempVec3 = new Vec3();
            var tempVec2_1 = new Vec2();
            var tempVec2_2 = new Vec2();
            var temoBodyDef = new box2d_1.BodyDef();
            var tempB2AABB = new box2d_1.AABB();
            var testResults = [];
            var b2PhysicsWorld = function () {
              function b2PhysicsWorld() {
                this._world = void 0;
                this._bodies = [];
                this._animatedBodies = [];
                this._rotationAxis = new Vec3();
                this._contactListener = void 0;
                this._aabbQueryCallback = void 0;
                this._raycastQueryCallback = void 0;
                this._debugGraphics = null;
                this._b2DebugDrawer = null;
                this._debugDrawFlags = 0;
                this._world = new box2d_1.World(new box2d_1.Vec2(0, -10));
                var 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();
              }

              var _proto = b2PhysicsWorld.prototype;

              _proto._checkDebugDrawValid = function _checkDebugDrawValid() {

                if (!this._debugGraphics || !this._debugGraphics.isValid) {
                  var canvas = find('Canvas');

                  if (!canvas) {
                    var scene = director.getScene();

                    if (!scene) {
                      return;
                    }

                    canvas = new Node$1('Canvas');
                    canvas.addComponent(Canvas);
                    canvas.parent = scene;
                  }

                  var node = new Node$1('PHYSICS_2D_DEBUG_DRAW');
                  node.hideFlags |= CCObject.Flags.DontSave;
                  node.parent = canvas;
                  node.worldPosition = Vec3.ZERO;
                  this._debugGraphics = node.addComponent(Graphics);
                  this._debugGraphics.lineWidth = 2;
                  var debugDraw = new PhysicsDebugDraw(this._debugGraphics);
                  this._b2DebugDrawer = debugDraw;

                  this._world.SetDebugDraw(debugDraw);
                }

                var parent = this._debugGraphics.node.parent;

                this._debugGraphics.node.setSiblingIndex(parent.children.length - 1);

                if (this._b2DebugDrawer) {
                  this._b2DebugDrawer.SetFlags(this.debugDrawFlags);
                }
              };

              _proto.setGravity = function setGravity(v) {
                this._world.SetGravity(v);
              };

              _proto.setAllowSleep = function setAllowSleep(v) {
                this._world.SetAllowSleeping(true);
              };

              _proto.step = function step(deltaTime, velocityIterations, positionIterations) {
                if (velocityIterations === void 0) {
                  velocityIterations = 10;
                }

                if (positionIterations === void 0) {
                  positionIterations = 10;
                }

                var animatedBodies = this._animatedBodies;

                for (var i = 0, l = animatedBodies.length; i < l; i++) {
                  animatedBodies[i].animate(deltaTime);
                }

                this._world.Step(deltaTime, velocityIterations, positionIterations);
              };

              _proto.raycast = function raycast(p1, p2, type, mask) {
                if (p1.equals(p2)) {
                  return [];
                }

                type = type || ERaycast2DType.Closest;
                tempVec2_1.x = p1.x / PHYSICS_2D_PTM_RATIO;
                tempVec2_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;
                var callback = this._raycastQueryCallback;
                callback.init(type, mask);

                this._world.RayCast(callback, tempVec2_1, tempVec2_2);

                var fixtures = callback.getFixtures();

                if (fixtures.length > 0) {
                  var points = callback.getPoints();
                  var normals = callback.getNormals();
                  var fractions = callback.getFractions();
                  var results = [];

                  for (var i = 0, l = fixtures.length; i < l; i++) {
                    var fixture = fixtures[i];
                    var shape = fixture.m_userData;
                    var collider = shape.collider;

                    if (type === ERaycast2DType.AllClosest) {
                      var result = void 0;

                      for (var 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: 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 [];
              };

              _proto.syncPhysicsToScene = function syncPhysicsToScene() {
                var bodies = this._bodies;

                for (var i = 0, l = bodies.length; i < l; i++) {
                  var body = bodies[i];
                  var bodyComp = body.rigidBody;

                  if (bodyComp.type === ERigidBody2DType.Animated) {
                    body.resetVelocity();
                    continue;
                  }

                  var node = bodyComp.node;
                  var b2body = body.impl;
                  var pos = b2body.GetPosition();
                  tempVec3.x = pos.x * PHYSICS_2D_PTM_RATIO;
                  tempVec3.y = pos.y * PHYSICS_2D_PTM_RATIO;
                  tempVec3.z = 0;
                  node.worldPosition = tempVec3;
                  var angle = toDegree(b2body.GetAngle());
                  node.setWorldRotationFromEuler(0, 0, angle);
                }
              };

              _proto.syncSceneToPhysics = function syncSceneToPhysics() {
                var bodies = this._bodies;

                for (var i = 0; i < bodies.length; i++) {
                  bodies[i].syncRotationToPhysics();
                  bodies[i].syncPositionToPhysics();
                }
              };

              _proto.addBody = function addBody(body) {
                var bodies = this._bodies;

                if (bodies.includes(body)) {
                  return;
                }

                var bodyDef = temoBodyDef;
                var 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;
                var node = comp.node;
                var pos = node.worldPosition;
                bodyDef.position.Set(pos.x / PHYSICS_2D_PTM_RATIO, pos.y / PHYSICS_2D_PTM_RATIO);
                tempVec3.z = Quat.getAxisAngle(this._rotationAxis, node.worldRotation);
                bodyDef.angle = tempVec3.z;
                bodyDef.awake = comp.awakeOnLoad;

                if (comp.type === ERigidBody2DType.Animated) {
                  bodyDef.type = ERigidBody2DType.Kinematic;

                  this._animatedBodies.push(body);

                  body._animatedPos.set(bodyDef.position.x, bodyDef.position.y);

                  body._animatedAngle = bodyDef.angle;
                } else {
                  bodyDef.type = comp.type;
                }

                var compPrivate = comp;
                var linearVelocity = compPrivate._linearVelocity;
                bodyDef.linearVelocity.Set(linearVelocity.x, linearVelocity.y);
                bodyDef.angularVelocity = toRadian(compPrivate._angularVelocity);

                var b2Body = this._world.CreateBody(bodyDef);

                b2Body.m_userData = body;
                body._imp = b2Body;

                this._bodies.push(body);
              };

              _proto.removeBody = function removeBody(body) {
                if (!this._bodies.includes(body)) {
                  return;
                }

                if (body.impl) {
                  body.impl.m_userData = null;

                  this._world.DestroyBody(body.impl);

                  body._imp = null;
                }

                array.remove(this._bodies, body);
                var comp = body.rigidBody;

                if (comp.type === ERigidBody2DType.Animated) {
                  array.remove(this._animatedBodies, body);
                }
              };

              _proto.registerContactFixture = function registerContactFixture(fixture) {
                this._contactListener.registerContactFixture(fixture);
              };

              _proto.unregisterContactFixture = function unregisterContactFixture(fixture) {
                this._contactListener.unregisterContactFixture(fixture);
              };

              _proto.testPoint = function testPoint(point) {
                var x = tempVec2_1.x = point.x / PHYSICS_2D_PTM_RATIO;
                var y = tempVec2_1.y = point.y / PHYSICS_2D_PTM_RATIO;
                var 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;
                var callback = this._aabbQueryCallback;
                callback.init(tempVec2_1);

                this._world.QueryAABB(callback, tempB2AABB);

                var fixtures = callback.getFixtures();
                testResults.length = 0;

                for (var i = 0; i < fixtures.length; i++) {
                  var collider = fixtures[i].m_userData.collider;

                  if (!testResults.includes(collider)) {
                    testResults.push(collider);
                  }
                }

                return testResults;
              };

              _proto.testAABB = function 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;
                var callback = this._aabbQueryCallback;
                callback.init();

                this._world.QueryAABB(callback, tempB2AABB);

                var fixtures = callback.getFixtures();
                testResults.length = 0;

                for (var i = 0; i < fixtures.length; i++) {
                  var collider = fixtures[i].m_userData.collider;

                  if (!testResults.includes(collider)) {
                    testResults.push(collider);
                  }
                }

                return testResults;
              };

              _proto.drawDebug = function drawDebug() {
                this._checkDebugDrawValid();

                if (!this._debugGraphics) {
                  return;
                }

                this._debugGraphics.clear();

                this._world.DrawDebugData();
              };

              _proto._onBeginContact = function _onBeginContact(b2contact) {
                var c = PhysicsContact.get(b2contact);
                c.emit(Contact2DType.BEGIN_CONTACT);
              };

              _proto._onEndContact = function _onEndContact(b2contact) {
                var c = b2contact.m_userData;

                if (!c) {
                  return;
                }

                c.emit(Contact2DType.END_CONTACT);
                PhysicsContact.put(b2contact);
              };

              _proto._onPreSolve = function _onPreSolve(b2contact) {
                var c = b2contact.m_userData;

                if (!c) {
                  return;
                }

                c.emit(Contact2DType.PRE_SOLVE);
              };

              _proto._onPostSolve = function _onPostSolve(b2contact, impulse) {
                var c = b2contact.m_userData;

                if (!c) {
                  return;
                }

                c._setImpulse(impulse);

                c.emit(Contact2DType.POST_SOLVE);

                c._setImpulse(null);
              };

              _createClass(b2PhysicsWorld, [{
                key: "impl",
                get: function get() {
                  return this._world;
                }
              }, {
                key: "debugDrawFlags",
                get: function get() {
                  return this._debugDrawFlags;
                },
                set: function set(v) {

                  if (!v) {
                    if (this._debugGraphics) {
                      this._debugGraphics.node.parent = null;
                    }
                  }

                  this._debugDrawFlags = v;
                }
              }]);

              return b2PhysicsWorld;
            }();

            var tempVec3$1 = new Vec3();
            var tempVec2_1$1 = new box2d_1.Vec2();
            var b2RigidBody2D = function () {
              function b2RigidBody2D() {
                this._animatedPos = new Vec2();
                this._animatedAngle = 0;
                this._body = null;
                this._inited = false;
              }

              var _proto = b2RigidBody2D.prototype;

              _proto.initialize = function initialize(com) {
                this._rigidBody = com;

                PhysicsSystem2D.instance._callAfterStep(this, this._init);
              };

              _proto.onDestroy = function onDestroy() {
                PhysicsSystem2D.instance._callAfterStep(this, this._destroy);
              };

              _proto.onEnable = function onEnable() {
                this.setActive(true);
              };

              _proto.onDisable = function onDisable() {
                this.setActive(false);
              };

              _proto._registerNodeEvents = function _registerNodeEvents() {
                var node = this.rigidBody.node;
                node.on(Node$1.EventType.TRANSFORM_CHANGED, this._onNodeTransformChanged, this);
              };

              _proto._unregisterNodeEvents = function _unregisterNodeEvents() {
                var node = this.rigidBody.node;
                node.off(Node$1.EventType.TRANSFORM_CHANGED, this._onNodeTransformChanged, this);
              };

              _proto._onNodeTransformChanged = function _onNodeTransformChanged(type) {
                if (PhysicsSystem2D.instance.stepping) {
                  return;
                }

                if (type & Node$1.TransformBit.SCALE) {
                  var colliders = this.rigidBody.getComponents(Collider2D);

                  for (var i = 0; i < colliders.length; i++) {
                    colliders[i].apply();
                  }
                } else {
                  if (type & Node$1.TransformBit.POSITION) {
                    this.syncPositionToPhysics(true);
                  }

                  if (type & Node$1.TransformBit.ROTATION) {
                    this.syncRotationToPhysics(true);
                  }
                }
              };

              _proto._init = function _init() {
                if (this._inited) {
                  return;
                }

                this._registerNodeEvents();

                PhysicsSystem2D.instance.physicsWorld.addBody(this);
                this._inited = true;
              };

              _proto._destroy = function _destroy() {
                if (!this._inited) return;
                PhysicsSystem2D.instance.physicsWorld.removeBody(this);

                this._unregisterNodeEvents();

                this._inited = false;
              };

              _proto.animate = function animate(dt) {
                var b2body = this._body;
                if (!b2body) return;
                var b2Pos = b2body.GetPosition();
                b2body.SetAwake(true);
                var timeStep = 1 / dt;
                tempVec2_1$1.x = (this._animatedPos.x - b2Pos.x) * timeStep;
                tempVec2_1$1.y = (this._animatedPos.y - b2Pos.y) * timeStep;
                b2body.SetLinearVelocity(tempVec2_1$1);
                var b2Rotation = b2body.GetAngle();
                b2body.SetAngularVelocity((this._animatedAngle - b2Rotation) * timeStep);
              };

              _proto.syncPositionToPhysics = function syncPositionToPhysics(enableAnimated) {
                if (enableAnimated === void 0) {
                  enableAnimated = false;
                }

                var b2body = this._body;
                if (!b2body) return;
                var pos = this._rigidBody.node.worldPosition;
                var temp;
                var bodyType = this._rigidBody.type;

                if (bodyType === ERigidBody2DType.Animated) {
                  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 === ERigidBody2DType.Animated && enableAnimated) {
                  this._animatedPos.set(temp.x, temp.y);
                } else {
                  b2body.SetTransformVec(temp, b2body.GetAngle());
                }
              };

              _proto.syncRotationToPhysics = function syncRotationToPhysics(enableAnimated) {
                if (enableAnimated === void 0) {
                  enableAnimated = false;
                }

                var b2body = this._body;
                if (!b2body) return;
                var rotation = toRadian(this._rigidBody.node.eulerAngles.z);
                var bodyType = this._rigidBody.type;

                if (bodyType === ERigidBody2DType.Animated && enableAnimated) {
                  this._animatedAngle = rotation;
                } else {
                  b2body.SetTransformVec(b2body.GetPosition(), rotation);
                }
              };

              _proto.resetVelocity = function resetVelocity() {
                var b2body = this._body;
                if (!b2body) return;
                var temp = b2body.m_linearVelocity;
                temp.Set(0, 0);
                b2body.SetLinearVelocity(temp);
                b2body.SetAngularVelocity(0);
              };

              _proto.setType = function setType(v) {
                this._body.SetType(v);
              };

              _proto.setLinearDamping = function setLinearDamping(v) {
                this._body.SetLinearDamping(v);
              };

              _proto.setAngularDamping = function setAngularDamping(v) {
                this._body.SetAngularDamping(v);
              };

              _proto.setGravityScale = function setGravityScale(v) {
                this._body.SetGravityScale(v);
              };

              _proto.setFixedRotation = function setFixedRotation(v) {
                this._body.SetFixedRotation(v);
              };

              _proto.setAllowSleep = function setAllowSleep(v) {
                this._body.SetSleepingAllowed(v);
              };

              _proto.isActive = function isActive() {
                return this._body.IsActive();
              };

              _proto.setActive = function setActive(v) {
                this._body.SetActive(v);
              };

              _proto.wakeUp = function wakeUp() {
                this._body.SetAwake(true);
              };

              _proto.sleep = function sleep() {
                this._body.SetAwake(false);
              };

              _proto.getMass = function getMass() {
                return this._body.GetMass();
              };

              _proto.setLinearVelocity = function setLinearVelocity(v) {
                this._body.SetLinearVelocity(v);
              };

              _proto.getLinearVelocity = function getLinearVelocity(out) {
                var velocity = this._body.GetLinearVelocity();

                out.x = velocity.x;
                out.y = velocity.y;
                return out;
              };

              _proto.getLinearVelocityFromWorldPoint = function getLinearVelocityFromWorldPoint(worldPoint, out) {
                tempVec2_1$1.Set(worldPoint.x / PHYSICS_2D_PTM_RATIO, worldPoint.y / PHYSICS_2D_PTM_RATIO);

                this._body.GetLinearVelocityFromWorldPoint(tempVec2_1$1, out);

                out.x *= PHYSICS_2D_PTM_RATIO;
                out.y *= PHYSICS_2D_PTM_RATIO;
                return out;
              };

              _proto.setAngularVelocity = function setAngularVelocity(v) {
                this._body.SetAngularVelocity(v);
              };

              _proto.getAngularVelocity = function getAngularVelocity() {
                return toDegree(this._body.GetAngularVelocity());
              };

              _proto.getLocalVector = function getLocalVector(worldVector, out) {
                out = out || new Vec2();
                tempVec2_1$1.Set(worldVector.x / PHYSICS_2D_PTM_RATIO, worldVector.y / PHYSICS_2D_PTM_RATIO);

                this._body.GetLocalVector(tempVec2_1$1, out);

                out.x *= PHYSICS_2D_PTM_RATIO;
                out.y *= PHYSICS_2D_PTM_RATIO;
                return out;
              };

              _proto.getWorldVector = function getWorldVector(localVector, out) {
                tempVec2_1$1.Set(localVector.x / PHYSICS_2D_PTM_RATIO, localVector.y / PHYSICS_2D_PTM_RATIO);

                this._body.GetWorldVector(tempVec2_1$1, out);

                out.x *= PHYSICS_2D_PTM_RATIO;
                out.y *= PHYSICS_2D_PTM_RATIO;
                return out;
              };

              _proto.getLocalPoint = function getLocalPoint(worldPoint, out) {
                out = out || new Vec2();
                tempVec2_1$1.Set(worldPoint.x / PHYSICS_2D_PTM_RATIO, worldPoint.y / PHYSICS_2D_PTM_RATIO);

                this._body.GetLocalPoint(tempVec2_1$1, out);

                out.x *= PHYSICS_2D_PTM_RATIO;
                out.y *= PHYSICS_2D_PTM_RATIO;
                return out;
              };

              _proto.getWorldPoint = function getWorldPoint(localPoint, out) {
                out = out || new Vec2();
                tempVec2_1$1.Set(localPoint.x / PHYSICS_2D_PTM_RATIO, localPoint.y / PHYSICS_2D_PTM_RATIO);

                this._body.GetWorldPoint(tempVec2_1$1, out);

                out.x *= PHYSICS_2D_PTM_RATIO;
                out.y *= PHYSICS_2D_PTM_RATIO;
                return out;
              };

              _proto.getLocalCenter = function getLocalCenter(out) {
                out = out || new Vec2();

                var pos = this._body.GetLocalCenter();

                out.x = pos.x * PHYSICS_2D_PTM_RATIO;
                out.y = pos.y * PHYSICS_2D_PTM_RATIO;
                return out;
              };

              _proto.getWorldCenter = function getWorldCenter(out) {
                out = out || new Vec2();

                var pos = this._body.GetWorldCenter();

                out.x = pos.x * PHYSICS_2D_PTM_RATIO;
                out.y = pos.y * PHYSICS_2D_PTM_RATIO;
                return out;
              };

              _proto.getInertia = function getInertia() {
                return this._body.GetInertia();
              };

              _proto.applyForce = function applyForce(force, point, wake) {
                if (this._body) {
                  tempVec2_1$1.Set(point.x / PHYSICS_2D_PTM_RATIO, point.y / PHYSICS_2D_PTM_RATIO);

                  this._body.ApplyForce(force, tempVec2_1$1, wake);
                }
              };

              _proto.applyForceToCenter = function applyForceToCenter(force, wake) {
                if (this._body) {
                  this._body.ApplyForceToCenter(force, wake);
                }
              };

              _proto.applyTorque = function applyTorque(torque, wake) {
                if (this._body) {
                  this._body.ApplyTorque(torque, wake);
                }
              };

              _proto.applyLinearImpulse = function applyLinearImpulse(impulse, point, wake) {
                if (this._body) {
                  tempVec2_1$1.Set(point.x / PHYSICS_2D_PTM_RATIO, point.y / PHYSICS_2D_PTM_RATIO);

                  this._body.ApplyLinearImpulse(impulse, tempVec2_1$1, wake);
                }
              };

              _proto.applyLinearImpulseToCenter = function applyLinearImpulseToCenter(impulse, wake) {
                if (this._body) {
                  this._body.ApplyLinearImpulse(impulse, this._body.GetPosition(), wake);
                }
              };

              _proto.applyAngularImpulse = function applyAngularImpulse(impulse, wake) {
                if (this._body) {
                  this._body.ApplyAngularImpulse(impulse, wake);
                }
              };

              _createClass(b2RigidBody2D, [{
                key: "impl",
                get: function get() {
                  return this._body;
                }
              }, {
                key: "_imp",
                set: function set(v) {
                  this._body = v;
                }
              }, {
                key: "rigidBody",
                get: function get() {
                  return this._rigidBody;
                }
              }, {
                key: "isAwake",
                get: function get() {
                  return this._body.IsAwake();
                }
              }, {
                key: "isSleeping",
                get: function get() {
                  return !this._body.IsAwake();
                }
              }]);

              return b2RigidBody2D;
            }();

            var tempFilter = new box2d_1.Filter();

            function getFilter(shape) {
              var comp = shape.collider;
              tempFilter.categoryBits = comp.group === PhysicsGroup.DEFAULT ? comp.body.group : comp.group;
              tempFilter.maskBits = PhysicsSystem2D.instance.collisionMatrix[tempFilter.categoryBits];
              return tempFilter;
            }

            var b2Shape2D = function () {
              function b2Shape2D() {
                this._shapes = [];
                this._fixtures = [];
                this._collider = null;
                this._body = null;
                this._inited = false;
                this._rect = new Rect();
              }

              var _proto = b2Shape2D.prototype;

              _proto.initialize = function initialize(comp) {
                this._collider = comp;
              };

              _proto.onLoad = function onLoad() {};

              _proto.onEnable = function onEnable() {
                PhysicsSystem2D.instance._callAfterStep(this, this._init);
              };

              _proto.onDisable = function onDisable() {
                PhysicsSystem2D.instance._callAfterStep(this, this._destroy);
              };

              _proto.start = function start() {};

              _proto.onGroupChanged = function onGroupChanged() {
                var filter = getFilter(this);

                this._fixtures.forEach(function (f) {
                  f.SetFilterData(filter);
                });
              };

              _proto.apply = function apply() {
                this._destroy();

                this._init();
              };

              _proto.getFixtureIndex = function getFixtureIndex(fixture) {
                return this._fixtures.indexOf(fixture);
              };

              _proto._createShapes = function _createShapes(scaleX, scaleY) {
                return [];
              };

              _proto._init = function _init() {
                var _body$impl;

                if (this._inited) return;
                var comp = this.collider;
                var body = comp.getComponent(RigidBody2D);
                if (!body) return;
                var innerBody = (_body$impl = body.impl) === null || _body$impl === void 0 ? void 0 : _body$impl.impl;
                if (!innerBody) return;
                var node = body.node;
                var scale = node.worldScale;
                var shapes = scale.x === 0 && scale.y === 0 ? [] : this._createShapes(scale.x, scale.y);
                var filter = getFilter(this);

                for (var i = 0; i < shapes.length; i++) {
                  var shape = shapes[i];
                  var fixDef = {
                    density: comp.density,
                    isSensor: comp.sensor,
                    friction: comp.friction,
                    restitution: comp.restitution,
                    shape: shape,
                    filter: filter
                  };
                  var fixture = innerBody.CreateFixture(fixDef);
                  fixture.m_userData = this;

                  if (body.enabledContactListener) {
                    PhysicsSystem2D.instance.physicsWorld.registerContactFixture(fixture);
                  }

                  this._shapes.push(shape);

                  this._fixtures.push(fixture);
                }

                this._body = innerBody;
                this._inited = true;
              };

              _proto._destroy = function _destroy() {
                if (!this._inited) return;
                var fixtures = this._fixtures;
                var body = this._body;

                for (var i = fixtures.length - 1; i >= 0; i--) {
                  var 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;
              };

              _createClass(b2Shape2D, [{
                key: "impl",
                get: function get() {
                  return this._shapes;
                }
              }, {
                key: "collider",
                get: function get() {
                  return this._collider;
                }
              }, {
                key: "worldAABB",
                get: function get() {
                  var MAX = 10e6;
                  var minX = MAX;
                  var minY = MAX;
                  var maxX = -MAX;
                  var maxY = -MAX;
                  var fixtures = this._fixtures;

                  for (var i = 0; i < fixtures.length; i++) {
                    var fixture = fixtures[i];
                    var count = fixture.GetShape().GetChildCount();

                    for (var j = 0; j < count; j++) {
                      var aabb = fixture.GetAABB(j);
                      if (aabb.lowerBound.x < minX) minX = aabb.lowerBound.x;
                      if (aabb.lowerBound.y < minY) minY = aabb.lowerBound.y;
                      if (aabb.upperBound.x > maxX) maxX = aabb.upperBound.x;
                      if (aabb.upperBound.y > maxY) maxY = aabb.upperBound.y;
                    }
                  }

                  minX *= PHYSICS_2D_PTM_RATIO;
                  minY *= PHYSICS_2D_PTM_RATIO;
                  maxX *= PHYSICS_2D_PTM_RATIO;
                  maxY *= PHYSICS_2D_PTM_RATIO;
                  var r = this._rect;
                  r.x = minX;
                  r.y = minY;
                  r.width = maxX - minX;
                  r.height = maxY - minY;
                  return r;
                }
              }]);

              return b2Shape2D;
            }();

            var tempAabb = new Rect();
            var b2BoxShape = function (_b2Shape2D) {
              _inheritsLoose(b2BoxShape, _b2Shape2D);

              function b2BoxShape() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _b2Shape2D.call.apply(_b2Shape2D, [this].concat(args)) || this;
                _this._worldPoints = [new Vec2(), new Vec2(), new Vec2(), new Vec2()];
                return _this;
              }

              var _proto = b2BoxShape.prototype;

              _proto._createShapes = function _createShapes(scaleX, scaleY) {
                scaleX = Math.abs(scaleX);
                scaleY = Math.abs(scaleY);
                var comp = this.collider;
                var width = comp.size.width / 2 / PHYSICS_2D_PTM_RATIO * scaleX;
                var height = comp.size.height / 2 / PHYSICS_2D_PTM_RATIO * scaleY;
                var offsetX = comp.offset.x / PHYSICS_2D_PTM_RATIO * scaleX;
                var offsetY = comp.offset.y / PHYSICS_2D_PTM_RATIO * scaleY;
                var shape = new box2d_1.PolygonShape();
                shape.SetAsBox(width, height, new box2d_1.Vec2(offsetX, offsetY), 0);
                return [shape];
              };

              _createClass(b2BoxShape, [{
                key: "worldPoints",
                get: function get() {
                  var aabb = tempAabb;
                  var collider = this.collider;
                  var size = collider.size;
                  var 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;
                  var wps = this._worldPoints;
                  var wp0 = wps[0];
                  var wp1 = wps[1];
                  var wp2 = wps[2];
                  var wp3 = wps[3];
                  aabb.transformMat4ToPoints(collider.node.worldMatrix, wp0, wp1, wp2, wp3);
                  return wps;
                }
              }]);

              return b2BoxShape;
            }(b2Shape2D);

            var b2CircleShape = function (_b2Shape2D) {
              _inheritsLoose(b2CircleShape, _b2Shape2D);

              function b2CircleShape() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _b2Shape2D.call.apply(_b2Shape2D, [this].concat(args)) || this;
                _this._worldPosition = new Vec2();
                return _this;
              }

              var _proto = b2CircleShape.prototype;

              _proto._createShapes = function _createShapes(scaleX, scaleY) {
                scaleX = Math.abs(scaleX);
                scaleY = Math.abs(scaleY);
                var comp = this.collider;
                var offsetX = comp.offset.x / PHYSICS_2D_PTM_RATIO * scaleX;
                var offsetY = comp.offset.y / PHYSICS_2D_PTM_RATIO * scaleY;
                var shape = new box2d_1.CircleShape();
                shape.m_radius = comp.radius / PHYSICS_2D_PTM_RATIO * scaleX;
                shape.m_p.Set(offsetX, offsetY);
                return [shape];
              };

              _createClass(b2CircleShape, [{
                key: "worldRadius",
                get: function get() {
                  return this._shapes[0].m_radius * PHYSICS_2D_PTM_RATIO;
                }
              }, {
                key: "worldPosition",
                get: function get() {
                  var p = this._shapes[0].m_p;
                  return this._worldPosition.set(p.x * PHYSICS_2D_PTM_RATIO, p.y * PHYSICS_2D_PTM_RATIO);
                }
              }]);

              return b2CircleShape;
            }(b2Shape2D);

            var b2PolygonShape = function (_b2Shape2D) {
              _inheritsLoose(b2PolygonShape, _b2Shape2D);

              function b2PolygonShape() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _b2Shape2D.call.apply(_b2Shape2D, [this].concat(args)) || this;
                _this._worldPoints = [];
                return _this;
              }

              var _proto = b2PolygonShape.prototype;

              _proto._createShapes = function _createShapes(scaleX, scaleY) {
                var shapes = [];
                var comp = this.collider;
                var points = comp.points;

                if (points.length > 0 && points[0].equals(points[points.length - 1])) {
                  points.length -= 1;
                }

                var polys = ConvexPartition(points);
                var offset = comp.offset;

                for (var i = 0; i < polys.length; i++) {
                  var poly = polys[i];
                  var shape = null;
                  var vertices = [];
                  var firstVertice = null;

                  for (var j = 0, l = poly.length; j < l; j++) {
                    if (!shape) {
                      shape = new box2d_1.PolygonShape();
                    }

                    var p = poly[j];
                    var x = (p.x + offset.x) / PHYSICS_2D_PTM_RATIO * scaleX;
                    var y = (p.y + offset.y) / PHYSICS_2D_PTM_RATIO * scaleY;
                    var v = new box2d_1.Vec2(x, y);
                    vertices.push(v);

                    if (!firstVertice) {
                      firstVertice = v;
                    }

                    if (vertices.length === box2d_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;
              };

              _createClass(b2PolygonShape, [{
                key: "worldPoints",
                get: function get() {
                  var comp = this.collider;
                  var points = comp.points;
                  var worldPoints = this._worldPoints;
                  var m = comp.node.worldMatrix;

                  for (var 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;
                }
              }]);

              return b2PolygonShape;
            }(b2Shape2D);

            var b2Joint = function () {
              function b2Joint() {
                this._b2joint = null;
                this._jointComp = null;
                this._body = null;
                this._inited = false;
              }

              var _proto = b2Joint.prototype;

              _proto.initialize = function initialize(comp) {
                this._jointComp = comp;
              };

              _proto.onEnable = function onEnable() {
                PhysicsSystem2D.instance._callAfterStep(this, this._init);
              };

              _proto.onDisable = function onDisable() {
                PhysicsSystem2D.instance._callAfterStep(this, this._destroy);
              };

              _proto.start = function start() {
                PhysicsSystem2D.instance._callAfterStep(this, this._init);
              };

              _proto._init = function _init() {
                if (this._inited) return;
                var comp = this._jointComp;

                if (!comp.isValid) {
                  return;
                }

                this._body = comp.getComponent(RigidBody2D);

                var def = this._createJointDef();

                if (!def) {
                  return;
                }

                var connectedBody = comp.connectedBody;

                if (!connectedBody || !connectedBody.enabledInHierarchy) {
                  return;
                }

                def.bodyA = this._body.impl.impl;
                def.bodyB = connectedBody.impl.impl;
                def.collideConnected = comp.collideConnected;
                this._b2joint = PhysicsSystem2D.instance.physicsWorld.impl.CreateJoint(def);
                this._inited = true;
              };

              _proto._destroy = function _destroy() {
                if (!this._inited) return;
                PhysicsSystem2D.instance.physicsWorld.impl.DestroyJoint(this._b2joint);
                this._b2joint = null;
                this._inited = false;
              };

              _proto._createJointDef = function _createJointDef() {
                return null;
              };

              _proto.isValid = function isValid() {
                return this._b2joint && this._body && this._body.impl && this._jointComp && this._jointComp.connectedBody && this._jointComp.connectedBody.impl;
              };

              _createClass(b2Joint, [{
                key: "impl",
                get: function get() {
                  return this._b2joint;
                }
              }, {
                key: "comp",
                get: function get() {
                  return this._jointComp;
                }
              }, {
                key: "body",
                get: function get() {
                  return this._body;
                }
              }]);

              return b2Joint;
            }();

            var tempB2Vec2 = new box2d_1.Vec2();
            var b2MouseJoint = function (_b2Joint) {
              _inheritsLoose(b2MouseJoint, _b2Joint);

              function b2MouseJoint() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _b2Joint.call.apply(_b2Joint, [this].concat(args)) || this;
                _this._touchPoint = new Vec2();
                _this._isTouched = false;
                return _this;
              }

              var _proto = b2MouseJoint.prototype;

              _proto.setTarget = function 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);
                }
              };

              _proto.setDampingRatio = function setDampingRatio(v) {
                if (this._b2joint) {
                  this._b2joint.SetDampingRatio(v);
                }
              };

              _proto.setFrequency = function setFrequency(v) {
                if (this._b2joint) {
                  this._b2joint.SetFrequency(v);
                }
              };

              _proto.setMaxForce = function setMaxForce(v) {
                if (this._b2joint) {
                  this._b2joint.SetMaxForce(v);
                }
              };

              _proto._createJointDef = function _createJointDef() {
                var def = new box2d_1.MouseJointDef();
                var 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;
              };

              _proto.initialize = function initialize(comp) {
                _b2Joint.prototype.initialize.call(this, comp);

                var canvas = find('Canvas');

                if (canvas) {
                  canvas.on(SystemEventType.TOUCH_START, this.onTouchBegan, this);
                  canvas.on(SystemEventType.TOUCH_MOVE, this.onTouchMove, this);
                  canvas.on(SystemEventType.TOUCH_END, this.onTouchEnd, this);
                  canvas.on(SystemEventType.TOUCH_CANCEL, this.onTouchEnd, this);
                }
              };

              _proto.onEnable = function onEnable() {};

              _proto.start = function start() {};

              _proto.onTouchBegan = function onTouchBegan(event) {
                this._isTouched = true;

                var target = this._touchPoint.set(event.getUILocation());

                var world = PhysicsSystem2D.instance.physicsWorld;
                var colliders = world.testPoint(target);
                if (colliders.length <= 0) return;
                var body = colliders[0].body;
                body.wakeUp();
                var comp = this._jointComp;
                comp.connectedBody = body;

                this._init();

                this.setMaxForce(comp.maxForce * body.getMass());
                this.setTarget(target);
              };

              _proto.onTouchMove = function onTouchMove(event) {
                this._touchPoint = event.getUILocation();
              };

              _proto.onTouchEnd = function onTouchEnd(event) {
                this._destroy();

                this._isTouched = false;
              };

              _proto.update = function update() {
                if (!this._isTouched || !this.isValid()) {
                  return;
                }

                this.setTarget(this._touchPoint);
              };

              return b2MouseJoint;
            }(b2Joint);

            var b2DistanceJoint = function (_b2Joint) {
              _inheritsLoose(b2DistanceJoint, _b2Joint);

              function b2DistanceJoint() {
                return _b2Joint.apply(this, arguments) || this;
              }

              var _proto = b2DistanceJoint.prototype;

              _proto.setMaxLength = function setMaxLength(v) {
                if (this._b2joint) {
                  this._b2joint.SetMaxLength(v);
                }
              };

              _proto._createJointDef = function _createJointDef() {
                var comp = this._jointComp;
                var def = new box2d_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;
              };

              return b2DistanceJoint;
            }(b2Joint);

            var b2SpringJoint = function (_b2Joint) {
              _inheritsLoose(b2SpringJoint, _b2Joint);

              function b2SpringJoint() {
                return _b2Joint.apply(this, arguments) || this;
              }

              var _proto = b2SpringJoint.prototype;

              _proto.setDampingRatio = function setDampingRatio(v) {
                if (this._b2joint) {
                  this._b2joint.SetDampingRatio(v);
                }
              };

              _proto.setFrequency = function setFrequency(v) {
                if (this._b2joint) {
                  this._b2joint.SetFrequency(v);
                }
              };

              _proto.setDistance = function setDistance(v) {
                if (this._b2joint) {
                  this._b2joint.SetLength(v);
                }
              };

              _proto._createJointDef = function _createJointDef() {
                var comp = this._jointComp;
                var def = new box2d_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;
              };

              return b2SpringJoint;
            }(b2Joint);

            var b2RelativeJoint = function (_b2Joint) {
              _inheritsLoose(b2RelativeJoint, _b2Joint);

              function b2RelativeJoint() {
                return _b2Joint.apply(this, arguments) || this;
              }

              var _proto = b2RelativeJoint.prototype;

              _proto.setMaxForce = function setMaxForce(v) {
                if (this._b2joint) {
                  this._b2joint.SetMaxForce(v);
                }
              };

              _proto.setAngularOffset = function setAngularOffset(v) {
                if (this._b2joint) {
                  this._b2joint.SetAngularOffset(toRadian(v));
                }
              };

              _proto.setLinearOffset = function setLinearOffset(v) {
                if (this._b2joint) {
                  this._b2joint.SetLinearOffset(new box2d_1.Vec2(v.x / PHYSICS_2D_PTM_RATIO, v.y / PHYSICS_2D_PTM_RATIO));
                }
              };

              _proto.setCorrectionFactor = function setCorrectionFactor(v) {
                if (this._b2joint) {
                  this._b2joint.m_correctionFactor = v;
                }
              };

              _proto.setMaxTorque = function setMaxTorque(v) {
                if (this._b2joint) {
                  this._b2joint.SetMaxTorque(v);
                }
              };

              _proto._createJointDef = function _createJointDef() {
                var comp = this._jointComp;
                var def = new box2d_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;
              };

              return b2RelativeJoint;
            }(b2Joint);

            var b2SliderJoint = function (_b2Joint) {
              _inheritsLoose(b2SliderJoint, _b2Joint);

              function b2SliderJoint() {
                return _b2Joint.apply(this, arguments) || this;
              }

              var _proto = b2SliderJoint.prototype;

              _proto.enableLimit = function enableLimit(v) {
                if (this._b2joint) {
                  this._b2joint.EnableLimit(v);
                }
              };

              _proto.setLowerLimit = function setLowerLimit(v) {
                this.updateLimits();
              };

              _proto.setUpperLimit = function setUpperLimit(v) {
                this.updateLimits();
              };

              _proto.updateLimits = function updateLimits() {
                if (this._b2joint) {
                  var comp = this._jointComp;

                  this._b2joint.SetLimits(comp.lowerLimit / PHYSICS_2D_PTM_RATIO, comp.upperLimit / PHYSICS_2D_PTM_RATIO);
                }
              };

              _proto.enableMotor = function enableMotor(v) {
                if (this._b2joint) {
                  this._b2joint.EnableMotor(v);
                }
              };

              _proto.setMaxMotorForce = function setMaxMotorForce(v) {
                if (this._b2joint) {
                  this._b2joint.SetMaxMotorForce(v);
                }
              };

              _proto.setMotorSpeed = function setMotorSpeed(v) {
                if (this._b2joint) {
                  this._b2joint.SetMotorSpeed(v);
                }
              };

              _proto._createJointDef = function _createJointDef() {
                var comp = this._jointComp;
                var def = new box2d_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);
                var 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;
              };

              return b2SliderJoint;
            }(b2Joint);

            var b2FixedJoint = function (_b2Joint) {
              _inheritsLoose(b2FixedJoint, _b2Joint);

              function b2FixedJoint() {
                return _b2Joint.apply(this, arguments) || this;
              }

              var _proto = b2FixedJoint.prototype;

              _proto.setFrequency = function setFrequency(v) {
                if (this._b2joint) {
                  this._b2joint.SetFrequency(v);
                }
              };

              _proto.setDampingRatio = function setDampingRatio(v) {
                if (this._b2joint) {
                  this._b2joint.SetDampingRatio(v);
                }
              };

              _proto._createJointDef = function _createJointDef() {
                var comp = this._jointComp;
                var def = new box2d_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;
              };

              return b2FixedJoint;
            }(b2Joint);

            var b2WheelJoint = function (_b2Joint) {
              _inheritsLoose(b2WheelJoint, _b2Joint);

              function b2WheelJoint() {
                return _b2Joint.apply(this, arguments) || this;
              }

              var _proto = b2WheelJoint.prototype;

              _proto.setDampingRatio = function setDampingRatio(v) {
                if (this._b2joint) {
                  this._b2joint.SetSpringDampingRatio(v);
                }
              };

              _proto.setFrequency = function setFrequency(v) {
                if (this._b2joint) {
                  this._b2joint.SetSpringFrequencyHz(v);
                }
              };

              _proto.enableMotor = function enableMotor(v) {
                if (this._b2joint) {
                  this._b2joint.EnableMotor(v);
                }
              };

              _proto.setMaxMotorTorque = function setMaxMotorTorque(v) {
                if (this._b2joint) {
                  this._b2joint.SetMaxMotorTorque(v);
                }
              };

              _proto.setMotorSpeed = function setMotorSpeed(v) {
                if (this._b2joint) {
                  this._b2joint.SetMotorSpeed(v);
                }
              };

              _proto._createJointDef = function _createJointDef() {
                var comp = this._jointComp;
                var def = new box2d_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);
                var 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;
              };

              return b2WheelJoint;
            }(b2Joint);

            var b2HingeJoint = function (_b2Joint) {
              _inheritsLoose(b2HingeJoint, _b2Joint);

              function b2HingeJoint() {
                return _b2Joint.apply(this, arguments) || this;
              }

              var _proto = b2HingeJoint.prototype;

              _proto.enableLimit = function enableLimit(v) {
                if (this._b2joint) {
                  this._b2joint.EnableLimit(v);
                }
              };

              _proto.setLowerAngle = function setLowerAngle(v) {
                this.updateLimits();
              };

              _proto.setUpperAngle = function setUpperAngle(v) {
                this.updateLimits();
              };

              _proto.updateLimits = function updateLimits() {
                if (this._b2joint) {
                  var comp = this._jointComp;

                  this._b2joint.SetLimits(toRadian(comp.lowerAngle), toRadian(comp.upperAngle));
                }
              };

              _proto.enableMotor = function enableMotor(v) {
                if (this._b2joint) {
                  this._b2joint.EnableMotor(v);
                }
              };

              _proto.setMaxMotorTorque = function setMaxMotorTorque(v) {
                if (this._b2joint) {
                  this._b2joint.SetMaxMotorTorque(v);
                }
              };

              _proto.setMotorSpeed = function setMotorSpeed(v) {
                if (this._b2joint) {
                  this._b2joint.SetMotorSpeed(v);
                }
              };

              _proto._createJointDef = function _createJointDef() {
                var comp = this._jointComp;
                var def = new box2d_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 = comp.lowerAngle;
                def.upperAngle = comp.upperAngle;
                return def;
              };

              return b2HingeJoint;
            }(b2Joint);

            select('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
            });

            function lineLine(a1, a2, b1, b2) {
              var ua_t = (b2.x - b1.x) * (a1.y - b1.y) - (b2.y - b1.y) * (a1.x - b1.x);
              var ub_t = (a2.x - a1.x) * (a1.y - b1.y) - (a2.y - a1.y) * (a1.x - b1.x);
              var u_b = (b2.y - b1.y) * (a2.x - a1.x) - (b2.x - b1.x) * (a2.y - a1.y);

              if (u_b !== 0) {
                var ua = ua_t / u_b;
                var ub = ub_t / u_b;

                if (ua >= 0 && ua <= 1 && ub >= 0 && ub <= 1) {
                  return true;
                }
              }

              return false;
            }

            var tempR1 = new Vec2();
            var tempR2 = new Vec2();
            var tempR3 = new Vec2();
            var tempR4 = new Vec2();

            function lineRect(a1, a2, b) {
              var r0 = tempR1.set(b.x, b.y);
              var r1 = tempR2.set(b.x, b.yMax);
              var r2 = tempR3.set(b.xMax, b.yMax);
              var 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) {
              var length = b.length;

              for (var i = 0; i < length; ++i) {
                var b1 = b[i];
                var b2 = b[(i + 1) % length];
                if (lineLine(a1, a2, b1, b2)) return true;
              }

              return false;
            }

            function rectRect(a, b) {
              var a_min_x = a.x;
              var a_min_y = a.y;
              var a_max_x = a.x + a.width;
              var a_max_y = a.y + a.height;
              var b_min_x = b.x;
              var b_min_y = b.y;
              var b_max_x = b.x + b.width;
              var 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) {
              var r0 = tempR1.set(a.x, a.y);
              var r1 = tempR2.set(a.x, a.yMax);
              var r2 = tempR3.set(a.xMax, a.yMax);
              var 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 (var 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) {
              var i;
              var l;

              for (i = 0, l = a.length; i < l; ++i) {
                var a1 = a[i];
                var 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) {
              var distance = Vec2.distance(c1p, c2p);
              return distance < c1r + c2r;
            }

            function polygonCircle(polygon, cp, cr) {
              var position = cp;

              if (pointInPolygon(position, polygon)) {
                return true;
              }

              for (var i = 0, l = polygon.length; i < l; i++) {
                var start = i === 0 ? polygon[polygon.length - 1] : polygon[i - 1];
                var end = polygon[i];

                if (pointLineDistance(position, start, end, true) < cr) {
                  return true;
                }
              }

              return false;
            }

            function rectCircle(rect, cp, cr) {
              var cx = cp.x;
              var cy = cp.y;
              var rx = rect.x;
              var ry = rect.y;
              var rw = rect.width;
              var rh = rect.height;
              var testX = cx;
              var 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;
              var distX = cx - testX;
              var distY = cy - testY;
              var distance = Math.sqrt(distX * distX + distY * distY);

              if (distance <= cr) {
                return true;
              }

              return false;
            }

            function pointInPolygon(point, polygon) {
              var inside = false;
              var x = point.x;
              var y = point.y;
              var length = polygon.length;

              for (var i = 0, j = length - 1; i < length; j = i++) {
                var xi = polygon[i].x;
                var yi = polygon[i].y;
                var xj = polygon[j].x;
                var yj = polygon[j].y;
                var 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) {
              var dx = end.x - start.x;
              var dy = end.y - start.y;
              var d = dx * dx + dy * dy;
              var t = ((point.x - start.x) * dx + (point.y - start.y) * dy) / d;
              var 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);
            }

            var Intersection2D = exports('Intersection2D', function 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 BufferBlob = function () {
              function BufferBlob() {
                this._arrayBufferOrPaddings = [];
                this._length = 0;
              }

              var _proto = BufferBlob.prototype;

              _proto.setNextAlignment = function setNextAlignment(align) {
                if (align !== 0) {
                  var remainder = this._length % align;

                  if (remainder !== 0) {
                    var padding = align - remainder;

                    this._arrayBufferOrPaddings.push(padding);

                    this._length += padding;
                  }
                }
              };

              _proto.addBuffer = function addBuffer(arrayBuffer) {
                var result = this._length;

                this._arrayBufferOrPaddings.push(arrayBuffer);

                this._length += arrayBuffer.byteLength;
                return result;
              };

              _proto.getLength = function getLength() {
                return this._length;
              };

              _proto.getCombined = function getCombined() {
                var result = new Uint8Array(this._length);
                var counter = 0;

                this._arrayBufferOrPaddings.forEach(function (arrayBufferOrPadding) {
                  if (typeof arrayBufferOrPadding === 'number') {
                    counter += arrayBufferOrPadding;
                  } else {
                    result.set(new Uint8Array(arrayBufferOrPadding), counter);
                    counter += arrayBufferOrPadding.byteLength;
                  }
                });

                return result.buffer;
              };

              return BufferBlob;
            }();

            var StdMorphRendering = function () {
              function StdMorphRendering(mesh, gfxDevice) {
                this._mesh = void 0;
                this._subMeshRenderings = [];
                this._mesh = mesh;

                if (!this._mesh.struct.morph) {
                  return;
                }

                var nSubMeshes = this._mesh.struct.primitives.length;
                this._subMeshRenderings = new Array(nSubMeshes).fill(null);

                for (var iSubMesh = 0; iSubMesh < nSubMeshes; ++iSubMesh) {
                  var subMeshMorph = this._mesh.struct.morph.subMeshMorphs[iSubMesh];

                  if (!subMeshMorph) {
                    continue;
                  }

                  if ( subMeshMorph.targets.length > UBOMorph.MAX_MORPH_TARGET_COUNT) {
                    this._subMeshRenderings[iSubMesh] = new CpuComputing(this._mesh, iSubMesh, this._mesh.struct.morph, gfxDevice);
                  } else {
                    this._subMeshRenderings[iSubMesh] = new GpuComputing(this._mesh, iSubMesh, this._mesh.struct.morph, gfxDevice);
                  }
                }
              }

              var _proto = StdMorphRendering.prototype;

              _proto.createInstance = function createInstance() {
                var _this = this;

                var nSubMeshes = this._mesh.struct.primitives.length;
                var subMeshInstances = new Array(nSubMeshes);

                for (var iSubMesh = 0; iSubMesh < nSubMeshes; ++iSubMesh) {
                  var _this$_subMeshRenderi, _this$_subMeshRenderi2;

                  subMeshInstances[iSubMesh] = (_this$_subMeshRenderi = (_this$_subMeshRenderi2 = this._subMeshRenderings[iSubMesh]) === null || _this$_subMeshRenderi2 === void 0 ? void 0 : _this$_subMeshRenderi2.createInstance()) !== null && _this$_subMeshRenderi !== void 0 ? _this$_subMeshRenderi : null;
                }

                return {
                  setWeights: function setWeights(subMeshIndex, weights) {
                    var _subMeshInstances$sub;

                    (_subMeshInstances$sub = subMeshInstances[subMeshIndex]) === null || _subMeshInstances$sub === void 0 ? void 0 : _subMeshInstances$sub.setWeights(weights);
                  },
                  requiredPatches: function requiredPatches(subMeshIndex) {
                    assertIsNonNullable(_this._mesh.struct.morph);
                    var subMeshMorph = _this._mesh.struct.morph.subMeshMorphs[subMeshIndex];
                    var subMeshRenderingInstance = subMeshInstances[subMeshIndex];

                    if (subMeshRenderingInstance === null) {
                      return null;
                    }

                    assertIsNonNullable(subMeshMorph);
                    var patches = [{
                      name: 'CC_USE_MORPH',
                      value: true
                    }, {
                      name: 'CC_MORPH_TARGET_COUNT',
                      value: subMeshMorph.targets.length
                    }];

                    if (subMeshMorph.attributes.includes(AttributeName.ATTR_POSITION)) {
                      patches.push({
                        name: 'CC_MORPH_TARGET_HAS_POSITION',
                        value: true
                      });
                    }

                    if (subMeshMorph.attributes.includes(AttributeName.ATTR_NORMAL)) {
                      patches.push({
                        name: 'CC_MORPH_TARGET_HAS_NORMAL',
                        value: true
                      });
                    }

                    if (subMeshMorph.attributes.includes(AttributeName.ATTR_TANGENT)) {
                      patches.push({
                        name: 'CC_MORPH_TARGET_HAS_TANGENT',
                        value: true
                      });
                    }

                    patches.push.apply(patches, subMeshRenderingInstance.requiredPatches());
                    return patches;
                  },
                  adaptPipelineState: function adaptPipelineState(subMeshIndex, descriptorSet) {
                    var _subMeshInstances$sub2;

                    (_subMeshInstances$sub2 = subMeshInstances[subMeshIndex]) === null || _subMeshInstances$sub2 === void 0 ? void 0 : _subMeshInstances$sub2.adaptPipelineState(descriptorSet);
                  },
                  destroy: function destroy() {
                    for (var _iterator = _createForOfIteratorHelperLoose(subMeshInstances), _step; !(_step = _iterator()).done;) {
                      var subMeshInstance = _step.value;
                      subMeshInstance === null || subMeshInstance === void 0 ? void 0 : subMeshInstance.destroy();
                    }
                  }
                };
              };

              return StdMorphRendering;
            }();

            var GpuComputing = function () {
              function GpuComputing(mesh, subMeshIndex, morph, gfxDevice) {
                this._gfxDevice = void 0;
                this._subMeshMorph = void 0;
                this._textureInfo = void 0;
                this._attributes = void 0;
                this._verticesCount = void 0;
                this._gfxDevice = gfxDevice;
                var subMeshMorph = morph.subMeshMorphs[subMeshIndex];
                assertIsNonNullable(subMeshMorph);
                this._subMeshMorph = subMeshMorph;
                enableVertexId(mesh, subMeshIndex, gfxDevice);
                var nVertices = mesh.struct.vertexBundles[mesh.struct.primitives[subMeshIndex].vertexBundelIndices[0]].view.count;
                this._verticesCount = nVertices;
                var nTargets = subMeshMorph.targets.length;
                var vec4Required = nVertices * nTargets;
                var vec4TextureFactory = createVec4TextureFactory(gfxDevice, vec4Required);
                this._textureInfo = {
                  width: vec4TextureFactory.width,
                  height: vec4TextureFactory.height
                };
                this._attributes = subMeshMorph.attributes.map(function (attributeName, attributeIndex) {
                  var vec4Tex = vec4TextureFactory.create();
                  var valueView = vec4Tex.valueView;
                  subMeshMorph.targets.forEach(function (morphTarget, morphTargetIndex) {
                    var displacementsView = morphTarget.displacements[attributeIndex];
                    var displacements = new Float32Array(mesh.data.buffer, mesh.data.byteOffset + displacementsView.offset, displacementsView.count);
                    var displacementsOffset = nVertices * morphTargetIndex * 4;

                    for (var iVertex = 0; iVertex < nVertices; ++iVertex) {
                      valueView[displacementsOffset + 4 * iVertex + 0] = displacements[3 * iVertex + 0];
                      valueView[displacementsOffset + 4 * iVertex + 1] = displacements[3 * iVertex + 1];
                      valueView[displacementsOffset + 4 * iVertex + 2] = displacements[3 * iVertex + 2];
                    }
                  });
                  vec4Tex.updatePixels();
                  return {
                    name: attributeName,
                    morphTexture: vec4Tex
                  };
                });
              }

              var _proto2 = GpuComputing.prototype;

              _proto2.destroy = function destroy() {
                for (var _iterator2 = _createForOfIteratorHelperLoose(this._attributes), _step2; !(_step2 = _iterator2()).done;) {
                  var attribute = _step2.value;
                  attribute.morphTexture.destroy();
                }
              };

              _proto2.createInstance = function createInstance() {
                var _this2 = this;

                var morphUniforms = new MorphUniforms(this._gfxDevice, this._subMeshMorph.targets.length);
                morphUniforms.setMorphTextureInfo(this._textureInfo.width, this._textureInfo.height);
                morphUniforms.setVerticesCount(this._verticesCount);
                morphUniforms.commit();
                return {
                  setWeights: function setWeights(weights) {
                    morphUniforms.setWeights(weights);
                    morphUniforms.commit();
                  },
                  requiredPatches: function requiredPatches() {
                    return [{
                      name: 'CC_MORPH_TARGET_USE_TEXTURE',
                      value: true
                    }];
                  },
                  adaptPipelineState: function adaptPipelineState(descriptorSet) {
                    for (var _iterator3 = _createForOfIteratorHelperLoose(_this2._attributes), _step3; !(_step3 = _iterator3()).done;) {
                      var attribute = _step3.value;
                      var binding = void 0;

                      switch (attribute.name) {
                        case AttributeName.ATTR_POSITION:
                          binding = UNIFORM_POSITION_MORPH_TEXTURE_BINDING;
                          break;

                        case AttributeName.ATTR_NORMAL:
                          binding = UNIFORM_NORMAL_MORPH_TEXTURE_BINDING;
                          break;

                        case AttributeName.ATTR_TANGENT:
                          binding = UNIFORM_TANGENT_MORPH_TEXTURE_BINDING;
                          break;

                        default:
                          warn('Unexpected attribute!');
                          break;
                      }

                      if (binding !== undefined) {
                        descriptorSet.bindSampler(binding, attribute.morphTexture.sampler);
                        descriptorSet.bindTexture(binding, attribute.morphTexture.texture);
                      }
                    }

                    descriptorSet.bindBuffer(UBOMorph.BINDING, morphUniforms.buffer);
                    descriptorSet.update();
                  },
                  destroy: function destroy() {}
                };
              };

              return GpuComputing;
            }();

            var CpuComputing = function () {
              function CpuComputing(mesh, subMeshIndex, morph, gfxDevice) {
                this._gfxDevice = void 0;
                this._attributes = [];
                this._gfxDevice = gfxDevice;
                var subMeshMorph = morph.subMeshMorphs[subMeshIndex];
                assertIsNonNullable(subMeshMorph);
                enableVertexId(mesh, subMeshIndex, gfxDevice);
                this._attributes = subMeshMorph.attributes.map(function (attributeName, attributeIndex) {
                  return {
                    name: attributeName,
                    targets: subMeshMorph.targets.map(function (attributeDisplacement) {
                      return {
                        displacements: new Float32Array(mesh.data.buffer, mesh.data.byteOffset + attributeDisplacement.displacements[attributeIndex].offset, attributeDisplacement.displacements[attributeIndex].count)
                      };
                    })
                  };
                });
              }

              var _proto3 = CpuComputing.prototype;

              _proto3.createInstance = function createInstance() {
                return new CpuComputingRenderingInstance(this, this._attributes[0].targets[0].displacements.length / 3, this._gfxDevice);
              };

              _createClass(CpuComputing, [{
                key: "data",
                get: function get() {
                  return this._attributes;
                }
              }]);

              return CpuComputing;
            }();

            var CpuComputingRenderingInstance = function () {
              function CpuComputingRenderingInstance(owner, nVertices, gfxDevice) {
                this._attributes = void 0;
                this._owner = void 0;
                this._morphUniforms = void 0;
                this._owner = owner;
                this._morphUniforms = new MorphUniforms(gfxDevice, 0);
                var vec4TextureFactory = createVec4TextureFactory(gfxDevice, nVertices);

                this._morphUniforms.setMorphTextureInfo(vec4TextureFactory.width, vec4TextureFactory.height);

                this._morphUniforms.commit();

                this._attributes = this._owner.data.map(function (attributeMorph, attributeIndex) {
                  var morphTexture = vec4TextureFactory.create();
                  return {
                    attributeName: attributeMorph.name,
                    morphTexture: morphTexture
                  };
                });
              }

              var _proto4 = CpuComputingRenderingInstance.prototype;

              _proto4.setWeights = function setWeights(weights) {
                for (var iAttribute = 0; iAttribute < this._attributes.length; ++iAttribute) {
                  var myAttribute = this._attributes[iAttribute];
                  var valueView = myAttribute.morphTexture.valueView;
                  var attributeMorph = this._owner.data[iAttribute];
                  assertIsTrue(weights.length === attributeMorph.targets.length);

                  for (var iTarget = 0; iTarget < attributeMorph.targets.length; ++iTarget) {
                    var targetDisplacements = attributeMorph.targets[iTarget].displacements;
                    var weight = weights[iTarget];
                    var nVertices = targetDisplacements.length / 3;

                    if (iTarget === 0) {
                      for (var iVertex = 0; iVertex < nVertices; ++iVertex) {
                        valueView[4 * iVertex + 0] = targetDisplacements[3 * iVertex + 0] * weight;
                        valueView[4 * iVertex + 1] = targetDisplacements[3 * iVertex + 1] * weight;
                        valueView[4 * iVertex + 2] = targetDisplacements[3 * iVertex + 2] * weight;
                      }
                    } else if (weight !== 0.0) {
                      for (var _iVertex = 0; _iVertex < nVertices; ++_iVertex) {
                        valueView[4 * _iVertex + 0] += targetDisplacements[3 * _iVertex + 0] * weight;
                        valueView[4 * _iVertex + 1] += targetDisplacements[3 * _iVertex + 1] * weight;
                        valueView[4 * _iVertex + 2] += targetDisplacements[3 * _iVertex + 2] * weight;
                      }
                    }
                  }

                  myAttribute.morphTexture.updatePixels();
                }
              };

              _proto4.requiredPatches = function requiredPatches() {
                return [{
                  name: 'CC_MORPH_TARGET_USE_TEXTURE',
                  value: true
                }, {
                  name: 'CC_MORPH_PRECOMPUTED',
                  value: true
                }];
              };

              _proto4.adaptPipelineState = function adaptPipelineState(descriptorSet) {
                for (var _iterator4 = _createForOfIteratorHelperLoose(this._attributes), _step4; !(_step4 = _iterator4()).done;) {
                  var attribute = _step4.value;
                  var attributeName = attribute.attributeName;
                  var binding = void 0;

                  switch (attributeName) {
                    case AttributeName.ATTR_POSITION:
                      binding = UNIFORM_POSITION_MORPH_TEXTURE_BINDING;
                      break;

                    case AttributeName.ATTR_NORMAL:
                      binding = UNIFORM_NORMAL_MORPH_TEXTURE_BINDING;
                      break;

                    case AttributeName.ATTR_TANGENT:
                      binding = UNIFORM_TANGENT_MORPH_TEXTURE_BINDING;
                      break;

                    default:
                      warn('Unexpected attribute!');
                      break;
                  }

                  if (binding !== undefined) {
                    descriptorSet.bindSampler(binding, attribute.morphTexture.sampler);
                    descriptorSet.bindTexture(binding, attribute.morphTexture.texture);
                  }
                }

                descriptorSet.bindBuffer(UBOMorph.BINDING, this._morphUniforms.buffer);
                descriptorSet.update();
              };

              _proto4.destroy = function destroy() {
                this._morphUniforms.destroy();

                for (var iAttribute = 0; iAttribute < this._attributes.length; ++iAttribute) {
                  var myAttribute = this._attributes[iAttribute];
                  myAttribute.morphTexture.destroy();
                }
              };

              return CpuComputingRenderingInstance;
            }();

            var MorphUniforms = function () {
              function MorphUniforms(gfxDevice, targetCount) {
                this._targetCount = void 0;
                this._localBuffer = void 0;
                this._remoteBuffer = void 0;
                this._targetCount = targetCount;
                this._localBuffer = new DataView(new ArrayBuffer(UBOMorph.SIZE));
                this._remoteBuffer = gfxDevice.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, UBOMorph.SIZE, UBOMorph.SIZE));
              }

              var _proto5 = MorphUniforms.prototype;

              _proto5.destroy = function destroy() {
                this._remoteBuffer.destroy();
              };

              _proto5.setWeights = function setWeights(weights) {
                assertIsTrue(weights.length === this._targetCount);

                for (var iWeight = 0; iWeight < weights.length; ++iWeight) {
                  this._localBuffer.setFloat32(UBOMorph.OFFSET_OF_WEIGHTS + 4 * iWeight, weights[iWeight], legacyCC.sys.isLittleEndian);
                }
              };

              _proto5.setMorphTextureInfo = function setMorphTextureInfo(width, height) {
                this._localBuffer.setFloat32(UBOMorph.OFFSET_OF_DISPLACEMENT_TEXTURE_WIDTH, width, legacyCC.sys.isLittleEndian);

                this._localBuffer.setFloat32(UBOMorph.OFFSET_OF_DISPLACEMENT_TEXTURE_HEIGHT, height, legacyCC.sys.isLittleEndian);
              };

              _proto5.setVerticesCount = function setVerticesCount(count) {
                this._localBuffer.setFloat32(UBOMorph.OFFSET_OF_VERTICES_COUNT, count, legacyCC.sys.isLittleEndian);
              };

              _proto5.commit = function commit() {
                this._remoteBuffer.update(this._localBuffer.buffer);
              };

              _createClass(MorphUniforms, [{
                key: "buffer",
                get: function get() {
                  return this._remoteBuffer;
                }
              }]);

              return MorphUniforms;
            }();

            function createVec4TextureFactory(gfxDevice, vec4Capacity) {
              var hasFeatureFloatTexture = gfxDevice.hasFeature(Feature.TEXTURE_FLOAT);
              var pixelRequired;
              var pixelFormat;
              var pixelBytes;
              var UpdateViewConstructor;

              if (hasFeatureFloatTexture) {
                pixelRequired = vec4Capacity;
                pixelBytes = 16;
                pixelFormat = Texture2D.PixelFormat.RGBA32F;
                UpdateViewConstructor = Float32Array;
              } else {
                pixelRequired = 4 * vec4Capacity;
                pixelBytes = 4;
                pixelFormat = Texture2D.PixelFormat.RGBA8888;
                UpdateViewConstructor = Uint8Array;
              }

              var _bestSizeToHavePixels = bestSizeToHavePixels(pixelRequired),
                  width = _bestSizeToHavePixels.width,
                  height = _bestSizeToHavePixels.height;

              assertIsTrue(width * height >= pixelRequired);
              return {
                width: width,
                height: height,
                create: function create() {
                  var arrayBuffer = new ArrayBuffer(width * height * pixelBytes);
                  var valueView = new Float32Array(arrayBuffer);
                  var updateView = UpdateViewConstructor === Float32Array ? valueView : new UpdateViewConstructor(arrayBuffer);
                  var image = new ImageAsset({
                    width: width,
                    height: height,
                    _data: updateView,
                    _compressed: false,
                    format: pixelFormat
                  });
                  var textureAsset = new Texture2D();
                  textureAsset.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST);
                  textureAsset.setMipFilter(Texture2D.Filter.NONE);
                  textureAsset.setWrapMode(Texture2D.WrapMode.CLAMP_TO_EDGE, Texture2D.WrapMode.CLAMP_TO_EDGE, Texture2D.WrapMode.CLAMP_TO_EDGE);
                  textureAsset.image = image;

                  if (!textureAsset.getGFXTexture()) {
                    warn('Unexpected: failed to create morph texture?');
                  }

                  var sampler = samplerLib.getSampler(gfxDevice, textureAsset.getSamplerHash());
                  return {
                    get texture() {
                      return textureAsset.getGFXTexture();
                    },

                    get sampler() {
                      return sampler;
                    },

                    get valueView() {
                      return valueView;
                    },

                    destroy: function destroy() {
                      textureAsset.destroy();
                    },
                    updatePixels: function updatePixels() {
                      textureAsset.uploadData(updateView);
                    }
                  };
                }
              };
            }

            function enableVertexId(mesh, subMeshIndex, gfxDevice) {
              mesh.renderingSubMeshes[subMeshIndex].enableVertexIdChannel(gfxDevice);
            }

            function bestSizeToHavePixels(nPixels) {
              if (nPixels < 5) {
                nPixels = 5;
              }

              var aligned = nextPow2(nPixels);
              var epxSum = log2(aligned);
              var h = epxSum >> 1;
              var w = epxSum & 1 ? h + 1 : h;
              return {
                width: 1 << w,
                height: 1 << h
              };
            }

            function createMorphRendering(mesh, gfxDevice) {
              return new StdMorphRendering(mesh, gfxDevice);
            }

            var _dec$1C, _class$1D, _class2$1r, _descriptor$1g, _descriptor2$$, _descriptor3$K, _temp$1u;

            function getIndexStrideCtor(stride) {
              switch (stride) {
                case 1:
                  return Uint8Array;

                case 2:
                  return Uint16Array;

                case 4:
                  return Uint32Array;

                default:
                  return Uint8Array;
              }
            }

            var v3_1$4 = new Vec3();
            var v3_2$2 = new Vec3();
            var globalEmptyMeshBuffer = new Uint8Array();
            var Mesh = (_dec$1C = ccclass('cc.Mesh'), _dec$1C(_class$1D = (_class2$1r = (_temp$1u = function (_Asset) {
              _inheritsLoose(Mesh, _Asset);

              function Mesh() {
                var _this;

                _this = _Asset.call(this) || this;
                _this.morphRendering = null;

                _initializerDefineProperty(_this, "_struct", _descriptor$1g, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_dataLength", _descriptor2$$, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_hash", _descriptor3$K, _assertThisInitialized(_this));

                _this._data = globalEmptyMeshBuffer;
                _this._initialized = false;
                _this._renderingSubMeshes = null;
                _this._boneSpaceBounds = new Map();
                _this._jointBufferIndices = null;
                _this.loaded = false;
                return _this;
              }

              var _proto = Mesh.prototype;

              _proto.initialize = function initialize() {
                var _this2 = this;

                if (this._initialized) {
                  return;
                }

                this._initialized = true;

                if (this._data.byteLength !== this._dataLength) {
                  this._data = new Uint8Array(this._dataLength);
                  legacyCC.assetManager.postLoadNative(this);
                }

                var buffer = this._data.buffer;
                var gfxDevice = legacyCC.director.root.device;

                var vertexBuffers = this._createVertexBuffers(gfxDevice, buffer);
                var subMeshes = [];

                var _loop = function _loop(i) {
                  var prim = _this2._struct.primitives[i];

                  if (prim.vertexBundelIndices.length === 0) {
                    return "continue";
                  }

                  var indexBuffer = null;
                  var ib = null;

                  if (prim.indexView) {
                    var idxView = prim.indexView;
                    var dstStride = idxView.stride;
                    var dstSize = idxView.length;

                    if (dstStride === 4 && !gfxDevice.hasFeature(Feature.ELEMENT_INDEX_UINT)) {
                      var vertexCount = _this2._struct.vertexBundles[prim.vertexBundelIndices[0]].view.count;

                      if (vertexCount >= 65536) {
                        warnID(10001, vertexCount, 65536);
                        return "continue";
                      } else {
                        dstStride >>= 1;
                        dstSize >>= 1;
                      }
                    }

                    indexBuffer = gfxDevice.createBuffer(new BufferInfo(BufferUsageBit.INDEX, MemoryUsageBit.DEVICE, dstSize, dstStride));
                    ib = new (getIndexStrideCtor(idxView.stride))(buffer, idxView.offset, idxView.count);

                    if (idxView.stride !== dstStride) {
                      ib = getIndexStrideCtor(dstStride).from(ib);
                    }

                    if (_this2.loaded) {
                      indexBuffer.update(ib);
                    } else {
                      _this2.once('load', function () {
                        indexBuffer.update(ib);
                      });
                    }
                  }

                  var vbReference = prim.vertexBundelIndices.map(function (idx) {
                    return vertexBuffers[idx];
                  });
                  var gfxAttributes = [];

                  if (prim.vertexBundelIndices.length > 0) {
                    var idx = prim.vertexBundelIndices[0];
                    var _vertexBundle = _this2._struct.vertexBundles[idx];
                    var attrs = _vertexBundle.attributes;

                    for (var j = 0; j < attrs.length; ++j) {
                      var attr = attrs[j];
                      gfxAttributes[j] = new Attribute(attr.name, attr.format, attr.isInstanced, attr.stream, attr.isInstanced, attr.location);
                    }
                  }

                  var subMesh = new RenderingSubMesh(vbReference, gfxAttributes, prim.primitiveMode, indexBuffer);
                  subMesh.mesh = _this2;
                  subMesh.subMeshIdx = i;
                  subMeshes.push(subMesh);
                };

                for (var i = 0; i < this._struct.primitives.length; i++) {
                  var _ret = _loop(i);

                  if (_ret === "continue") continue;
                }

                this._renderingSubMeshes = subMeshes;

                if (this._struct.morph) {
                  this.morphRendering = createMorphRendering(this, gfxDevice);
                }
              };

              _proto.destroy = function destroy() {
                this.destroyRenderingMesh();
                return _Asset.prototype.destroy.call(this);
              };

              _proto.destroyRenderingMesh = function destroyRenderingMesh() {
                if (this._renderingSubMeshes) {
                  for (var i = 0; i < this._renderingSubMeshes.length; i++) {
                    this._renderingSubMeshes[i].destroy();
                  }

                  this._renderingSubMeshes = null;
                  this._initialized = false;
                }
              };

              _proto.assign = function assign(struct, data) {
                this.reset({
                  struct: struct,
                  data: data
                });
              };

              _proto.reset = function reset(info) {
                this.destroyRenderingMesh();
                this._struct = info.struct;
                this._data = info.data;
                this._dataLength = this.data.byteLength;
                this._hash = 0;
                this.loaded = true;
                this.emit('load');
              };

              _proto.getBoneSpaceBounds = function getBoneSpaceBounds(skeleton) {
                if (this._boneSpaceBounds.has(skeleton.hash)) {
                  return this._boneSpaceBounds.get(skeleton.hash);
                }

                var bounds = [];

                this._boneSpaceBounds.set(skeleton.hash, bounds);

                var valid = [];
                var bindposes = skeleton.bindposes;

                for (var i = 0; i < bindposes.length; i++) {
                  bounds.push(new AABB(Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity));
                  valid.push(false);
                }

                var primitives = this._struct.primitives;

                for (var p = 0; p < primitives.length; p++) {
                  var joints = this.readAttribute(p, AttributeName.ATTR_JOINTS);
                  var weights = this.readAttribute(p, AttributeName.ATTR_WEIGHTS);
                  var positions = this.readAttribute(p, AttributeName.ATTR_POSITION);

                  if (!joints || !weights || !positions) {
                    continue;
                  }

                  var vertCount = Math.min(joints.length / 4, weights.length / 4, positions.length / 3);

                  for (var _i = 0; _i < vertCount; _i++) {
                    Vec3.set(v3_1$4, positions[3 * _i + 0], positions[3 * _i + 1], positions[3 * _i + 2]);

                    for (var j = 0; j < 4; ++j) {
                      var idx = 4 * _i + j;
                      var joint = joints[idx];

                      if (weights[idx] === 0 || joint >= bindposes.length) {
                        continue;
                      }

                      Vec3.transformMat4(v3_2$2, v3_1$4, bindposes[joint]);
                      valid[joint] = true;
                      var b = bounds[joint];
                      Vec3.min(b.center, b.center, v3_2$2);
                      Vec3.max(b.halfExtents, b.halfExtents, v3_2$2);
                    }
                  }
                }

                for (var _i2 = 0; _i2 < bindposes.length; _i2++) {
                  var _b = bounds[_i2];

                  if (!valid[_i2]) {
                    bounds[_i2] = null;
                  } else {
                    AABB.fromPoints(_b, _b.center, _b.halfExtents);
                  }
                }

                return bounds;
              };

              _proto.merge = function merge(mesh, worldMatrix, validate) {
                if (validate) {
                  if (!this.loaded || !mesh.loaded || !this.validateMergingMesh(mesh)) {
                    return false;
                  }
                }

                var vec3_temp = new Vec3();
                var rotate = worldMatrix && new Quat();
                var boundingBox = worldMatrix && new AABB();

                if (rotate) {
                  worldMatrix.getRotation(rotate);
                }

                if (!this._initialized) {
                  var struct = JSON.parse(JSON.stringify(mesh._struct));

                  var data = mesh._data.slice();

                  if (worldMatrix) {
                    if (struct.maxPosition && struct.minPosition) {
                      Vec3.add(boundingBox.center, struct.maxPosition, struct.minPosition);
                      Vec3.multiplyScalar(boundingBox.center, boundingBox.center, 0.5);
                      Vec3.subtract(boundingBox.halfExtents, struct.maxPosition, struct.minPosition);
                      Vec3.multiplyScalar(boundingBox.halfExtents, boundingBox.halfExtents, 0.5);
                      AABB.transform(boundingBox, boundingBox, worldMatrix);
                      Vec3.add(struct.maxPosition, boundingBox.center, boundingBox.halfExtents);
                      Vec3.subtract(struct.minPosition, boundingBox.center, boundingBox.halfExtents);
                    }

                    for (var i = 0; i < struct.vertexBundles.length; i++) {
                      var vtxBdl = struct.vertexBundles[i];

                      for (var j = 0; j < vtxBdl.attributes.length; j++) {
                        if (vtxBdl.attributes[j].name === AttributeName.ATTR_POSITION || vtxBdl.attributes[j].name === AttributeName.ATTR_NORMAL) {
                          var format = vtxBdl.attributes[j].format;
                          var inputView = new DataView(data.buffer, vtxBdl.view.offset + getOffset(vtxBdl.attributes, j));
                          var reader = getReader(inputView, format);
                          var writer = getWriter(inputView, format);

                          if (!reader || !writer) {
                            continue;
                          }

                          var vertexCount = vtxBdl.view.count;
                          var vertexStride = vtxBdl.view.stride;
                          var attrComponentByteLength = getComponentByteLength(format);

                          for (var vtxIdx = 0; vtxIdx < vertexCount; vtxIdx++) {
                            var xOffset = vtxIdx * vertexStride;
                            var yOffset = xOffset + attrComponentByteLength;
                            var zOffset = yOffset + attrComponentByteLength;
                            vec3_temp.set(reader(xOffset), reader(yOffset), reader(zOffset));

                            switch (vtxBdl.attributes[j].name) {
                              case AttributeName.ATTR_POSITION:
                                vec3_temp.transformMat4(worldMatrix);
                                break;

                              case AttributeName.ATTR_NORMAL:
                                Vec3.transformQuat(vec3_temp, vec3_temp, rotate);
                                break;
                            }

                            writer(xOffset, vec3_temp.x);
                            writer(yOffset, vec3_temp.y);
                            writer(zOffset, vec3_temp.z);
                          }
                        }
                      }
                    }
                  }

                  this.reset({
                    struct: struct,
                    data: data
                  });
                  this.initialize();
                  return true;
                }

                var bufferBlob = new BufferBlob();
                var vertCount = 0;
                var vertStride = 0;
                var srcOffset = 0;
                var dstOffset = 0;
                var vb;
                var vbView;
                var srcVBView;
                var dstVBView;
                var srcAttrOffset = 0;
                var srcVBOffset = 0;
                var dstVBOffset = 0;
                var attrSize = 0;
                var dstAttrView;
                var hasAttr = false;
                var vertexBundles = new Array(this._struct.vertexBundles.length);

                for (var _i3 = 0; _i3 < this._struct.vertexBundles.length; ++_i3) {
                  var bundle = this._struct.vertexBundles[_i3];
                  var dstBundle = mesh._struct.vertexBundles[_i3];
                  srcOffset = bundle.view.offset;
                  dstOffset = dstBundle.view.offset;
                  vertStride = bundle.view.stride;
                  vertCount = bundle.view.count + dstBundle.view.count;
                  vb = new ArrayBuffer(vertCount * vertStride);
                  vbView = new Uint8Array(vb);
                  srcVBView = this._data.subarray(srcOffset, srcOffset + bundle.view.length);
                  srcOffset += srcVBView.length;
                  dstVBView = mesh._data.subarray(dstOffset, dstOffset + dstBundle.view.length);
                  dstOffset += dstVBView.length;
                  vbView.set(srcVBView);
                  srcAttrOffset = 0;

                  for (var _iterator = _createForOfIteratorHelperLoose(bundle.attributes), _step; !(_step = _iterator()).done;) {
                    var attr = _step.value;
                    dstVBOffset = 0;
                    hasAttr = false;

                    for (var _iterator2 = _createForOfIteratorHelperLoose(dstBundle.attributes), _step2; !(_step2 = _iterator2()).done;) {
                      var dstAttr = _step2.value;

                      if (attr.name === dstAttr.name && attr.format === dstAttr.format) {
                        hasAttr = true;
                        break;
                      }

                      dstVBOffset += FormatInfos[dstAttr.format].size;
                    }

                    if (hasAttr) {
                      attrSize = FormatInfos[attr.format].size;
                      srcVBOffset = bundle.view.length + srcAttrOffset;

                      for (var v = 0; v < dstBundle.view.count; ++v) {
                        dstAttrView = dstVBView.subarray(dstVBOffset, dstVBOffset + attrSize);
                        vbView.set(dstAttrView, srcVBOffset);

                        if ((attr.name === AttributeName.ATTR_POSITION || attr.name === AttributeName.ATTR_NORMAL) && worldMatrix) {
                          var f32_temp = new Float32Array(vbView.buffer, srcVBOffset, 3);
                          vec3_temp.set(f32_temp[0], f32_temp[1], f32_temp[2]);

                          switch (attr.name) {
                            case AttributeName.ATTR_POSITION:
                              vec3_temp.transformMat4(worldMatrix);
                              break;

                            case AttributeName.ATTR_NORMAL:
                              Vec3.transformQuat(vec3_temp, vec3_temp, rotate);
                              break;
                          }

                          f32_temp[0] = vec3_temp.x;
                          f32_temp[1] = vec3_temp.y;
                          f32_temp[2] = vec3_temp.z;
                        }

                        srcVBOffset += bundle.view.stride;
                        dstVBOffset += dstBundle.view.stride;
                      }
                    }

                    srcAttrOffset += FormatInfos[attr.format].size;
                  }

                  vertexBundles[_i3] = {
                    attributes: bundle.attributes,
                    view: {
                      offset: bufferBlob.getLength(),
                      length: vb.byteLength,
                      count: vertCount,
                      stride: vertStride
                    }
                  };
                  bufferBlob.addBuffer(vb);
                }

                var idxCount = 0;
                var idxStride = 2;
                var vertBatchCount = 0;
                var ibView;
                var srcIBView;
                var dstIBView;
                var primitives = new Array(this._struct.primitives.length);

                for (var _i4 = 0; _i4 < this._struct.primitives.length; ++_i4) {
                  var prim = this._struct.primitives[_i4];
                  var dstPrim = mesh._struct.primitives[_i4];
                  primitives[_i4] = {
                    primitiveMode: prim.primitiveMode,
                    vertexBundelIndices: prim.vertexBundelIndices
                  };

                  for (var _iterator3 = _createForOfIteratorHelperLoose(prim.vertexBundelIndices), _step3; !(_step3 = _iterator3()).done;) {
                    var bundleIdx = _step3.value;
                    vertBatchCount = Math.max(vertBatchCount, this._struct.vertexBundles[bundleIdx].view.count);
                  }

                  if (prim.indexView && dstPrim.indexView) {
                    idxCount = prim.indexView.count;
                    idxCount += dstPrim.indexView.count;
                    srcOffset = prim.indexView.offset;
                    dstOffset = dstPrim.indexView.offset;

                    if (idxCount < 256) {
                      idxStride = 1;
                    } else if (idxCount < 65536) {
                      idxStride = 2;
                    } else {
                      idxStride = 4;
                    }

                    var ib = new ArrayBuffer(idxCount * idxStride);

                    if (idxStride === 2) {
                      ibView = new Uint16Array(ib);
                    } else if (idxStride === 1) {
                      ibView = new Uint8Array(ib);
                    } else {
                      ibView = new Uint32Array(ib);
                    }

                    if (prim.indexView.stride === 2) {
                      srcIBView = new Uint16Array(this._data.buffer, srcOffset, prim.indexView.count);
                    } else if (prim.indexView.stride === 1) {
                      srcIBView = new Uint8Array(this._data.buffer, srcOffset, prim.indexView.count);
                    } else {
                      srcIBView = new Uint32Array(this._data.buffer, srcOffset, prim.indexView.count);
                    }

                    if (idxStride === prim.indexView.stride) {
                      ibView.set(srcIBView);
                    } else {
                      for (var n = 0; n < prim.indexView.count; ++n) {
                        ibView[n] = srcIBView[n];
                      }
                    }

                    srcOffset += prim.indexView.length;

                    if (dstPrim.indexView.stride === 2) {
                      dstIBView = new Uint16Array(mesh._data.buffer, dstOffset, dstPrim.indexView.count);
                    } else if (dstPrim.indexView.stride === 1) {
                      dstIBView = new Uint8Array(mesh._data.buffer, dstOffset, dstPrim.indexView.count);
                    } else {
                      dstIBView = new Uint32Array(mesh._data.buffer, dstOffset, dstPrim.indexView.count);
                    }

                    for (var _n = 0; _n < dstPrim.indexView.count; ++_n) {
                      ibView[prim.indexView.count + _n] = vertBatchCount + dstIBView[_n];
                    }

                    dstOffset += dstPrim.indexView.length;
                    primitives[_i4].indexView = {
                      offset: bufferBlob.getLength(),
                      length: ib.byteLength,
                      count: idxCount,
                      stride: idxStride
                    };
                    bufferBlob.setNextAlignment(idxStride);
                    bufferBlob.addBuffer(ib);
                  }
                }

                var meshStruct = {
                  vertexBundles: vertexBundles,
                  primitives: primitives,
                  minPosition: this._struct.minPosition,
                  maxPosition: this._struct.maxPosition
                };

                if (meshStruct.minPosition && mesh._struct.minPosition && meshStruct.maxPosition && mesh._struct.maxPosition) {
                  if (worldMatrix) {
                    Vec3.add(boundingBox.center, mesh._struct.maxPosition, mesh._struct.minPosition);
                    Vec3.multiplyScalar(boundingBox.center, boundingBox.center, 0.5);
                    Vec3.subtract(boundingBox.halfExtents, mesh._struct.maxPosition, mesh._struct.minPosition);
                    Vec3.multiplyScalar(boundingBox.halfExtents, boundingBox.halfExtents, 0.5);
                    AABB.transform(boundingBox, boundingBox, worldMatrix);
                    Vec3.add(vec3_temp, boundingBox.center, boundingBox.halfExtents);
                    Vec3.max(meshStruct.maxPosition, meshStruct.maxPosition, vec3_temp);
                    Vec3.subtract(vec3_temp, boundingBox.center, boundingBox.halfExtents);
                    Vec3.min(meshStruct.minPosition, meshStruct.minPosition, vec3_temp);
                  } else {
                    Vec3.min(meshStruct.minPosition, meshStruct.minPosition, mesh._struct.minPosition);
                    Vec3.max(meshStruct.maxPosition, meshStruct.maxPosition, mesh._struct.maxPosition);
                  }
                }

                this.reset({
                  struct: meshStruct,
                  data: new Uint8Array(bufferBlob.getCombined())
                });
                this.initialize();
                return true;
              };

              _proto.validateMergingMesh = function validateMergingMesh(mesh) {
                if (this._struct.vertexBundles.length !== mesh._struct.vertexBundles.length) {
                  return false;
                }

                for (var i = 0; i < this._struct.vertexBundles.length; ++i) {
                  var bundle = this._struct.vertexBundles[i];
                  var dstBundle = mesh._struct.vertexBundles[i];

                  if (bundle.attributes.length !== dstBundle.attributes.length) {
                    return false;
                  }

                  for (var j = 0; j < bundle.attributes.length; ++j) {
                    if (bundle.attributes[j].format !== dstBundle.attributes[j].format) {
                      return false;
                    }
                  }
                }

                if (this._struct.primitives.length !== mesh._struct.primitives.length) {
                  return false;
                }

                for (var _i5 = 0; _i5 < this._struct.primitives.length; ++_i5) {
                  var prim = this._struct.primitives[_i5];
                  var dstPrim = mesh._struct.primitives[_i5];

                  if (prim.vertexBundelIndices.length !== dstPrim.vertexBundelIndices.length) {
                    return false;
                  }

                  for (var _j = 0; _j < prim.vertexBundelIndices.length; ++_j) {
                    if (prim.vertexBundelIndices[_j] !== dstPrim.vertexBundelIndices[_j]) {
                      return false;
                    }
                  }

                  if (prim.primitiveMode !== dstPrim.primitiveMode) {
                    return false;
                  }

                  if (prim.indexView) {
                    if (dstPrim.indexView === undefined) {
                      return false;
                    }
                  } else if (dstPrim.indexView) {
                    return false;
                  }
                }

                return true;
              };

              _proto.readAttribute = function readAttribute(primitiveIndex, attributeName) {
                var _this3 = this;

                var result = null;

                this._accessAttribute(primitiveIndex, attributeName, function (vertexBundle, iAttribute) {
                  var vertexCount = vertexBundle.view.count;
                  var format = vertexBundle.attributes[iAttribute].format;
                  var StorageConstructor = getTypedArrayConstructor(FormatInfos[format]);

                  if (vertexCount === 0) {
                    return;
                  }

                  var inputView = new DataView(_this3._data.buffer, vertexBundle.view.offset + getOffset(vertexBundle.attributes, iAttribute));
                  var formatInfo = FormatInfos[format];
                  var reader = getReader(inputView, format);

                  if (!StorageConstructor || !reader) {
                    return;
                  }

                  var componentCount = formatInfo.count;
                  var storage = new StorageConstructor(vertexCount * componentCount);
                  var inputStride = vertexBundle.view.stride;

                  for (var iVertex = 0; iVertex < vertexCount; ++iVertex) {
                    for (var iComponent = 0; iComponent < componentCount; ++iComponent) {
                      storage[componentCount * iVertex + iComponent] = reader(inputStride * iVertex + storage.BYTES_PER_ELEMENT * iComponent);
                    }
                  }

                  result = storage;
                });

                return result;
              };

              _proto.copyAttribute = function copyAttribute(primitiveIndex, attributeName, buffer, stride, offset) {
                var _this4 = this;

                var written = false;

                this._accessAttribute(primitiveIndex, attributeName, function (vertexBundle, iAttribute) {
                  var vertexCount = vertexBundle.view.count;

                  if (vertexCount === 0) {
                    written = true;
                    return;
                  }

                  var format = vertexBundle.attributes[iAttribute].format;
                  var inputView = new DataView(_this4._data.buffer, vertexBundle.view.offset + getOffset(vertexBundle.attributes, iAttribute));
                  var outputView = new DataView(buffer, offset);
                  var formatInfo = FormatInfos[format];
                  var reader = getReader(inputView, format);
                  var writer = getWriter(outputView, format);

                  if (!reader || !writer) {
                    return;
                  }

                  var componentCount = formatInfo.count;
                  var inputStride = vertexBundle.view.stride;
                  var inputComponentByteLength = getComponentByteLength(format);
                  var outputStride = stride;
                  var outputComponentByteLength = inputComponentByteLength;

                  for (var iVertex = 0; iVertex < vertexCount; ++iVertex) {
                    for (var iComponent = 0; iComponent < componentCount; ++iComponent) {
                      var inputOffset = inputStride * iVertex + inputComponentByteLength * iComponent;
                      var outputOffset = outputStride * iVertex + outputComponentByteLength * iComponent;
                      writer(outputOffset, reader(inputOffset));
                    }
                  }

                  written = true;
                });

                return written;
              };

              _proto.readIndices = function readIndices(primitiveIndex) {
                if (primitiveIndex >= this._struct.primitives.length) {
                  return null;
                }

                var primitive = this._struct.primitives[primitiveIndex];

                if (!primitive.indexView) {
                  return null;
                }

                var stride = primitive.indexView.stride;
                var Ctor = stride === 1 ? Uint8Array : stride === 2 ? Uint16Array : Uint32Array;
                return new Ctor(this._data.buffer, primitive.indexView.offset, primitive.indexView.count);
              };

              _proto.copyIndices = function copyIndices(primitiveIndex, outputArray) {
                if (primitiveIndex >= this._struct.primitives.length) {
                  return false;
                }

                var primitive = this._struct.primitives[primitiveIndex];

                if (!primitive.indexView) {
                  return false;
                }

                var indexCount = primitive.indexView.count;
                var indexFormat = primitive.indexView.stride === 1 ? Format.R8UI : primitive.indexView.stride === 2 ? Format.R16UI : Format.R32UI;
                var reader = getReader(new DataView(this._data.buffer), indexFormat);

                for (var i = 0; i < indexCount; ++i) {
                  outputArray[i] = reader(primitive.indexView.offset + FormatInfos[indexFormat].size * i);
                }

                return true;
              };

              _proto._accessAttribute = function _accessAttribute(primitiveIndex, attributeName, accessor) {
                if (primitiveIndex >= this._struct.primitives.length) {
                  return;
                }

                var primitive = this._struct.primitives[primitiveIndex];

                for (var _iterator4 = _createForOfIteratorHelperLoose(primitive.vertexBundelIndices), _step4; !(_step4 = _iterator4()).done;) {
                  var vertexBundleIndex = _step4.value;
                  var _vertexBundle2 = this._struct.vertexBundles[vertexBundleIndex];

                  var _iAttribute = _vertexBundle2.attributes.findIndex(function (a) {
                    return a.name === attributeName;
                  });

                  if (_iAttribute < 0) {
                    continue;
                  }

                  accessor(_vertexBundle2, _iAttribute);
                  break;
                }
              };

              _proto._createVertexBuffers = function _createVertexBuffers(gfxDevice, data) {
                var _this5 = this;

                return this._struct.vertexBundles.map(function (vertexBundle) {
                  var vertexBuffer = gfxDevice.createBuffer(new BufferInfo(BufferUsageBit.VERTEX, MemoryUsageBit.DEVICE, vertexBundle.view.length, vertexBundle.view.stride));
                  var view = new Uint8Array(data, vertexBundle.view.offset, vertexBundle.view.length);

                  if (_this5.loaded) {
                    vertexBuffer.update(view);
                  } else {
                    _this5.once('load', function () {
                      vertexBuffer.update(view);
                    });
                  }

                  return vertexBuffer;
                });
              };

              _proto.initDefault = function initDefault(uuid) {
                _Asset.prototype.initDefault.call(this, uuid);

                this.reset({
                  struct: {
                    vertexBundles: [],
                    primitives: []
                  },
                  data: globalEmptyMeshBuffer
                });
              };

              _proto.validate = function validate() {
                return this.renderingSubMeshes.length > 0 && this.data.byteLength > 0;
              };

              _createClass(Mesh, [{
                key: "_nativeAsset",
                get: function get() {
                  return this._data.buffer;
                },
                set: function set(value) {
                  if (this._data.byteLength === value.byteLength) {
                    this._data.set(new Uint8Array(value));
                  } else {
                    this._data = new Uint8Array(value);
                  }

                  this.loaded = true;
                  this.emit('load');
                }
              }, {
                key: "subMeshCount",
                get: function get() {
                  var renderingMesh = this.renderingSubMeshes;
                  return renderingMesh ? renderingMesh.length : 0;
                }
              }, {
                key: "minPosition",
                get: function get() {
                  return this.struct.minPosition;
                }
              }, {
                key: "maxPosition",
                get: function get() {
                  return this.struct.maxPosition;
                }
              }, {
                key: "struct",
                get: function get() {
                  return this._struct;
                }
              }, {
                key: "data",
                get: function get() {
                  return this._data;
                }
              }, {
                key: "hash",
                get: function get() {
                  if (!this._hash) {
                    this._hash = murmurhash2_32_gc(this._data, 666);
                  }

                  return this._hash;
                }
              }, {
                key: "jointBufferIndices",
                get: function get() {
                  if (this._jointBufferIndices) {
                    return this._jointBufferIndices;
                  }

                  return this._jointBufferIndices = this._struct.primitives.map(function (p) {
                    return p.jointMapIndex || 0;
                  });
                }
              }, {
                key: "renderingSubMeshes",
                get: function get() {
                  this.initialize();
                  return this._renderingSubMeshes;
                }
              }]);

              return Mesh;
            }(Asset), _temp$1u), (_descriptor$1g = _applyDecoratedDescriptor(_class2$1r.prototype, "_struct", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return {
                  vertexBundles: [],
                  primitives: []
                };
              }
            }), _descriptor2$$ = _applyDecoratedDescriptor(_class2$1r.prototype, "_dataLength", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor3$K = _applyDecoratedDescriptor(_class2$1r.prototype, "_hash", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            })), _class2$1r)) || _class$1D);
            legacyCC.Mesh = Mesh;

            function getOffset(attributes, attributeIndex) {
              var result = 0;

              for (var i = 0; i < attributeIndex; ++i) {
                var attribute = attributes[i];
                result += FormatInfos[attribute.format].size;
              }

              return result;
            }

            var isLittleEndian = sys.isLittleEndian;

            function getComponentByteLength(format) {
              var info = FormatInfos[format];
              return info.size / info.count;
            }

            function getReader(dataView, format) {
              var info = FormatInfos[format];
              var stride = info.size / info.count;

              switch (info.type) {
                case FormatType.UNORM:
                  {
                    switch (stride) {
                      case 1:
                        return function (offset) {
                          return dataView.getUint8(offset);
                        };

                      case 2:
                        return function (offset) {
                          return dataView.getUint16(offset, isLittleEndian);
                        };

                      case 4:
                        return function (offset) {
                          return dataView.getUint32(offset, isLittleEndian);
                        };
                    }

                    break;
                  }

                case FormatType.SNORM:
                  {
                    switch (stride) {
                      case 1:
                        return function (offset) {
                          return dataView.getInt8(offset);
                        };

                      case 2:
                        return function (offset) {
                          return dataView.getInt16(offset, isLittleEndian);
                        };

                      case 4:
                        return function (offset) {
                          return dataView.getInt32(offset, isLittleEndian);
                        };
                    }

                    break;
                  }

                case FormatType.INT:
                  {
                    switch (stride) {
                      case 1:
                        return function (offset) {
                          return dataView.getInt8(offset);
                        };

                      case 2:
                        return function (offset) {
                          return dataView.getInt16(offset, isLittleEndian);
                        };

                      case 4:
                        return function (offset) {
                          return dataView.getInt32(offset, isLittleEndian);
                        };
                    }

                    break;
                  }

                case FormatType.UINT:
                  {
                    switch (stride) {
                      case 1:
                        return function (offset) {
                          return dataView.getUint8(offset);
                        };

                      case 2:
                        return function (offset) {
                          return dataView.getUint16(offset, isLittleEndian);
                        };

                      case 4:
                        return function (offset) {
                          return dataView.getUint32(offset, isLittleEndian);
                        };
                    }

                    break;
                  }

                case FormatType.FLOAT:
                  {
                    return function (offset) {
                      return dataView.getFloat32(offset, isLittleEndian);
                    };
                  }
              }

              return null;
            }

            function getWriter(dataView, format) {
              var info = FormatInfos[format];
              var stride = info.size / info.count;

              switch (info.type) {
                case FormatType.UNORM:
                  {
                    switch (stride) {
                      case 1:
                        return function (offset, value) {
                          return dataView.setUint8(offset, value);
                        };

                      case 2:
                        return function (offset, value) {
                          return dataView.setUint16(offset, value, isLittleEndian);
                        };

                      case 4:
                        return function (offset, value) {
                          return dataView.setUint32(offset, value, isLittleEndian);
                        };
                    }

                    break;
                  }

                case FormatType.SNORM:
                  {
                    switch (stride) {
                      case 1:
                        return function (offset, value) {
                          return dataView.setInt8(offset, value);
                        };

                      case 2:
                        return function (offset, value) {
                          return dataView.setInt16(offset, value, isLittleEndian);
                        };

                      case 4:
                        return function (offset, value) {
                          return dataView.setInt32(offset, value, isLittleEndian);
                        };
                    }

                    break;
                  }

                case FormatType.INT:
                  {
                    switch (stride) {
                      case 1:
                        return function (offset, value) {
                          return dataView.setInt8(offset, value);
                        };

                      case 2:
                        return function (offset, value) {
                          return dataView.setInt16(offset, value, isLittleEndian);
                        };

                      case 4:
                        return function (offset, value) {
                          return dataView.setInt32(offset, value, isLittleEndian);
                        };
                    }

                    break;
                  }

                case FormatType.UINT:
                  {
                    switch (stride) {
                      case 1:
                        return function (offset, value) {
                          return dataView.setUint8(offset, value);
                        };

                      case 2:
                        return function (offset, value) {
                          return dataView.setUint16(offset, value, isLittleEndian);
                        };

                      case 4:
                        return function (offset, value) {
                          return dataView.setUint32(offset, value, isLittleEndian);
                        };
                    }

                    break;
                  }

                case FormatType.FLOAT:
                  {
                    return function (offset, value) {
                      return dataView.setFloat32(offset, value, isLittleEndian);
                    };
                  }
              }

              return null;
            }

            var MorphModel = function (_Model) {
              _inheritsLoose(MorphModel, _Model);

              function MorphModel() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Model.call.apply(_Model, [this].concat(args)) || this;
                _this._morphRenderingInstance = null;
                _this._usedMaterials = new Set();
                return _this;
              }

              var _proto = MorphModel.prototype;

              _proto.getMacroPatches = function getMacroPatches(subModelIndex) {
                if (this._morphRenderingInstance) {
                  return this._morphRenderingInstance.requiredPatches(subModelIndex);
                } else {
                  return null;
                }
              };

              _proto.initSubModel = function initSubModel(subModelIndex, subMeshData, material) {
                return _Model.prototype.initSubModel.call(this, subModelIndex, subMeshData, this._launderMaterial(material));
              };

              _proto.destroy = function destroy() {
                _Model.prototype.destroy.call(this);

                this._morphRenderingInstance = null;
              };

              _proto.setSubModelMaterial = function setSubModelMaterial(subModelIndex, material) {
                return _Model.prototype.setSubModelMaterial.call(this, subModelIndex, this._launderMaterial(material));
              };

              _proto._updateLocalDescriptors = function _updateLocalDescriptors(submodelIdx, descriptorSet) {
                _Model.prototype._updateLocalDescriptors.call(this, submodelIdx, descriptorSet);

                if (this._morphRenderingInstance) {
                  this._morphRenderingInstance.adaptPipelineState(submodelIdx, descriptorSet);
                }
              };

              _proto._launderMaterial = function _launderMaterial(material) {
                return material;
              };

              _proto.setMorphRendering = function setMorphRendering(morphRendering) {
                this._morphRenderingInstance = morphRendering;
              };

              return MorphModel;
            }(Model);

            var _dec$1D, _dec2$1b, _class$1E, _class2$1s, _descriptor$1h, _descriptor2$10, _descriptor3$L, _descriptor4$E, _descriptor5$w, _descriptor6$n, _temp$1v, _dec3$S, _dec4$L, _dec5$C, _dec6$v, _dec7$t, _dec8$q, _dec9$n, _dec10$m, _dec11$l, _dec12$k, _dec13$h, _class4$7, _class5$5, _descriptor7$i, _descriptor8$i, _descriptor9$f, _descriptor10$f, _descriptor11$e, _class6, _temp2$5;
            var ModelShadowCastingMode = Enum({
              OFF: 0,
              ON: 1
            });
            var ModelShadowReceivingMode = Enum({
              OFF: 0,
              ON: 1
            });
            var ModelLightmapSettings = (_dec$1D = ccclass('cc.ModelLightmapSettings'), _dec2$1b = formerlySerializedAs('_recieveShadow'), _dec$1D(_class$1E = (_class2$1s = (_temp$1v = function () {
              function ModelLightmapSettings() {
                _initializerDefineProperty(this, "texture", _descriptor$1h, this);

                _initializerDefineProperty(this, "uvParam", _descriptor2$10, this);

                _initializerDefineProperty(this, "_bakeable", _descriptor3$L, this);

                _initializerDefineProperty(this, "_castShadow", _descriptor4$E, this);

                _initializerDefineProperty(this, "_receiveShadow", _descriptor5$w, this);

                _initializerDefineProperty(this, "_lightmapSize", _descriptor6$n, this);
              }

              _createClass(ModelLightmapSettings, [{
                key: "bakeable",
                get: function get() {
                  return this._bakeable;
                },
                set: function set(val) {
                  this._bakeable = val;
                }
              }, {
                key: "castShadow",
                get: function get() {
                  return this._castShadow;
                },
                set: function set(val) {
                  this._castShadow = val;
                }
              }, {
                key: "receiveShadow",
                get: function get() {
                  return this._receiveShadow;
                },
                set: function set(val) {
                  this._receiveShadow = val;
                }
              }, {
                key: "lightmapSize",
                get: function get() {
                  return this._lightmapSize;
                },
                set: function set(val) {
                  this._lightmapSize = val;
                }
              }]);

              return ModelLightmapSettings;
            }(), _temp$1v), (_descriptor$1h = _applyDecoratedDescriptor(_class2$1s.prototype, "texture", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor2$10 = _applyDecoratedDescriptor(_class2$1s.prototype, "uvParam", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new Vec4();
              }
            }), _descriptor3$L = _applyDecoratedDescriptor(_class2$1s.prototype, "_bakeable", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor4$E = _applyDecoratedDescriptor(_class2$1s.prototype, "_castShadow", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor5$w = _applyDecoratedDescriptor(_class2$1s.prototype, "_receiveShadow", [_dec2$1b], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor6$n = _applyDecoratedDescriptor(_class2$1s.prototype, "_lightmapSize", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 64;
              }
            }), _applyDecoratedDescriptor(_class2$1s.prototype, "bakeable", [editable], Object.getOwnPropertyDescriptor(_class2$1s.prototype, "bakeable"), _class2$1s.prototype), _applyDecoratedDescriptor(_class2$1s.prototype, "castShadow", [editable], Object.getOwnPropertyDescriptor(_class2$1s.prototype, "castShadow"), _class2$1s.prototype), _applyDecoratedDescriptor(_class2$1s.prototype, "receiveShadow", [editable], Object.getOwnPropertyDescriptor(_class2$1s.prototype, "receiveShadow"), _class2$1s.prototype), _applyDecoratedDescriptor(_class2$1s.prototype, "lightmapSize", [editable], Object.getOwnPropertyDescriptor(_class2$1s.prototype, "lightmapSize"), _class2$1s.prototype)), _class2$1s)) || _class$1E);
            var MeshRenderer = (_dec3$S = ccclass('cc.MeshRenderer'), _dec4$L = help(), _dec5$C = executionOrder(100), _dec6$v = menu(), _dec7$t = type(ModelShadowCastingMode), _dec8$q = tooltip(), _dec9$n = type(ModelShadowReceivingMode), _dec10$m = tooltip(), _dec11$l = type(Mesh), _dec12$k = tooltip(), _dec13$h = visible(), _dec3$S(_class4$7 = _dec4$L(_class4$7 = _dec5$C(_class4$7 = _dec6$v(_class4$7 = executeInEditMode(_class4$7 = (_class5$5 = (_temp2$5 = _class6 = function (_RenderableComponent) {
              _inheritsLoose(MeshRenderer, _RenderableComponent);

              function MeshRenderer() {
                var _this;

                _this = _RenderableComponent.call(this) || this;

                _initializerDefineProperty(_this, "lightmapSettings", _descriptor7$i, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_mesh", _descriptor8$i, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_shadowCastingMode", _descriptor9$f, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_shadowReceivingMode", _descriptor10$f, _assertThisInitialized(_this));

                _this._modelType = void 0;
                _this._model = null;
                _this._morphInstance = null;

                _initializerDefineProperty(_this, "_enableMorph", _descriptor11$e, _assertThisInitialized(_this));

                _this._modelType = Model;
                return _this;
              }

              var _proto = MeshRenderer.prototype;

              _proto.onLoad = function onLoad() {
                if (this._mesh) {
                  this._mesh.initialize();
                }

                this._watchMorphInMesh();

                this._updateModels();

                this._updateCastShadow();

                this._updateReceiveShadow();
              };

              _proto.onRestore = function onRestore() {
                this._updateModels();

                this._updateCastShadow();

                this._updateReceiveShadow();
              };

              _proto.onEnable = function onEnable() {
                if (!this._model) {
                  this._updateModels();
                }

                this._attachToScene();
              };

              _proto.onDisable = function onDisable() {
                if (this._model) {
                  this._detachFromScene();
                }
              };

              _proto.onDestroy = function onDestroy() {
                if (this._model) {
                  legacyCC.director.root.destroyModel(this._model);
                  this._model = null;
                  this._models.length = 0;
                }

                if (this._morphInstance) {
                  this._morphInstance.destroy();
                }
              };

              _proto.setWeights = function setWeights(weights, subMeshIndex) {
                if (this._morphInstance) {
                  this._morphInstance.setWeights(subMeshIndex, weights);
                }
              };

              _proto.setInstancedAttribute = function setInstancedAttribute(name, value) {
                if (!this.model) {
                  return;
                }

                var _this$model$instanced = this.model.instancedAttributes,
                    attributes = _this$model$instanced.attributes,
                    views = _this$model$instanced.views;

                for (var i = 0; i < attributes.length; i++) {
                  if (attributes[i].name === name) {
                    views[i].set(value);
                    break;
                  }
                }
              };

              _proto._updateLightmap = function _updateLightmap(lightmap, uOff, vOff, uScale, vScale) {
                this.lightmapSettings.texture = lightmap;
                this.lightmapSettings.uvParam.x = uOff;
                this.lightmapSettings.uvParam.y = vOff;
                this.lightmapSettings.uvParam.z = uScale;
                this.lightmapSettings.uvParam.w = vScale;

                this._onUpdateLightingmap();
              };

              _proto._updateModels = function _updateModels() {
                if (!this.enabledInHierarchy || !this._mesh) {
                  return;
                }

                var model = this._model;

                if (model) {
                  model.destroy();
                  model.initialize();
                  model.node = model.transform = this.node;
                } else {
                  this._createModel();
                }

                if (this._model) {
                  this._model.createBoundingShape(this._mesh.struct.minPosition, this._mesh.struct.maxPosition);

                  this._updateModelParams();

                  this._onUpdateLightingmap();
                }
              };

              _proto._createModel = function _createModel() {
                var preferMorphOverPlain = !!this._morphInstance;
                var modelType = preferMorphOverPlain && this._modelType === Model ? MorphModel : this._modelType;
                var model = this._model = legacyCC.director.root.createModel(modelType);
                model.visFlags = this.visibility;
                model.node = model.transform = this.node;
                this._models.length = 0;

                this._models.push(this._model);

                if (this._morphInstance && model instanceof MorphModel) {
                  model.setMorphRendering(this._morphInstance);
                }
              };

              _proto._attachToScene = function _attachToScene() {
                if (!this.node.scene || !this._model) {
                  return;
                }

                var renderScene = this._getRenderScene();

                if (this._model.scene !== null) {
                  this._detachFromScene();
                }

                renderScene.addModel(this._model);
              };

              _proto._detachFromScene = function _detachFromScene() {
                if (this._model && this._model.scene) {
                  this._model.scene.removeModel(this._model);
                }
              };

              _proto._updateModelParams = function _updateModelParams() {
                if (!this._mesh || !this._model) {
                  return;
                }

                this.node.hasChangedFlags |= TransformBit.POSITION;
                this._model.transform.hasChangedFlags |= TransformBit.POSITION;
                this._model.isDynamicBatching = this._isBatchingEnabled();
                var meshCount = this._mesh ? this._mesh.renderingSubMeshes.length : 0;
                var renderingMesh = this._mesh.renderingSubMeshes;

                if (renderingMesh) {
                  for (var i = 0; i < meshCount; ++i) {
                    var material = this.getRenderMaterial(i);

                    if (material && !material.isValid) {
                      material = null;
                    }

                    var subMeshData = renderingMesh[i];

                    if (subMeshData) {
                      this._model.initSubModel(i, subMeshData, material || this._getBuiltinMaterial());
                    }
                  }
                }

                this._model.enabled = true;
              };

              _proto._onUpdateLightingmap = function _onUpdateLightingmap() {
                if (this.model !== null) {
                  this.model.updateLightingmap(this.lightmapSettings.texture, this.lightmapSettings.uvParam);
                }

                this.setInstancedAttribute('a_lightingMapUVParam', [this.lightmapSettings.uvParam.x, this.lightmapSettings.uvParam.y, this.lightmapSettings.uvParam.z, this.lightmapSettings.uvParam.w]);
              };

              _proto._onMaterialModified = function _onMaterialModified(idx, material) {
                if (!this._model || !this._model.inited) {
                  return;
                }

                this._onRebuildPSO(idx, material || this._getBuiltinMaterial());
              };

              _proto._onRebuildPSO = function _onRebuildPSO(idx, material) {
                if (!this._model || !this._model.inited) {
                  return;
                }

                this._model.isDynamicBatching = this._isBatchingEnabled();

                this._model.setSubModelMaterial(idx, material);

                this._onUpdateLightingmap();
              };

              _proto._onMeshChanged = function _onMeshChanged(old) {};

              _proto._clearMaterials = function _clearMaterials() {
                if (!this._model) {
                  return;
                }

                var subModels = this._model.subModels;

                for (var i = 0; i < subModels.length; ++i) {
                  this._onMaterialModified(i, null);
                }
              };

              _proto._getBuiltinMaterial = function _getBuiltinMaterial() {
                return builtinResMgr.get('missing-material');
              };

              _proto._onVisibilityChange = function _onVisibilityChange(val) {
                if (!this._model) {
                  return;
                }

                this._model.visFlags = val;
              };

              _proto._updateCastShadow = function _updateCastShadow() {
                if (!this._model) {
                  return;
                }

                if (this._shadowCastingMode === ModelShadowCastingMode.OFF) {
                  this._model.castShadow = false;
                } else {
                  assertIsTrue(this._shadowCastingMode === ModelShadowCastingMode.ON, "ShadowCastingMode " + this._shadowCastingMode + " is not supported.");
                  this._model.castShadow = true;
                }
              };

              _proto._updateReceiveShadow = function _updateReceiveShadow() {
                if (!this._model) {
                  return;
                }

                if (this._shadowReceivingMode === ModelShadowReceivingMode.OFF) {
                  this._model.receiveShadow = false;
                } else {
                  this._model.receiveShadow = true;
                }
              };

              _proto._isBatchingEnabled = function _isBatchingEnabled() {
                for (var i = 0; i < this._materials.length; ++i) {
                  var mat = this._materials[i];

                  if (!mat) {
                    continue;
                  }

                  for (var p = 0; p < mat.passes.length; ++p) {
                    var pass = mat.passes[p];

                    if (pass.batchingScheme) {
                      return true;
                    }
                  }
                }

                return false;
              };

              _proto._watchMorphInMesh = function _watchMorphInMesh() {
                if (this._morphInstance) {
                  this._morphInstance.destroy();

                  this._morphInstance = null;
                }

                if (!this._enableMorph) {
                  return;
                }

                if (!this._mesh || !this._mesh.struct.morph || !this._mesh.morphRendering) {
                  return;
                }

                var morph = this._mesh.struct.morph;
                this._morphInstance = this._mesh.morphRendering.createInstance();
                var nSubMeshes = this._mesh.struct.primitives.length;

                for (var iSubMesh = 0; iSubMesh < nSubMeshes; ++iSubMesh) {
                  var subMeshMorph = morph.subMeshMorphs[iSubMesh];

                  if (!subMeshMorph) {
                    continue;
                  }

                  var initialWeights = subMeshMorph.weights || morph.weights;
                  var weights = initialWeights ? initialWeights.slice() : new Array(subMeshMorph.targets.length).fill(0);

                  this._morphInstance.setWeights(iSubMesh, weights);
                }

                if (this._model && this._model instanceof MorphModel) {
                  this._model.setMorphRendering(this._morphInstance);
                }
              };

              _proto._syncMorphWeights = function _syncMorphWeights(subMeshIndex) {
                if (!this._morphInstance) {
                  return;
                }

                var subMeshMorphInstance = this._morphInstance[subMeshIndex];

                if (!subMeshMorphInstance || !subMeshMorphInstance.renderResources) {
                  return;
                }

                subMeshMorphInstance.renderResources.setWeights(subMeshMorphInstance.weights);
              };

              _createClass(MeshRenderer, [{
                key: "shadowCastingMode",
                get: function get() {
                  return this._shadowCastingMode;
                },
                set: function set(val) {
                  this._shadowCastingMode = val;

                  this._updateCastShadow();
                }
              }, {
                key: "receiveShadow",
                get: function get() {
                  return this._shadowReceivingMode;
                },
                set: function set(val) {
                  this._shadowReceivingMode = val;

                  this._updateReceiveShadow();
                }
              }, {
                key: "mesh",
                get: function get() {
                  return this._mesh;
                },
                set: function set(val) {
                  var old = this._mesh;
                  this._mesh = val;

                  if (this._mesh) {
                    this._mesh.initialize();
                  }

                  this._watchMorphInMesh();

                  this._onMeshChanged(old);

                  this._updateModels();

                  if (this.enabledInHierarchy) {
                    this._attachToScene();
                  }

                  this._updateCastShadow();

                  this._updateReceiveShadow();
                }
              }, {
                key: "model",
                get: function get() {
                  return this._model;
                }
              }, {
                key: "enableMorph",
                get: function get() {
                  return this._enableMorph;
                },
                set: function set(value) {
                  this._enableMorph = value;
                }
              }]);

              return MeshRenderer;
            }(RenderableComponent), _class6.ShadowCastingMode = ModelShadowCastingMode, _class6.ShadowReceivingMode = ModelShadowReceivingMode, _temp2$5), (_descriptor7$i = _applyDecoratedDescriptor(_class5$5.prototype, "lightmapSettings", [serializable, editable, disallowAnimation], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new ModelLightmapSettings();
              }
            }), _descriptor8$i = _applyDecoratedDescriptor(_class5$5.prototype, "_mesh", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor9$f = _applyDecoratedDescriptor(_class5$5.prototype, "_shadowCastingMode", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return ModelShadowCastingMode.OFF;
              }
            }), _descriptor10$f = _applyDecoratedDescriptor(_class5$5.prototype, "_shadowReceivingMode", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return ModelShadowReceivingMode.ON;
              }
            }), _applyDecoratedDescriptor(_class5$5.prototype, "shadowCastingMode", [_dec7$t, _dec8$q, disallowAnimation], Object.getOwnPropertyDescriptor(_class5$5.prototype, "shadowCastingMode"), _class5$5.prototype), _applyDecoratedDescriptor(_class5$5.prototype, "receiveShadow", [_dec9$n, _dec10$m, disallowAnimation], Object.getOwnPropertyDescriptor(_class5$5.prototype, "receiveShadow"), _class5$5.prototype), _applyDecoratedDescriptor(_class5$5.prototype, "mesh", [_dec11$l, _dec12$k], Object.getOwnPropertyDescriptor(_class5$5.prototype, "mesh"), _class5$5.prototype), _applyDecoratedDescriptor(_class5$5.prototype, "enableMorph", [_dec13$h, disallowAnimation], Object.getOwnPropertyDescriptor(_class5$5.prototype, "enableMorph"), _class5$5.prototype), _descriptor11$e = _applyDecoratedDescriptor(_class5$5.prototype, "_enableMorph", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            })), _class5$5)) || _class4$7) || _class4$7) || _class4$7) || _class4$7) || _class4$7);

            var _keyMap;

            (function (_keyMap) {
              _keyMap[_keyMap["positions"] = AttributeName.ATTR_POSITION] = "positions";
              _keyMap[_keyMap["normals"] = AttributeName.ATTR_NORMAL] = "normals";
              _keyMap[_keyMap["uvs"] = AttributeName.ATTR_TEX_COORD] = "uvs";
              _keyMap[_keyMap["colors"] = AttributeName.ATTR_COLOR] = "colors";
            })(_keyMap || (_keyMap = {}));

            var _defAttrs = [new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), new Attribute(AttributeName.ATTR_NORMAL, Format.RGB32F), new Attribute(AttributeName.ATTR_TEX_COORD, Format.RG32F), new Attribute(AttributeName.ATTR_TANGENT, Format.RGBA32F), new Attribute(AttributeName.ATTR_COLOR, Format.RGBA32F)];
            var v3_1$5 = new Vec3();
            function createMesh(geometry, out, options) {
              options = options || {};
              var attributes = [];
              var stride = 0;
              var channels = [];
              var vertCount = 0;
              var attr;
              var positions = geometry.positions.slice();

              if (positions.length > 0) {
                attr = null;

                if (geometry.attributes) {
                  for (var _iterator = _createForOfIteratorHelperLoose(geometry.attributes), _step; !(_step = _iterator()).done;) {
                    var att = _step.value;

                    if (att.name === AttributeName.ATTR_POSITION) {
                      attr = att;
                      break;
                    }
                  }
                }

                if (!attr) {
                  attr = _defAttrs[0];
                }

                attributes.push(attr);
                var info = FormatInfos[attr.format];
                vertCount = Math.max(vertCount, Math.floor(positions.length / info.count));
                channels.push({
                  offset: stride,
                  data: positions,
                  attribute: attr
                });
                stride += info.size;
              }

              if (geometry.normals && geometry.normals.length > 0) {
                attr = null;

                if (geometry.attributes) {
                  for (var _iterator2 = _createForOfIteratorHelperLoose(geometry.attributes), _step2; !(_step2 = _iterator2()).done;) {
                    var _att = _step2.value;

                    if (_att.name === AttributeName.ATTR_NORMAL) {
                      attr = _att;
                      break;
                    }
                  }
                }

                if (!attr) {
                  attr = _defAttrs[1];
                }

                var _info = FormatInfos[attr.format];
                attributes.push(attr);
                vertCount = Math.max(vertCount, Math.floor(geometry.normals.length / _info.count));
                channels.push({
                  offset: stride,
                  data: geometry.normals,
                  attribute: attr
                });
                stride += _info.size;
              }

              if (geometry.uvs && geometry.uvs.length > 0) {
                attr = null;

                if (geometry.attributes) {
                  for (var _iterator3 = _createForOfIteratorHelperLoose(geometry.attributes), _step3; !(_step3 = _iterator3()).done;) {
                    var _att2 = _step3.value;

                    if (_att2.name === AttributeName.ATTR_TEX_COORD) {
                      attr = _att2;
                      break;
                    }
                  }
                }

                if (!attr) {
                  attr = _defAttrs[2];
                }

                var _info2 = FormatInfos[attr.format];
                attributes.push(attr);
                vertCount = Math.max(vertCount, Math.floor(geometry.uvs.length / _info2.count));
                channels.push({
                  offset: stride,
                  data: geometry.uvs,
                  attribute: attr
                });
                stride += _info2.size;
              }

              if (geometry.tangents && geometry.tangents.length > 0) {
                attr = null;

                if (geometry.attributes) {
                  for (var _iterator4 = _createForOfIteratorHelperLoose(geometry.attributes), _step4; !(_step4 = _iterator4()).done;) {
                    var _att3 = _step4.value;

                    if (_att3.name === AttributeName.ATTR_TANGENT) {
                      attr = _att3;
                      break;
                    }
                  }
                }

                if (!attr) {
                  attr = _defAttrs[3];
                }

                var _info3 = FormatInfos[attr.format];
                attributes.push(attr);
                vertCount = Math.max(vertCount, Math.floor(geometry.tangents.length / _info3.count));
                channels.push({
                  offset: stride,
                  data: geometry.tangents,
                  attribute: attr
                });
                stride += _info3.size;
              }

              if (geometry.colors && geometry.colors.length > 0) {
                attr = null;

                if (geometry.attributes) {
                  for (var _iterator5 = _createForOfIteratorHelperLoose(geometry.attributes), _step5; !(_step5 = _iterator5()).done;) {
                    var _att4 = _step5.value;

                    if (_att4.name === AttributeName.ATTR_COLOR) {
                      attr = _att4;
                      break;
                    }
                  }
                }

                if (!attr) {
                  attr = _defAttrs[4];
                }

                var _info4 = FormatInfos[attr.format];
                attributes.push(attr);
                vertCount = Math.max(vertCount, Math.floor(geometry.colors.length / _info4.count));
                channels.push({
                  offset: stride,
                  data: geometry.colors,
                  attribute: attr
                });
                stride += _info4.size;
              }

              if (geometry.customAttributes) {
                for (var _iterator6 = _createForOfIteratorHelperLoose(geometry.customAttributes), _step6; !(_step6 = _iterator6()).done;) {
                  var ca = _step6.value;
                  var _info5 = FormatInfos[ca.attr.format];
                  attributes.push(ca.attr);
                  vertCount = Math.max(vertCount, Math.floor(ca.values.length / _info5.count));
                  channels.push({
                    offset: stride,
                    data: ca.values,
                    attribute: ca.attr
                  });
                  stride += _info5.size;
                }
              }

              var bufferBlob = new BufferBlob();
              var vertexBuffer = new ArrayBuffer(vertCount * stride);
              var vertexBufferView = new DataView(vertexBuffer);

              for (var _i = 0, _channels = channels; _i < _channels.length; _i++) {
                var channel = _channels[_i];
                writeBuffer(vertexBufferView, channel.data, channel.attribute.format, channel.offset, stride);
              }

              bufferBlob.setNextAlignment(0);
              var vertexBundle = {
                attributes: attributes,
                view: {
                  offset: bufferBlob.getLength(),
                  length: vertexBuffer.byteLength,
                  count: vertCount,
                  stride: stride
                }
              };
              bufferBlob.addBuffer(vertexBuffer);
              var indexBuffer = null;
              var idxCount = 0;
              var idxStride = 2;

              if (geometry.indices) {
                var indices = geometry.indices;
                idxCount = indices.length;
                indexBuffer = new ArrayBuffer(idxStride * idxCount);
                var indexBufferView = new DataView(indexBuffer);
                writeBuffer(indexBufferView, indices, Format.R16UI);
              }

              var primitive = {
                primitiveMode: geometry.primitiveMode || PrimitiveMode.TRIANGLE_LIST,
                vertexBundelIndices: [0]
              };

              if (indexBuffer) {
                bufferBlob.setNextAlignment(idxStride);
                primitive.indexView = {
                  offset: bufferBlob.getLength(),
                  length: indexBuffer.byteLength,
                  count: idxCount,
                  stride: idxStride
                };
                bufferBlob.addBuffer(indexBuffer);
              }

              var minPosition = geometry.minPos;

              if (!minPosition && options.calculateBounds) {
                minPosition = Vec3.set(new Vec3(), Infinity, Infinity, Infinity);

                for (var iVertex = 0; iVertex < vertCount; ++iVertex) {
                  Vec3.set(v3_1$5, positions[iVertex * 3 + 0], positions[iVertex * 3 + 1], positions[iVertex * 3 + 2]);
                  Vec3.min(minPosition, minPosition, v3_1$5);
                }
              }

              var maxPosition = geometry.maxPos;

              if (!maxPosition && options.calculateBounds) {
                maxPosition = Vec3.set(new Vec3(), -Infinity, -Infinity, -Infinity);

                for (var _iVertex = 0; _iVertex < vertCount; ++_iVertex) {
                  Vec3.set(v3_1$5, positions[_iVertex * 3 + 0], positions[_iVertex * 3 + 1], positions[_iVertex * 3 + 2]);
                  Vec3.max(maxPosition, maxPosition, v3_1$5);
                }
              }

              var meshStruct = {
                vertexBundles: [vertexBundle],
                primitives: [primitive]
              };

              if (minPosition) {
                meshStruct.minPosition = new Vec3(minPosition.x, minPosition.y, minPosition.z);
              }

              if (maxPosition) {
                meshStruct.maxPosition = new Vec3(maxPosition.x, maxPosition.y, maxPosition.z);
              }

              if (!out) {
                out = new Mesh();
              }

              out.reset({
                struct: meshStruct,
                data: new Uint8Array(bufferBlob.getCombined())
              });
              return out;
            }

            var Counter = function () {
              function Counter(id, opts, now) {
                this._id = void 0;
                this._opts = void 0;
                this._accumStart = void 0;
                this._total = 0;
                this._value = 0;
                this._averageValue = 0;
                this._accumValue = 0;
                this._accumSamples = 0;
                this._id = id;
                this._opts = opts;
                this._accumStart = now;
              }

              var _proto = Counter.prototype;

              _proto.sample = function sample(now) {
                this._average(this._value, now);
              };

              _proto.human = function human() {
                var _this$_opts = this._opts,
                    average = _this$_opts.average,
                    isInteger = _this$_opts.isInteger;
                var v = average ? this._averageValue : this._value;
                return isInteger ? Math.round(v) : Math.round(v * 100) / 100;
              };

              _proto.alarm = function alarm() {
                return this._opts.below && this._value < this._opts.below || this._opts.over && this._value > this._opts.over;
              };

              _proto._average = function _average(v, now) {
                if (now === void 0) {
                  now = 0;
                }

                if (this._opts.average) {
                  this._accumValue += v;
                  ++this._accumSamples;
                  var t = now;

                  if (t - this._accumStart >= this._opts.average) {
                    this._averageValue = this._accumValue / this._accumSamples;
                    this._accumValue = 0;
                    this._accumStart = t;
                    this._accumSamples = 0;
                  }
                }
              };

              _createClass(Counter, [{
                key: "value",
                get: function get() {
                  return this._value;
                },
                set: function set(val) {
                  this._value = val;
                }
              }]);

              return Counter;
            }();

            var _dec$1E, _class$1F, _temp$1w;
            var PerfCounter = (_dec$1E = ccclass('cc.PerfCounter'), _dec$1E(_class$1F = (_temp$1w = function (_Counter) {
              _inheritsLoose(PerfCounter, _Counter);

              function PerfCounter(id, opts, now) {
                var _this;

                _this = _Counter.call(this, id, opts, now) || this;
                _this._time = void 0;
                _this._time = now;
                return _this;
              }

              var _proto = PerfCounter.prototype;

              _proto.start = function start(now) {
                if (now === void 0) {
                  now = 0;
                }

                this._time = now;
              };

              _proto.end = function end(now) {
                if (now === void 0) {
                  now = 0;
                }

                this._value = now - this._time;

                this._average(this._value);
              };

              _proto.tick = function tick() {
                this.end();
                this.start();
              };

              _proto.frame = function frame(now) {
                var t = now;
                var e = t - this._time;
                this._total++;
                var avg = this._opts.average || 1000;

                if (e > avg) {
                  this._value = this._total * 1000 / e;
                  this._total = 0;
                  this._time = t;

                  this._average(this._value);
                }
              };

              return PerfCounter;
            }(Counter), _temp$1w)) || _class$1F);

            var _characters = '0123456789. ';
            var _average = 500;
            var _string2offset = {
              0: 0,
              1: 1,
              2: 2,
              3: 3,
              4: 4,
              5: 5,
              6: 6,
              7: 7,
              8: 8,
              9: 9,
              '.': 10
            };
            var _profileInfo = {
              fps: {
                desc: 'Framerate (FPS)',
                below: 30,
                average: _average,
                isInteger: true
              },
              draws: {
                desc: 'Draw call',
                isInteger: true
              },
              frame: {
                desc: 'Frame time (ms)',
                min: 0,
                max: 50,
                average: _average
              },
              instances: {
                desc: 'Instance Count',
                isInteger: true
              },
              tricount: {
                desc: 'Triangle',
                isInteger: true
              },
              logic: {
                desc: 'Game Logic (ms)',
                min: 0,
                max: 50,
                average: _average,
                color: '#080'
              },
              physics: {
                desc: 'Physics (ms)',
                min: 0,
                max: 50,
                average: _average
              },
              render: {
                desc: 'Renderer (ms)',
                min: 0,
                max: 50,
                average: _average,
                color: '#f90'
              },
              textureMemory: {
                desc: 'GFX Texture Mem(M)'
              },
              bufferMemory: {
                desc: 'GFX Buffer Mem(M)'
              }
            };
            var _constants = {
              fontSize: 23,
              quadHeight: 0.4,
              segmentsPerLine: 8,
              textureWidth: 256,
              textureHeight: 256
            };
            var Profiler = exports('Profiler', function () {
              function Profiler() {
                this._stats = null;
                this.id = '__Profiler__';
                this._showFPS = false;
                this._rootNode = null;
                this._device = 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 = document.createElement('canvas');
                  this._ctx = this._canvas.getContext('2d');

                  this._canvasArr.push(this._canvas);
                }
              }

              var _proto = Profiler.prototype;

              _proto.isShowingStats = function isShowingStats() {
                return this._showFPS;
              };

              _proto.hideStats = function hideStats() {
                if (this._showFPS) {
                  if (this._rootNode) {
                    this._rootNode.active = false;
                  }

                  legacyCC.game.off(legacyCC.Game.EVENT_RESTART, this.generateNode, this);
                  legacyCC.director.off(legacyCC.Director.EVENT_BEFORE_UPDATE, this.beforeUpdate, this);
                  legacyCC.director.off(legacyCC.Director.EVENT_AFTER_UPDATE, this.afterUpdate, this);
                  legacyCC.director.off(legacyCC.Director.EVENT_BEFORE_PHYSICS, this.beforePhysics, this);
                  legacyCC.director.off(legacyCC.Director.EVENT_AFTER_PHYSICS, this.afterPhysics, this);
                  legacyCC.director.off(legacyCC.Director.EVENT_BEFORE_DRAW, this.beforeDraw, this);
                  legacyCC.director.off(legacyCC.Director.EVENT_AFTER_DRAW, this.afterDraw, this);
                  this._showFPS = false;
                  legacyCC.game.config.showFPS = false;
                }
              };

              _proto.showStats = function showStats() {
                if (!this._showFPS) {
                  if (!this._device) {
                    this._device = legacyCC.director.root.device;
                  }

                  {
                    this.generateCanvas();
                  }

                  this.generateStats();

                  {
                    legacyCC.game.once(legacyCC.Game.EVENT_ENGINE_INITED, this.generateNode, this);
                    legacyCC.game.on(legacyCC.Game.EVENT_RESTART, this.generateNode, this);
                  }

                  if (this._rootNode) {
                    this._rootNode.active = true;
                  }

                  legacyCC.director.on(legacyCC.Director.EVENT_BEFORE_UPDATE, this.beforeUpdate, this);
                  legacyCC.director.on(legacyCC.Director.EVENT_AFTER_UPDATE, this.afterUpdate, this);
                  legacyCC.director.on(legacyCC.Director.EVENT_BEFORE_PHYSICS, this.beforePhysics, this);
                  legacyCC.director.on(legacyCC.Director.EVENT_AFTER_PHYSICS, this.afterPhysics, this);
                  legacyCC.director.on(legacyCC.Director.EVENT_BEFORE_DRAW, this.beforeDraw, this);
                  legacyCC.director.on(legacyCC.Director.EVENT_AFTER_DRAW, this.afterDraw, this);
                  this._showFPS = true;
                  this._canvasDone = true;
                  this._statsDone = true;
                  legacyCC.game.config.showFPS = true;
                }
              };

              _proto.generateCanvas = function generateCanvas() {
                if (this._canvasDone) {
                  return;
                }

                var textureWidth = _constants.textureWidth,
                    textureHeight = _constants.textureHeight;

                if (!this._ctx || !this._canvas) {
                  return;
                }

                this._canvas.width = textureWidth;
                this._canvas.height = textureHeight;
                this._canvas.style.width = "" + this._canvas.width;
                this._canvas.style.height = "" + this._canvas.height;
                this._ctx.font = _constants.fontSize + "px Arial";
                this._ctx.textBaseline = 'top';
                this._ctx.fillStyle = '#fff';
                this._texture = this._device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.SAMPLED | TextureUsageBit.TRANSFER_DST, Format.RGBA8, textureWidth, textureHeight));
                this._region.texExtent.width = textureWidth;
                this._region.texExtent.height = textureHeight;
              };

              _proto.generateStats = function generateStats() {
                if (this._statsDone || !this._ctx || !this._canvas) {
                  return;
                }

                this._stats = null;
                var now = performance.now();
                this._ctx.textAlign = 'left';
                var i = 0;

                for (var id in _profileInfo) {
                  var element = _profileInfo[id];
                  this._ctx.fillText(element.desc, 0, i * this._lineHeight);
                  element.counter = new PerfCounter(id, element, now);
                  i++;
                }

                this._totalLines = i;
                this._wordHeight = this._totalLines * this._lineHeight / this._canvas.height;

                {
                  for (var j = 0; j < _characters.length; ++j) {
                    var offset = this._ctx.measureText(_characters[j]).width;

                    this._eachNumWidth = Math.max(this._eachNumWidth, offset);
                  }

                  for (var _j = 0; _j < _characters.length; ++_j) {
                    this._ctx.fillText(_characters[_j], _j * this._eachNumWidth, this._totalLines * this._lineHeight);
                  }
                }

                this._eachNumWidth /= this._canvas.width;
                this._stats = _profileInfo;
                this._canvasArr[0] = this._canvas;
                this._device.copyTexImagesToTexture(this._canvasArr, this._texture, this._regionArr);
              };

              _proto.generateNode = function generateNode() {
                if (this._rootNode && this._rootNode.isValid) {
                  return;
                }

                this._rootNode = new Node$1('PROFILER_NODE');
                legacyCC.game.addPersistRootNode(this._rootNode);
                var cameraNode = new Node$1('Profiler_Camera');
                cameraNode.setPosition(0, 0, 1.5);
                cameraNode.parent = this._rootNode;
                var camera = cameraNode.addComponent('cc.Camera');
                camera.projection = Camera$1.ProjectionType.ORTHO;
                camera.orthoHeight = 1;
                camera.near = 1;
                camera.far = 2;
                camera.visibility = Layers.BitMask.PROFILER;
                camera.clearFlags = ClearFlagBit.NONE;
                camera.priority = 0xffffffff;
                var managerNode = new Node$1('Profiler_Root');
                managerNode.parent = this._rootNode;
                var height = _constants.quadHeight;
                var rowHeight = height / this._totalLines;
                var lWidth = height / this._wordHeight;
                var scale = rowHeight / _constants.fontSize;
                var columnWidth = this._eachNumWidth * this._canvas.width * scale;
                var vertexPos = [0, height, 0, lWidth, height, 0, lWidth, 0, 0, 0, 0, 0];
                var vertexindices = [0, 2, 1, 0, 3, 2];
                var vertexUV = [0, 0, -1, 0, 1, 0, -1, 0, 1, this._wordHeight, -1, 0, 0, this._wordHeight, -1, 0];
                var offset = 0;

                for (var i = 0; i < this._totalLines; i++) {
                  for (var j = 0; j < _constants.segmentsPerLine; j++) {
                    vertexPos.push(lWidth + j * columnWidth, height - i * rowHeight, 0);
                    vertexPos.push(lWidth + (j + 1) * columnWidth, height - i * rowHeight, 0);
                    vertexPos.push(lWidth + (j + 1) * columnWidth, height - (i + 1) * rowHeight, 0);
                    vertexPos.push(lWidth + j * columnWidth, height - (i + 1) * rowHeight, 0);
                    offset = (i * _constants.segmentsPerLine + j + 1) * 4;
                    vertexindices.push(0 + offset, 2 + offset, 1 + offset, 0 + offset, 3 + offset, 2 + offset);
                    var idx = i * _constants.segmentsPerLine + j;
                    var z = Math.floor(idx / 4);
                    var w = idx - z * 4;
                    vertexUV.push(0, this._wordHeight, z, w);
                    vertexUV.push(this._eachNumWidth, this._wordHeight, z, w);
                    vertexUV.push(this._eachNumWidth, 1, z, w);
                    vertexUV.push(0, 1, z, w);
                  }
                }

                var modelCom = managerNode.addComponent(MeshRenderer);
                modelCom.mesh = createMesh({
                  positions: vertexPos,
                  indices: vertexindices,
                  colors: vertexUV
                });

                var _material = new Material();

                _material.initialize({
                  effectName: 'profiler'
                });

                var pass = this.pass = _material.passes[0];
                var hTexture = pass.getBinding('mainTexture');
                var bDigits = pass.getBinding('digits');
                var bOffset = pass.getBinding('offset');
                pass.bindTexture(hTexture, this._texture);
                this.digitsData = pass.blocks[bDigits];
                this.offsetData = pass.blocks[bOffset];
                this.offsetData[3] = -1;
                modelCom.material = _material;
                modelCom.node.layer = Layers.Enum.PROFILER;
                this._inited = true;
              };

              _proto.beforeUpdate = function beforeUpdate() {
                if (!this._stats) {
                  return;
                }

                var now = performance.now();

                this._stats.frame.counter.end(now);

                this._stats.frame.counter.start(now);

                this._stats.logic.counter.start(now);
              };

              _proto.afterUpdate = function afterUpdate() {
                if (!this._stats) {
                  return;
                }

                var now = performance.now();

                if (legacyCC.director.isPaused()) {
                  this._stats.frame.counter.start(now);
                } else {
                  this._stats.logic.counter.end(now);
                }
              };

              _proto.beforePhysics = function beforePhysics() {
                if (!this._stats) {
                  return;
                }

                var now = performance.now();

                this._stats.physics.counter.start(now);
              };

              _proto.afterPhysics = function afterPhysics() {
                if (!this._stats) {
                  return;
                }

                var now = performance.now();

                this._stats.physics.counter.end(now);
              };

              _proto.beforeDraw = function beforeDraw() {
                if (!this._stats) {
                  return;
                }

                {
                  var surfaceTransform = this._device.surfaceTransform;
                  var clipSpaceSignY = this._device.capabilities.clipSpaceSignY;

                  if (surfaceTransform !== this.offsetData[3]) {
                    var preTransform = preTransforms[surfaceTransform];
                    var x = -0.9;
                    var y = -0.9 * clipSpaceSignY;
                    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._rootBufferDirty = true;
                }

                var now = performance.now();

                this._stats.render.counter.start(now);
              };

              _proto.afterDraw = function afterDraw() {
                if (!this._stats || !this._inited) {
                  return;
                }

                var now = performance.now();

                this._stats.fps.counter.frame(now);

                this._stats.render.counter.end(now);

                if (now - this.lastTime < _average) {
                  return;
                }

                this.lastTime = now;
                var device = this._device;
                this._stats.draws.counter.value = device.numDrawCalls;
                this._stats.instances.counter.value = device.numInstances;
                this._stats.bufferMemory.counter.value = device.memoryStatus.bufferSize / (1024 * 1024);
                this._stats.textureMemory.counter.value = device.memoryStatus.textureSize / (1024 * 1024);
                this._stats.tricount.counter.value = device.numTris;
                var i = 0;

                {
                  var view = this.digitsData;

                  for (var id in this._stats) {
                    var stat = this._stats[id];
                    stat.counter.sample(now);
                    var result = stat.counter.human().toString();

                    for (var j = _constants.segmentsPerLine - 1; j >= 0; j--) {
                      var index = i * _constants.segmentsPerLine + j;
                      var character = result[result.length - (_constants.segmentsPerLine - j)];
                      var offset = _string2offset[character];

                      if (offset === undefined) {
                        offset = 11;
                      }

                      view[index] = offset;
                    }

                    i++;
                  }
                }
              };

              return Profiler;
            }());
            var profiler = exports('profiler', new Profiler());
            legacyCC.profiler = profiler;

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

            var ZERO_VEC2 = new Vec2(0, 0);

            var _pos = new Vec2();

            var _tpa = new Vec2();

            var _tpb = new Vec2();

            var _tpc = new Vec2();

            var formatBytes = getComponentPerVertex(vfmtPosUvColor);

            function getWorldRotation(node) {
              var rotation = 0;
              var tempNode = node;

              while (tempNode) {
                rotation += tempNode.eulerAngles.z;
                tempNode = tempNode.parent;
              }

              return rotation;
            }

            var Particle = function Particle() {
              this.pos = new Vec2(0, 0);
              this.startPos = new Vec2(0, 0);
              this.color = new Color(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;
            };

            var ParticlePool = function (_Pool) {
              _inheritsLoose(ParticlePool, _Pool);

              function ParticlePool() {
                return _Pool.apply(this, arguments) || this;
              }

              var _proto = ParticlePool.prototype;

              _proto.get = function get() {
                return this._get() || new Particle();
              };

              return ParticlePool;
            }(Pool);

            var pool$2 = new ParticlePool(function (par) {
              par.pos.set(ZERO_VEC2);
              par.startPos.set(ZERO_VEC2);
              par.color._val = 0xFF000000;
              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(ZERO_VEC2);
              par.aspectRatio = 1;
              par.dir.set(ZERO_VEC2);
              par.radialAccel = 0;
              par.tangentialAccel = 0;
              par.angle = 0;
              par.degreesPerSecond = 0;
              par.radius = 0;
              par.deltaRadius = 0;
            }, 1024);
            var Simulator = function () {
              function Simulator(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;
              }

              var _proto2 = Simulator.prototype;

              _proto2.stop = function stop() {
                this.active = false;
                this.readyToPlay = false;
                this.elapsed = this.sys.duration;
                this.emitCounter = 0;
              };

              _proto2.reset = function reset() {
                this.active = true;
                this.readyToPlay = true;
                this.elapsed = 0;
                this.emitCounter = 0;
                this.finished = false;
                var particles = this.particles;

                for (var id = 0; id < particles.length; ++id) {
                  pool$2.put(particles[id]);
                }

                particles.length = 0;
              };

              _proto2.emitParticle = function emitParticle(pos) {
                var psys = this.sys;
                var particle = pool$2.get();
                this.particles.push(particle);
                particle.timeToLive = psys.life + psys.lifeVar * (Math.random() - 0.5) * 2;
                var timeToLive = particle.timeToLive = Math.max(0, particle.timeToLive);
                particle.pos.x = psys.sourcePos.x + psys.posVar.x * (Math.random() - 0.5) * 2;
                particle.pos.y = psys.sourcePos.y + psys.posVar.y * (Math.random() - 0.5) * 2;
                var sr = 0;
                var sg = 0;
                var sb = 0;
                var sa = 0;
                var startColor = psys.startColor;
                var startColorVar = psys.startColorVar;
                var endColor = psys.endColor;
                var endColorVar = psys.endColorVar;
                particle.color.r = sr = clampf(startColor.r + startColorVar.r * (Math.random() - 0.5) * 2, 0, 255);
                particle.color.g = sg = clampf(startColor.g + startColorVar.g * (Math.random() - 0.5) * 2, 0, 255);
                particle.color.b = sb = clampf(startColor.b + startColorVar.b * (Math.random() - 0.5) * 2, 0, 255);
                particle.color.a = sa = clampf(startColor.a + startColorVar.a * (Math.random() - 0.5) * 2, 0, 255);
                particle.deltaColor.r = (clampf(endColor.r + endColorVar.r * (Math.random() - 0.5) * 2, 0, 255) - sr) / timeToLive;
                particle.deltaColor.g = (clampf(endColor.g + endColorVar.g * (Math.random() - 0.5) * 2, 0, 255) - sg) / timeToLive;
                particle.deltaColor.b = (clampf(endColor.b + endColorVar.b * (Math.random() - 0.5) * 2, 0, 255) - sb) / timeToLive;
                particle.deltaColor.a = (clampf(endColor.a + endColorVar.a * (Math.random() - 0.5) * 2, 0, 255) - sa) / timeToLive;
                var startS = psys.startSize + psys.startSizeVar * (Math.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 {
                  var endS = psys.endSize + psys.endSizeVar * (Math.random() - 0.5) * 2;
                  endS = Math.max(0, endS);
                  particle.deltaSize = (endS - startS) / timeToLive;
                }

                var startA = psys.startSpin + psys.startSpinVar * (Math.random() - 0.5) * 2;
                var endA = psys.endSpin + psys.endSpinVar * (Math.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;
                var a = degreesToRadians(psys.angle + this._worldRotation + psys.angleVar * (Math.random() - 0.5) * 2);

                if (psys.emitterMode === EmitterMode.GRAVITY) {
                  var s = psys.speed + psys.speedVar * (Math.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 * (Math.random() - 0.5) * 2;
                  particle.tangentialAccel = psys.tangentialAccel + psys.tangentialAccelVar * (Math.random() - 0.5) * 2;

                  if (psys.rotationIsDir) {
                    particle.rotation = -radiansToDegrees(Math.atan2(particle.dir.y, particle.dir.x));
                  }
                } else {
                  var startRadius = psys.startRadius + psys.startRadiusVar * (Math.random() - 0.5) * 2;
                  var endRadius = psys.endRadius + psys.endRadiusVar * (Math.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 = degreesToRadians(psys.rotatePerS + psys.rotatePerSVar * (Math.random() - 0.5) * 2);
                }
              };

              _proto2.updateUVs = function updateUVs(force) {
                var renderData = this.renderData;

                if (renderData && this.sys._renderSpriteFrame) {
                  var vbuf = renderData.vData;
                  var uv = this.sys._renderSpriteFrame.uv;
                  var start = force ? 0 : this.uvFilled;
                  var particleCount = this.particles.length;

                  for (var i = start; i < particleCount; i++) {
                    var 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;
                }
              };

              _proto2.updateParticleBuffer = function updateParticleBuffer(particle, pos, buffer, offset) {
                var vbuf = buffer.vData;
                var x = pos.x;
                var y = pos.y;
                var width = particle.size;
                var height = width;
                var aspectRatio = particle.aspectRatio;

                if (aspectRatio > 1) {
                  height = width / aspectRatio;
                } else {
                  width = height * aspectRatio;
                }

                var halfWidth = width / 2;
                var halfHeight = height / 2;

                if (particle.rotation) {
                  var x1 = -halfWidth;
                  var y1 = -halfHeight;
                  var x2 = halfWidth;
                  var y2 = halfHeight;
                  var rad = -degreesToRadians(particle.rotation);
                  var cr = Math.cos(rad);
                  var 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;
                }

                Color.toArray(vbuf, particle.color, offset + 5);
                Color.toArray(vbuf, particle.color, offset + 14);
                Color.toArray(vbuf, particle.color, offset + 23);
                Color.toArray(vbuf, particle.color, offset + 32);
              };

              _proto2.step = function step(dt) {
                var assembler = this.sys.assembler;
                var psys = this.sys;
                var node = psys.node;
                var particles = this.particles;
                dt = dt > assembler.maxParticleDeltaTime ? assembler.maxParticleDeltaTime : dt;
                node.updateWorldTransform();

                if (psys.positionType === PositionType.FREE) {
                  this._worldRotation = getWorldRotation(node);
                  var 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) {
                  var 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();
                  }
                }

                var renderData = this.renderData;
                var particleCount = particles.length;
                renderData.reset();
                this.requestData(particleCount * 4, particleCount * 6);

                if (particleCount > this.uvFilled) {
                  this.updateUVs();
                }

                var particleIdx = 0;

                while (particleIdx < particles.length) {
                  _tpa.x = _tpa.y = _tpb.x = _tpb.y = _tpc.x = _tpc.y = 0;
                  var particle = particles[particleIdx];
                  particle.timeToLive -= dt;

                  if (particle.timeToLive > 0) {
                    if (psys.emitterMode === EmitterMode.GRAVITY) {
                      var tmp = _tpc;
                      var radial = _tpa;
                      var tangential = _tpb;

                      if (particle.pos.x || particle.pos.y) {
                        radial.set(particle.pos);
                        radial.normalize();
                      }

                      tangential.set(radial);
                      radial.multiplyScalar(particle.radialAccel);
                      var 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;
                    var newPos = _tpa;
                    newPos.set(particle.pos);

                    if (psys.positionType !== PositionType.GROUPED) {
                      newPos.add(particle.startPos);
                    }

                    var offset = formatBytes * particleIdx * 4;
                    this.updateParticleBuffer(particle, newPos, renderData, offset);
                    ++particleIdx;
                  } else {
                    var deadParticle = particles[particleIdx];

                    if (particleIdx !== particles.length - 1) {
                      particles[particleIdx] = particles[particles.length - 1];
                    }

                    pool$2.put(deadParticle);
                    particles.length--;
                    renderData.indicesCount -= 6;
                    renderData.vertexCount -= 4;
                  }
                }

                if (particles.length === 0 && !this.active && !this.readyToPlay) {
                  this.finished = true;

                  psys._finishedSimulation();
                }
              };

              _proto2.requestData = function requestData(vertexCount, indicesCount) {
                var offset = this.renderData.indicesCount;
                this.renderData.request(vertexCount, indicesCount);
                var count = this.renderData.indicesCount / 6;
                var buffer = this.renderData.iData;

                for (var i = offset; i < count; i++) {
                  var 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;
                }
              };

              return Simulator;
            }();

            var _dec$1F, _class$1G, _class2$1t, _descriptor$1i, _temp$1x;
            var ParticleAsset = exports('ParticleAsset', (_dec$1F = ccclass('cc.ParticleAsset'), _dec$1F(_class$1G = (_class2$1t = (_temp$1x = function (_Asset) {
              _inheritsLoose(ParticleAsset, _Asset);

              function ParticleAsset() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "spriteFrame", _descriptor$1i, _assertThisInitialized(_this));

                return _this;
              }

              return ParticleAsset;
            }(Asset), _temp$1x), (_descriptor$1i = _applyDecoratedDescriptor(_class2$1t.prototype, "spriteFrame", [serializable, editable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            })), _class2$1t)) || _class$1G));
            legacyCC.ParticleAsset = ParticleAsset;

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

              function i(a) {
                throw a;
              }

              var r = void 0,
                  v = !0,
                  aa = this;

              function y(a, c) {
                var b = a.split("."),
                    e = aa;
                !(b[0] in e) && e.execScript && e.execScript("var " + b[0]);

                for (var f; b.length && (f = b.shift());) {
                  !b.length && c !== r ? e[f] = c : e = e[f] ? e[f] : e[f] = {};
                }
              }
              var H = "undefined" !== typeof Uint8Array && "undefined" !== typeof Uint16Array && "undefined" !== typeof Uint32Array;

              function ba(a) {
                if ("string" === typeof a) {
                  var c = a.split(""),
                      b,
                      e;
                  b = 0;

                  for (e = c.length; b < e; b++) {
                    c[b] = (c[b].charCodeAt(0) & 255) >>> 0;
                  }

                  a = c;
                }

                for (var f = 1, d = 0, g = a.length, h, m = 0; 0 < g;) {
                  h = 1024 < g ? 1024 : g;
                  g -= h;

                  do {
                    f += a[m++], d += f;
                  } while (--h);

                  f %= 65521;
                  d %= 65521;
                }

                return (d << 16 | f) >>> 0;
              }

              function J(a, c) {
                this.index = "number" === typeof c ? c : 0;
                this.i = 0;
                this.buffer = a instanceof (H ? Uint8Array : Array) ? a : new (H ? Uint8Array : Array)(32768);
                2 * this.buffer.length <= this.index && i(Error("invalid index"));
                this.buffer.length <= this.index && this.f();
              }

              J.prototype.f = function () {
                var a = this.buffer,
                    c,
                    b = a.length,
                    e = new (H ? Uint8Array : Array)(b << 1);
                if (H) e.set(a);else for (c = 0; c < b; ++c) {
                  e[c] = a[c];
                }
                return this.buffer = e;
              };

              J.prototype.d = function (a, c, b) {
                var e = this.buffer,
                    f = this.index,
                    d = this.i,
                    g = e[f],
                    h;
                b && 1 < c && (a = 8 < c ? (N[a & 255] << 24 | N[a >>> 8 & 255] << 16 | N[a >>> 16 & 255] << 8 | N[a >>> 24 & 255]) >> 32 - c : N[a] >> 8 - c);
                if (8 > c + d) g = g << c | a, d += c;else for (h = 0; h < c; ++h) {
                  g = g << 1 | a >> c - h - 1 & 1, 8 === ++d && (d = 0, e[f++] = N[g], g = 0, f === e.length && (e = this.f()));
                }
                e[f] = g;
                this.buffer = e;
                this.i = d;
                this.index = f;
              };

              J.prototype.finish = function () {
                var a = this.buffer,
                    c = this.index,
                    b;
                0 < this.i && (a[c] <<= 8 - this.i, a[c] = N[a[c]], c++);
                H ? b = a.subarray(0, c) : (a.length = c, b = a);
                return b;
              };

              var ca = new (H ? Uint8Array : Array)(256),
                  ha;

              for (ha = 0; 256 > ha; ++ha) {
                for (var R = ha, ia = R, ja = 7, R = R >>> 1; R; R >>>= 1) {
                  ia <<= 1, ia |= R & 1, --ja;
                }

                ca[ha] = (ia << ja & 255) >>> 0;
              }

              var N = ca;

              function la(a) {
                this.buffer = new (H ? Uint16Array : Array)(2 * a);
                this.length = 0;
              }

              la.prototype.getParent = function (a) {
                return 2 * ((a - 2) / 4 | 0);
              };

              la.prototype.push = function (a, c) {
                var b,
                    e,
                    f = this.buffer,
                    d;
                b = this.length;
                f[this.length++] = c;

                for (f[this.length++] = a; 0 < b;) {
                  if (e = this.getParent(b), f[b] > f[e]) d = f[b], f[b] = f[e], f[e] = d, d = f[b + 1], f[b + 1] = f[e + 1], f[e + 1] = d, b = e;else break;
                }

                return this.length;
              };

              la.prototype.pop = function () {
                var a,
                    c,
                    b = this.buffer,
                    e,
                    f,
                    d;
                c = b[0];
                a = b[1];
                this.length -= 2;
                b[0] = b[this.length];
                b[1] = b[this.length + 1];

                for (d = 0;;) {
                  f = 2 * d + 2;
                  if (f >= this.length) break;
                  f + 2 < this.length && b[f + 2] > b[f] && (f += 2);
                  if (b[f] > b[d]) e = b[d], b[d] = b[f], b[f] = e, e = b[d + 1], b[d + 1] = b[f + 1], b[f + 1] = e;else break;
                  d = f;
                }

                return {
                  index: a,
                  value: c,
                  length: this.length
                };
              };

              function S(a) {
                var c = a.length,
                    b = 0,
                    e = Number.POSITIVE_INFINITY,
                    f,
                    d,
                    g,
                    h,
                    m,
                    j,
                    s,
                    n,
                    l;

                for (n = 0; n < c; ++n) {
                  a[n] > b && (b = a[n]), a[n] < e && (e = a[n]);
                }

                f = 1 << b;
                d = new (H ? Uint32Array : Array)(f);
                g = 1;
                h = 0;

                for (m = 2; g <= b;) {
                  for (n = 0; n < c; ++n) {
                    if (a[n] === g) {
                      j = 0;
                      s = h;

                      for (l = 0; l < g; ++l) {
                        j = j << 1 | s & 1, s >>= 1;
                      }

                      for (l = j; l < f; l += m) {
                        d[l] = g << 16 | n;
                      }

                      ++h;
                    }
                  }

                  ++g;
                  h <<= 1;
                  m <<= 1;
                }

                return [d, b, e];
              }

              function ma(a, c) {
                this.h = pa;
                this.w = 0;
                this.input = a;
                this.b = 0;
                c && (c.lazy && (this.w = c.lazy), "number" === typeof c.compressionType && (this.h = c.compressionType), c.outputBuffer && (this.a = H && c.outputBuffer instanceof Array ? new Uint8Array(c.outputBuffer) : c.outputBuffer), "number" === typeof c.outputIndex && (this.b = c.outputIndex));
                this.a || (this.a = new (H ? Uint8Array : Array)(32768));
              }

              var pa = 2,
                  qa = {
                NONE: 0,
                r: 1,
                j: pa,
                N: 3
              },
                  ra = [],
                  T;

              for (T = 0; 288 > T; T++) {
                switch (v) {
                  case 143 >= T:
                    ra.push([T + 48, 8]);
                    break;

                  case 255 >= T:
                    ra.push([T - 144 + 400, 9]);
                    break;

                  case 279 >= T:
                    ra.push([T - 256 + 0, 7]);
                    break;

                  case 287 >= T:
                    ra.push([T - 280 + 192, 8]);
                    break;

                  default:
                    i("invalid literal: " + T);
                }
              }

              ma.prototype.n = function () {
                var a,
                    c,
                    b,
                    e,
                    f = this.input;

                switch (this.h) {
                  case 0:
                    b = 0;

                    for (e = f.length; b < e;) {
                      c = H ? f.subarray(b, b + 65535) : f.slice(b, b + 65535);
                      b += c.length;
                      var d = c,
                          g = b === e,
                          h = r,
                          m = r,
                          j = r,
                          s = r,
                          n = r,
                          l = this.a,
                          q = this.b;

                      if (H) {
                        for (l = new Uint8Array(this.a.buffer); l.length <= q + d.length + 5;) {
                          l = new Uint8Array(l.length << 1);
                        }

                        l.set(this.a);
                      }

                      h = g ? 1 : 0;
                      l[q++] = h | 0;
                      m = d.length;
                      j = ~m + 65536 & 65535;
                      l[q++] = m & 255;
                      l[q++] = m >>> 8 & 255;
                      l[q++] = j & 255;
                      l[q++] = j >>> 8 & 255;
                      if (H) l.set(d, q), q += d.length, l = l.subarray(0, q);else {
                        s = 0;

                        for (n = d.length; s < n; ++s) {
                          l[q++] = d[s];
                        }

                        l.length = q;
                      }
                      this.b = q;
                      this.a = l;
                    }

                    break;

                  case 1:
                    var E = new J(new Uint8Array(this.a.buffer), this.b);
                    E.d(1, 1, v);
                    E.d(1, 2, v);
                    var t = sa(this, f),
                        z,
                        K,
                        A;
                    z = 0;

                    for (K = t.length; z < K; z++) {
                      if (A = t[z], J.prototype.d.apply(E, ra[A]), 256 < A) E.d(t[++z], t[++z], v), E.d(t[++z], 5), E.d(t[++z], t[++z], v);else if (256 === A) break;
                    }

                    this.a = E.finish();
                    this.b = this.a.length;
                    break;

                  case pa:
                    var x = new J(new Uint8Array(this.a), this.b),
                        B,
                        k,
                        p,
                        D,
                        C,
                        da = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15],
                        W,
                        Ma,
                        ea,
                        Na,
                        na,
                        va = Array(19),
                        Oa,
                        $,
                        oa,
                        F,
                        Pa;
                    B = pa;
                    x.d(1, 1, v);
                    x.d(B, 2, v);
                    k = sa(this, f);
                    W = ta(this.L, 15);
                    Ma = ua(W);
                    ea = ta(this.K, 7);
                    Na = ua(ea);

                    for (p = 286; 257 < p && 0 === W[p - 1]; p--) {
                    }

                    for (D = 30; 1 < D && 0 === ea[D - 1]; D--) {
                    }

                    var Qa = p,
                        Ra = D,
                        M = new (H ? Uint32Array : Array)(Qa + Ra),
                        u,
                        O,
                        w,
                        fa,
                        L = new (H ? Uint32Array : Array)(316),
                        I,
                        G,
                        P = new (H ? Uint8Array : Array)(19);

                    for (u = O = 0; u < Qa; u++) {
                      M[O++] = W[u];
                    }

                    for (u = 0; u < Ra; u++) {
                      M[O++] = ea[u];
                    }

                    if (!H) {
                      u = 0;

                      for (fa = P.length; u < fa; ++u) {
                        P[u] = 0;
                      }
                    }

                    u = I = 0;

                    for (fa = M.length; u < fa; u += O) {
                      for (O = 1; u + O < fa && M[u + O] === M[u]; ++O) {
                      }

                      w = O;
                      if (0 === M[u]) {
                        if (3 > w) for (; 0 < w--;) {
                          L[I++] = 0, P[0]++;
                        } else for (; 0 < w;) {
                          G = 138 > w ? w : 138, G > w - 3 && G < w && (G = w - 3), 10 >= G ? (L[I++] = 17, L[I++] = G - 3, P[17]++) : (L[I++] = 18, L[I++] = G - 11, P[18]++), w -= G;
                        }
                      } else if (L[I++] = M[u], P[M[u]]++, w--, 3 > w) for (; 0 < w--;) {
                        L[I++] = M[u], P[M[u]]++;
                      } else for (; 0 < w;) {
                        G = 6 > w ? w : 6, G > w - 3 && G < w && (G = w - 3), L[I++] = 16, L[I++] = G - 3, P[16]++, w -= G;
                      }
                    }

                    a = H ? L.subarray(0, I) : L.slice(0, I);
                    na = ta(P, 7);

                    for (F = 0; 19 > F; F++) {
                      va[F] = na[da[F]];
                    }

                    for (C = 19; 4 < C && 0 === va[C - 1]; C--) {
                    }

                    Oa = ua(na);
                    x.d(p - 257, 5, v);
                    x.d(D - 1, 5, v);
                    x.d(C - 4, 4, v);

                    for (F = 0; F < C; F++) {
                      x.d(va[F], 3, v);
                    }

                    F = 0;

                    for (Pa = a.length; F < Pa; F++) {
                      if ($ = a[F], x.d(Oa[$], na[$], v), 16 <= $) {
                        F++;

                        switch ($) {
                          case 16:
                            oa = 2;
                            break;

                          case 17:
                            oa = 3;
                            break;

                          case 18:
                            oa = 7;
                            break;

                          default:
                            i("invalid code: " + $);
                        }

                        x.d(a[F], oa, v);
                      }
                    }

                    var Sa = [Ma, W],
                        Ta = [Na, ea],
                        Q,
                        Ua,
                        ga,
                        ya,
                        Va,
                        Wa,
                        Xa,
                        Ya;
                    Va = Sa[0];
                    Wa = Sa[1];
                    Xa = Ta[0];
                    Ya = Ta[1];
                    Q = 0;

                    for (Ua = k.length; Q < Ua; ++Q) {
                      if (ga = k[Q], x.d(Va[ga], Wa[ga], v), 256 < ga) x.d(k[++Q], k[++Q], v), ya = k[++Q], x.d(Xa[ya], Ya[ya], v), x.d(k[++Q], k[++Q], v);else if (256 === ga) break;
                    }

                    this.a = x.finish();
                    this.b = this.a.length;
                    break;

                  default:
                    i("invalid compression type");
                }

                return this.a;
              };

              function wa(a, c) {
                this.length = a;
                this.G = c;
              }

              function xa() {
                var a = za;

                switch (v) {
                  case 3 === a:
                    return [257, a - 3, 0];

                  case 4 === a:
                    return [258, a - 4, 0];

                  case 5 === a:
                    return [259, a - 5, 0];

                  case 6 === a:
                    return [260, a - 6, 0];

                  case 7 === a:
                    return [261, a - 7, 0];

                  case 8 === a:
                    return [262, a - 8, 0];

                  case 9 === a:
                    return [263, a - 9, 0];

                  case 10 === a:
                    return [264, a - 10, 0];

                  case 12 >= a:
                    return [265, a - 11, 1];

                  case 14 >= a:
                    return [266, a - 13, 1];

                  case 16 >= a:
                    return [267, a - 15, 1];

                  case 18 >= a:
                    return [268, a - 17, 1];

                  case 22 >= a:
                    return [269, a - 19, 2];

                  case 26 >= a:
                    return [270, a - 23, 2];

                  case 30 >= a:
                    return [271, a - 27, 2];

                  case 34 >= a:
                    return [272, a - 31, 2];

                  case 42 >= a:
                    return [273, a - 35, 3];

                  case 50 >= a:
                    return [274, a - 43, 3];

                  case 58 >= a:
                    return [275, a - 51, 3];

                  case 66 >= a:
                    return [276, a - 59, 3];

                  case 82 >= a:
                    return [277, a - 67, 4];

                  case 98 >= a:
                    return [278, a - 83, 4];

                  case 114 >= a:
                    return [279, a - 99, 4];

                  case 130 >= a:
                    return [280, a - 115, 4];

                  case 162 >= a:
                    return [281, a - 131, 5];

                  case 194 >= a:
                    return [282, a - 163, 5];

                  case 226 >= a:
                    return [283, a - 195, 5];

                  case 257 >= a:
                    return [284, a - 227, 5];

                  case 258 === a:
                    return [285, a - 258, 0];

                  default:
                    i("invalid length: " + a);
                }
              }

              var Aa = [],
                  za,
                  Ba;

              for (za = 3; 258 >= za; za++) {
                Ba = xa(), Aa[za] = Ba[2] << 24 | Ba[1] << 16 | Ba[0];
              }

              var Ca = H ? new Uint32Array(Aa) : Aa;

              function sa(a, c) {
                function b(a, c) {
                  var b = a.G,
                      d = [],
                      e = 0,
                      f;
                  f = Ca[a.length];
                  d[e++] = f & 65535;
                  d[e++] = f >> 16 & 255;
                  d[e++] = f >> 24;
                  var g;

                  switch (v) {
                    case 1 === b:
                      g = [0, b - 1, 0];
                      break;

                    case 2 === b:
                      g = [1, b - 2, 0];
                      break;

                    case 3 === b:
                      g = [2, b - 3, 0];
                      break;

                    case 4 === b:
                      g = [3, b - 4, 0];
                      break;

                    case 6 >= b:
                      g = [4, b - 5, 1];
                      break;

                    case 8 >= b:
                      g = [5, b - 7, 1];
                      break;

                    case 12 >= b:
                      g = [6, b - 9, 2];
                      break;

                    case 16 >= b:
                      g = [7, b - 13, 2];
                      break;

                    case 24 >= b:
                      g = [8, b - 17, 3];
                      break;

                    case 32 >= b:
                      g = [9, b - 25, 3];
                      break;

                    case 48 >= b:
                      g = [10, b - 33, 4];
                      break;

                    case 64 >= b:
                      g = [11, b - 49, 4];
                      break;

                    case 96 >= b:
                      g = [12, b - 65, 5];
                      break;

                    case 128 >= b:
                      g = [13, b - 97, 5];
                      break;

                    case 192 >= b:
                      g = [14, b - 129, 6];
                      break;

                    case 256 >= b:
                      g = [15, b - 193, 6];
                      break;

                    case 384 >= b:
                      g = [16, b - 257, 7];
                      break;

                    case 512 >= b:
                      g = [17, b - 385, 7];
                      break;

                    case 768 >= b:
                      g = [18, b - 513, 8];
                      break;

                    case 1024 >= b:
                      g = [19, b - 769, 8];
                      break;

                    case 1536 >= b:
                      g = [20, b - 1025, 9];
                      break;

                    case 2048 >= b:
                      g = [21, b - 1537, 9];
                      break;

                    case 3072 >= b:
                      g = [22, b - 2049, 10];
                      break;

                    case 4096 >= b:
                      g = [23, b - 3073, 10];
                      break;

                    case 6144 >= b:
                      g = [24, b - 4097, 11];
                      break;

                    case 8192 >= b:
                      g = [25, b - 6145, 11];
                      break;

                    case 12288 >= b:
                      g = [26, b - 8193, 12];
                      break;

                    case 16384 >= b:
                      g = [27, b - 12289, 12];
                      break;

                    case 24576 >= b:
                      g = [28, b - 16385, 13];
                      break;

                    case 32768 >= b:
                      g = [29, b - 24577, 13];
                      break;

                    default:
                      i("invalid distance");
                  }

                  f = g;
                  d[e++] = f[0];
                  d[e++] = f[1];
                  d[e++] = f[2];
                  var h, j;
                  h = 0;

                  for (j = d.length; h < j; ++h) {
                    l[q++] = d[h];
                  }

                  t[d[0]]++;
                  z[d[3]]++;
                  E = a.length + c - 1;
                  n = null;
                }

                var e,
                    f,
                    d,
                    g,
                    h,
                    m = {},
                    j,
                    s,
                    n,
                    l = H ? new Uint16Array(2 * c.length) : [],
                    q = 0,
                    E = 0,
                    t = new (H ? Uint32Array : Array)(286),
                    z = new (H ? Uint32Array : Array)(30),
                    K = a.w,
                    A;

                if (!H) {
                  for (d = 0; 285 >= d;) {
                    t[d++] = 0;
                  }

                  for (d = 0; 29 >= d;) {
                    z[d++] = 0;
                  }
                }

                t[256] = 1;
                e = 0;

                for (f = c.length; e < f; ++e) {
                  d = h = 0;

                  for (g = 3; d < g && e + d !== f; ++d) {
                    h = h << 8 | c[e + d];
                  }

                  m[h] === r && (m[h] = []);
                  j = m[h];

                  if (!(0 < E--)) {
                    for (; 0 < j.length && 32768 < e - j[0];) {
                      j.shift();
                    }

                    if (e + 3 >= f) {
                      n && b(n, -1);
                      d = 0;

                      for (g = f - e; d < g; ++d) {
                        A = c[e + d], l[q++] = A, ++t[A];
                      }

                      break;
                    }

                    if (0 < j.length) {
                      var x = r,
                          B = r,
                          k = 0,
                          p = r,
                          D = r,
                          C = r,
                          da = r,
                          W = c.length,
                          D = 0,
                          da = j.length;

                      a: for (; D < da; D++) {
                        x = j[da - D - 1];
                        p = 3;

                        if (3 < k) {
                          for (C = k; 3 < C; C--) {
                            if (c[x + C - 1] !== c[e + C - 1]) continue a;
                          }

                          p = k;
                        }

                        for (; 258 > p && e + p < W && c[x + p] === c[e + p];) {
                          ++p;
                        }

                        p > k && (B = x, k = p);
                        if (258 === p) break;
                      }

                      s = new wa(k, e - B);
                      n ? n.length < s.length ? (A = c[e - 1], l[q++] = A, ++t[A], b(s, 0)) : b(n, -1) : s.length < K ? n = s : b(s, 0);
                    } else n ? b(n, -1) : (A = c[e], l[q++] = A, ++t[A]);
                  }

                  j.push(e);
                }

                l[q++] = 256;
                t[256]++;
                a.L = t;
                a.K = z;
                return H ? l.subarray(0, q) : l;
              }

              function ta(a, c) {
                function b(a) {
                  var c = z[a][K[a]];
                  c === n ? (b(a + 1), b(a + 1)) : --E[c];
                  ++K[a];
                }

                var e = a.length,
                    f = new la(572),
                    d = new (H ? Uint8Array : Array)(e),
                    g,
                    h,
                    m,
                    j,
                    s;
                if (!H) for (j = 0; j < e; j++) {
                  d[j] = 0;
                }

                for (j = 0; j < e; ++j) {
                  0 < a[j] && f.push(j, a[j]);
                }

                g = Array(f.length / 2);
                h = new (H ? Uint32Array : Array)(f.length / 2);
                if (1 === g.length) return d[f.pop().index] = 1, d;
                j = 0;

                for (s = f.length / 2; j < s; ++j) {
                  g[j] = f.pop(), h[j] = g[j].value;
                }

                var n = h.length,
                    l = new (H ? Uint16Array : Array)(c),
                    q = new (H ? Uint8Array : Array)(c),
                    E = new (H ? Uint8Array : Array)(n),
                    t = Array(c),
                    z = Array(c),
                    K = Array(c),
                    A = (1 << c) - n,
                    x = 1 << c - 1,
                    B,
                    k,
                    p,
                    D,
                    C;
                l[c - 1] = n;

                for (k = 0; k < c; ++k) {
                  A < x ? q[k] = 0 : (q[k] = 1, A -= x), A <<= 1, l[c - 2 - k] = (l[c - 1 - k] / 2 | 0) + n;
                }

                l[0] = q[0];
                t[0] = Array(l[0]);
                z[0] = Array(l[0]);

                for (k = 1; k < c; ++k) {
                  l[k] > 2 * l[k - 1] + q[k] && (l[k] = 2 * l[k - 1] + q[k]), t[k] = Array(l[k]), z[k] = Array(l[k]);
                }

                for (B = 0; B < n; ++B) {
                  E[B] = c;
                }

                for (p = 0; p < l[c - 1]; ++p) {
                  t[c - 1][p] = h[p], z[c - 1][p] = p;
                }

                for (B = 0; B < c; ++B) {
                  K[B] = 0;
                }

                1 === q[c - 1] && (--E[0], ++K[c - 1]);

                for (k = c - 2; 0 <= k; --k) {
                  D = B = 0;
                  C = K[k + 1];

                  for (p = 0; p < l[k]; p++) {
                    D = t[k + 1][C] + t[k + 1][C + 1], D > h[B] ? (t[k][p] = D, z[k][p] = n, C += 2) : (t[k][p] = h[B], z[k][p] = B, ++B);
                  }

                  K[k] = 0;
                  1 === q[k] && b(k);
                }

                m = E;
                j = 0;

                for (s = g.length; j < s; ++j) {
                  d[g[j].index] = m[j];
                }

                return d;
              }

              function ua(a) {
                var c = new (H ? Uint16Array : Array)(a.length),
                    b = [],
                    e = [],
                    f = 0,
                    d,
                    g,
                    h,
                    m;
                d = 0;

                for (g = a.length; d < g; d++) {
                  b[a[d]] = (b[a[d]] | 0) + 1;
                }

                d = 1;

                for (g = 16; d <= g; d++) {
                  e[d] = f, f += b[d] | 0, f > 1 << d && i("overcommitted"), f <<= 1;
                }

                65536 > f && i("undercommitted");
                d = 0;

                for (g = a.length; d < g; d++) {
                  f = e[a[d]];
                  e[a[d]] += 1;
                  h = c[d] = 0;

                  for (m = a[d]; h < m; h++) {
                    c[d] = c[d] << 1 | f & 1, f >>>= 1;
                  }
                }

                return c;
              }

              function Da(a, c) {
                this.input = a;
                this.a = new (H ? Uint8Array : Array)(32768);
                this.h = U.j;
                var b = {},
                    e;
                if ((c || !(c = {})) && "number" === typeof c.compressionType) this.h = c.compressionType;

                for (e in c) {
                  b[e] = c[e];
                }

                b.outputBuffer = this.a;
                this.z = new ma(this.input, b);
              }

              var U = qa;

              Da.prototype.n = function () {
                var a,
                    c,
                    b,
                    e,
                    f,
                    d,
                    g,
                    h = 0;
                g = this.a;
                a = Ea;

                switch (a) {
                  case Ea:
                    c = Math.LOG2E * Math.log(32768) - 8;
                    break;

                  default:
                    i(Error("invalid compression method"));
                }

                b = c << 4 | a;
                g[h++] = b;

                switch (a) {
                  case Ea:
                    switch (this.h) {
                      case U.NONE:
                        f = 0;
                        break;

                      case U.r:
                        f = 1;
                        break;

                      case U.j:
                        f = 2;
                        break;

                      default:
                        i(Error("unsupported compression type"));
                    }

                    break;

                  default:
                    i(Error("invalid compression method"));
                }

                e = f << 6 | 0;
                g[h++] = e | 31 - (256 * b + e) % 31;
                d = ba(this.input);
                this.z.b = h;
                g = this.z.n();
                h = g.length;
                H && (g = new Uint8Array(g.buffer), g.length <= h + 4 && (this.a = new Uint8Array(g.length + 4), this.a.set(g), g = this.a), g = g.subarray(0, h + 4));
                g[h++] = d >> 24 & 255;
                g[h++] = d >> 16 & 255;
                g[h++] = d >> 8 & 255;
                g[h++] = d & 255;
                return g;
              };

              y("Zlib.Deflate", Da);
              y("Zlib.Deflate.compress", function (a, c) {
                return new Da(a, c).n();
              });
              y("Zlib.Deflate.CompressionType", U);
              y("Zlib.Deflate.CompressionType.NONE", U.NONE);
              y("Zlib.Deflate.CompressionType.FIXED", U.r);
              y("Zlib.Deflate.CompressionType.DYNAMIC", U.j);

              function V(a, c) {
                this.k = [];
                this.l = 32768;
                this.e = this.g = this.c = this.q = 0;
                this.input = H ? new Uint8Array(a) : a;
                this.s = !1;
                this.m = Fa;
                this.B = !1;
                if (c || !(c = {})) c.index && (this.c = c.index), c.bufferSize && (this.l = c.bufferSize), c.bufferType && (this.m = c.bufferType), c.resize && (this.B = c.resize);

                switch (this.m) {
                  case Ga:
                    this.b = 32768;
                    this.a = new (H ? Uint8Array : Array)(32768 + this.l + 258);
                    break;

                  case Fa:
                    this.b = 0;
                    this.a = new (H ? Uint8Array : Array)(this.l);
                    this.f = this.J;
                    this.t = this.H;
                    this.o = this.I;
                    break;

                  default:
                    i(Error("invalid inflate mode"));
                }
              }

              var Ga = 0,
                  Fa = 1,
                  Ha = {
                D: Ga,
                C: Fa
              };

              V.prototype.p = function () {
                for (; !this.s;) {
                  var a = X(this, 3);
                  a & 1 && (this.s = v);
                  a >>>= 1;

                  switch (a) {
                    case 0:
                      var c = this.input,
                          b = this.c,
                          e = this.a,
                          f = this.b,
                          d = r,
                          g = r,
                          h = r,
                          m = e.length,
                          j = r;
                      this.e = this.g = 0;
                      d = c[b++];
                      d === r && i(Error("invalid uncompressed block header: LEN (first byte)"));
                      g = d;
                      d = c[b++];
                      d === r && i(Error("invalid uncompressed block header: LEN (second byte)"));
                      g |= d << 8;
                      d = c[b++];
                      d === r && i(Error("invalid uncompressed block header: NLEN (first byte)"));
                      h = d;
                      d = c[b++];
                      d === r && i(Error("invalid uncompressed block header: NLEN (second byte)"));
                      h |= d << 8;
                      g === ~h && i(Error("invalid uncompressed block header: length verify"));
                      b + g > c.length && i(Error("input buffer is broken"));

                      switch (this.m) {
                        case Ga:
                          for (; f + g > e.length;) {
                            j = m - f;
                            g -= j;
                            if (H) e.set(c.subarray(b, b + j), f), f += j, b += j;else for (; j--;) {
                              e[f++] = c[b++];
                            }
                            this.b = f;
                            e = this.f();
                            f = this.b;
                          }

                          break;

                        case Fa:
                          for (; f + g > e.length;) {
                            e = this.f({
                              v: 2
                            });
                          }

                          break;

                        default:
                          i(Error("invalid inflate mode"));
                      }

                      if (H) e.set(c.subarray(b, b + g), f), f += g, b += g;else for (; g--;) {
                        e[f++] = c[b++];
                      }
                      this.c = b;
                      this.b = f;
                      this.a = e;
                      break;

                    case 1:
                      this.o(Ia, Ja);
                      break;

                    case 2:
                      Ka(this);
                      break;

                    default:
                      i(Error("unknown BTYPE: " + a));
                  }
                }

                return this.t();
              };

              var La = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15],
                  Za = H ? new Uint16Array(La) : La,
                  $a = [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 258, 258],
                  ab = H ? new Uint16Array($a) : $a,
                  bb = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0],
                  cb = H ? new Uint8Array(bb) : bb,
                  db = [1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577],
                  eb = H ? new Uint16Array(db) : db,
                  fb = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13],
                  gb = H ? new Uint8Array(fb) : fb,
                  hb = new (H ? Uint8Array : Array)(288),
                  Y,
                  ib;
              Y = 0;

              for (ib = hb.length; Y < ib; ++Y) {
                hb[Y] = 143 >= Y ? 8 : 255 >= Y ? 9 : 279 >= Y ? 7 : 8;
              }

              var Ia = S(hb),
                  jb = new (H ? Uint8Array : Array)(30),
                  kb,
                  lb;
              kb = 0;

              for (lb = jb.length; kb < lb; ++kb) {
                jb[kb] = 5;
              }

              var Ja = S(jb);

              function X(a, c) {
                for (var b = a.g, e = a.e, f = a.input, d = a.c, g; e < c;) {
                  g = f[d++], g === r && i(Error("input buffer is broken")), b |= g << e, e += 8;
                }

                g = b & (1 << c) - 1;
                a.g = b >>> c;
                a.e = e - c;
                a.c = d;
                return g;
              }

              function mb(a, c) {
                for (var b = a.g, e = a.e, f = a.input, d = a.c, g = c[0], h = c[1], m, j, s; e < h;) {
                  m = f[d++], m === r && i(Error("input buffer is broken")), b |= m << e, e += 8;
                }

                j = g[b & (1 << h) - 1];
                s = j >>> 16;
                a.g = b >> s;
                a.e = e - s;
                a.c = d;
                return j & 65535;
              }

              function Ka(a) {
                function c(a, b, c) {
                  var d, e, f, g;

                  for (g = 0; g < a;) {
                    switch (d = mb(this, b), d) {
                      case 16:
                        for (f = 3 + X(this, 2); f--;) {
                          c[g++] = e;
                        }

                        break;

                      case 17:
                        for (f = 3 + X(this, 3); f--;) {
                          c[g++] = 0;
                        }

                        e = 0;
                        break;

                      case 18:
                        for (f = 11 + X(this, 7); f--;) {
                          c[g++] = 0;
                        }

                        e = 0;
                        break;

                      default:
                        e = c[g++] = d;
                    }
                  }

                  return c;
                }

                var b = X(a, 5) + 257,
                    e = X(a, 5) + 1,
                    f = X(a, 4) + 4,
                    d = new (H ? Uint8Array : Array)(Za.length),
                    g,
                    h,
                    m,
                    j;

                for (j = 0; j < f; ++j) {
                  d[Za[j]] = X(a, 3);
                }

                g = S(d);
                h = new (H ? Uint8Array : Array)(b);
                m = new (H ? Uint8Array : Array)(e);
                a.o(S(c.call(a, b, g, h)), S(c.call(a, e, g, m)));
              }

              V.prototype.o = function (a, c) {
                var b = this.a,
                    e = this.b;
                this.u = a;

                for (var f = b.length - 258, d, g, h, m; 256 !== (d = mb(this, a));) {
                  if (256 > d) e >= f && (this.b = e, b = this.f(), e = this.b), b[e++] = d;else {
                    g = d - 257;
                    m = ab[g];
                    0 < cb[g] && (m += X(this, cb[g]));
                    d = mb(this, c);
                    h = eb[d];
                    0 < gb[d] && (h += X(this, gb[d]));
                    e >= f && (this.b = e, b = this.f(), e = this.b);

                    for (; m--;) {
                      b[e] = b[e++ - h];
                    }
                  }
                }

                for (; 8 <= this.e;) {
                  this.e -= 8, this.c--;
                }

                this.b = e;
              };

              V.prototype.I = function (a, c) {
                var b = this.a,
                    e = this.b;
                this.u = a;

                for (var f = b.length, d, g, h, m; 256 !== (d = mb(this, a));) {
                  if (256 > d) e >= f && (b = this.f(), f = b.length), b[e++] = d;else {
                    g = d - 257;
                    m = ab[g];
                    0 < cb[g] && (m += X(this, cb[g]));
                    d = mb(this, c);
                    h = eb[d];
                    0 < gb[d] && (h += X(this, gb[d]));
                    e + m > f && (b = this.f(), f = b.length);

                    for (; m--;) {
                      b[e] = b[e++ - h];
                    }
                  }
                }

                for (; 8 <= this.e;) {
                  this.e -= 8, this.c--;
                }

                this.b = e;
              };

              V.prototype.f = function () {
                var a = new (H ? Uint8Array : Array)(this.b - 32768),
                    c = this.b - 32768,
                    b,
                    e,
                    f = this.a;
                if (H) a.set(f.subarray(32768, a.length));else {
                  b = 0;

                  for (e = a.length; b < e; ++b) {
                    a[b] = f[b + 32768];
                  }
                }
                this.k.push(a);
                this.q += a.length;
                if (H) f.set(f.subarray(c, c + 32768));else for (b = 0; 32768 > b; ++b) {
                  f[b] = f[c + b];
                }
                this.b = 32768;
                return f;
              };

              V.prototype.J = function (a) {
                var c,
                    b = this.input.length / this.c + 1 | 0,
                    e,
                    f,
                    d,
                    g = this.input,
                    h = this.a;
                a && ("number" === typeof a.v && (b = a.v), "number" === typeof a.F && (b += a.F));
                2 > b ? (e = (g.length - this.c) / this.u[2], d = 258 * (e / 2) | 0, f = d < h.length ? h.length + d : h.length << 1) : f = h.length * b;
                H ? (c = new Uint8Array(f), c.set(h)) : c = h;
                return this.a = c;
              };

              V.prototype.t = function () {
                var a = 0,
                    c = this.a,
                    b = this.k,
                    e,
                    f = new (H ? Uint8Array : Array)(this.q + (this.b - 32768)),
                    d,
                    g,
                    h,
                    m;
                if (0 === b.length) return H ? this.a.subarray(32768, this.b) : this.a.slice(32768, this.b);
                d = 0;

                for (g = b.length; d < g; ++d) {
                  e = b[d];
                  h = 0;

                  for (m = e.length; h < m; ++h) {
                    f[a++] = e[h];
                  }
                }

                d = 32768;

                for (g = this.b; d < g; ++d) {
                  f[a++] = c[d];
                }

                this.k = [];
                return this.buffer = f;
              };

              V.prototype.H = function () {
                var a,
                    c = this.b;
                H ? this.B ? (a = new Uint8Array(c), a.set(this.a.subarray(0, c))) : a = this.a.subarray(0, c) : (this.a.length > c && (this.a.length = c), a = this.a);
                return this.buffer = a;
              };

              function nb(a, c) {
                var b, e;
                this.input = a;
                this.c = 0;
                if (c || !(c = {})) c.index && (this.c = c.index), c.verify && (this.M = c.verify);
                b = a[this.c++];
                e = a[this.c++];

                switch (b & 15) {
                  case Ea:
                    this.method = Ea;
                    break;

                  default:
                    i(Error("unsupported compression method"));
                }

                0 !== ((b << 8) + e) % 31 && i(Error("invalid fcheck flag:" + ((b << 8) + e) % 31));
                e & 32 && i(Error("fdict flag is not supported"));
                this.A = new V(a, {
                  index: this.c,
                  bufferSize: c.bufferSize,
                  bufferType: c.bufferType,
                  resize: c.resize
                });
              }

              nb.prototype.p = function () {
                var a = this.input,
                    c,
                    b;
                c = this.A.p();
                this.c = this.A.c;
                this.M && (b = (a[this.c++] << 24 | a[this.c++] << 16 | a[this.c++] << 8 | a[this.c++]) >>> 0, b !== ba(c) && i(Error("invalid adler-32 checksum")));
                return c;
              };

              y("Zlib.Inflate", nb);
              y("Zlib.Inflate.BufferType", Ha);
              Ha.ADAPTIVE = Ha.C;
              Ha.BLOCK = Ha.D;
              y("Zlib.Inflate.prototype.decompress", nb.prototype.p);
              var tb = new (H ? Uint8Array : Array)(288),
                  Z,
                  ub;
              Z = 0;

              for (ub = tb.length; Z < ub; ++Z) {
                tb[Z] = 143 >= Z ? 8 : 255 >= Z ? 9 : 279 >= Z ? 7 : 8;
              }

              S(tb);
              var vb = new (H ? Uint8Array : Array)(30),
                  wb,
                  xb;
              wb = 0;

              for (xb = vb.length; wb < xb; ++wb) {
                vb[wb] = 5;
              }

              S(vb);
              var Ea = 8;
            }).call(window$1);
            var _p = window$1.Zlib;
            _p.Deflate = _p["Deflate"];
            _p.Deflate.compress = _p.Deflate["compress"];
            _p.Inflate = _p["Inflate"];
            _p.Inflate.BufferType = _p.Inflate["BufferType"];
            _p.Inflate.prototype.decompress = _p.Inflate.prototype["decompress"];

            var PNGReader = function () {
              function PNGReader(data) {
                var _this = this;

                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
                };
                var frame;
                var i = 0;
                var _i = 0;
                var _j = 0;
                var chunkSize = 0;

                while (true) {
                  chunkSize = this.readUInt32();

                  var section = function () {
                    var _results = [];

                    for (i = _i = 0; _i < 4; i = ++_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()
                      };
                      var delayNum = this.readUInt16();
                      var 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 = _i = 0; chunkSize >= 0 ? _i < chunkSize : _i > chunkSize; i = 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);
                          var ccshort = 255 - this.transparency.indexed.length;

                          if (ccshort > 0) {
                            for (i = _j = 0; ccshort >= 0 ? _j < ccshort : _j > ccshort; i = 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':
                      var text = this.read(chunkSize);
                      var index = text.indexOf(0);
                      var 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 = function () {
                        switch (_this.colorType) {
                          case 0:
                          case 3:
                          case 4:
                            return 1;

                          case 2:
                          case 6:
                            return 3;
                        }
                      }.call(this);

                      var _ref = this.colorType;
                      this.hasAlphaChannel = _ref === 4 || _ref === 6;
                      var colors = this.colors + (this.hasAlphaChannel ? 1 : 0);
                      this.pixelBitlength = this.bits * colors;

                      this.colorSpace = function () {
                        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));
                  }
                }
              }

              var _proto = PNGReader.prototype;

              _proto.read = function read(bytes) {
                var i = 0;
                var _i = 0;
                var _results = [];

                for (i = _i = 0; bytes >= 0 ? _i < bytes : _i > bytes; i = bytes >= 0 ? ++_i : --_i) {
                  _results.push(this.data[this.pos++]);
                }

                return _results;
              };

              _proto.readUInt32 = function readUInt32() {
                var b1 = this.data[this.pos++] << 24;
                var b2 = this.data[this.pos++] << 16;
                var b3 = this.data[this.pos++] << 8;
                var b4 = this.data[this.pos++];
                return b1 | b2 | b3 | b4;
              };

              _proto.readUInt16 = function readUInt16() {
                var b1 = this.data[this.pos++] << 8;
                var b2 = this.data[this.pos++];
                return b1 | b2;
              };

              _proto.decodePixels = function decodePixels(data) {
                if (data == null) {
                  data = this.imgData;
                }

                if (data.length === 0) {
                  return new Uint8Array(0);
                }

                var inflate = new _p.Inflate(data, {
                  index: 0,
                  verify: false
                });
                data = inflate.decompress();
                var pixelBytes = this.pixelBitlength / 8;
                var scanlineLength = pixelBytes * this.width;
                var pixels = new Uint8Array(scanlineLength * this.height);
                var length = data.length;
                var row = 0;
                var pos = 0;
                var c = 0;
                var ccbyte = 0;
                var col = 0;
                var i = 0;
                var _i = 0;
                var _j = 0;
                var _k = 0;
                var _l = 0;
                var _m = 0;
                var left = 0;
                var p = 0;
                var pa = 0;
                var paeth = 0;
                var pb = 0;
                var pc = 0;
                var upper = 0;
                var 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;
              };

              _proto.copyToImageData = function copyToImageData(imageData, pixels) {
                var alpha = this.hasAlphaChannel;
                var palette;
                var colors = this.colors;

                if (this.palette.length) {
                  palette = this._decodedPalette != null ? this._decodedPalette : this._decodedPalette = this.decodePalette();
                  colors = 4;
                  alpha = true;
                }

                var data = imageData.data || imageData;
                var length = data.length;
                var input = palette || pixels;
                var i = 0;
                var j = 0;
                var k = 0;
                var 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;
                  }
                }
              };

              _proto.decodePalette = function decodePalette() {
                var palette = this.palette;
                var transparency = this.transparency.indexed || [];
                var ret = new Uint8Array((transparency.length || 0) + palette.length);
                var pos = 0;
                var c = 0;
                var _ref1 = 0;

                for (var 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;
              };

              _proto.render = function render(canvas) {
                canvas.width = this.width;
                canvas.height = this.height;
                var ctx = canvas.getContext('2d');
                var data = ctx.createImageData(this.width, this.height);
                this.copyToImageData(data, this.decodePixels(null));
                return ctx.putImageData(data, 0, 0);
              };

              return PNGReader;
            }();

            var TiffReader = function () {
              function TiffReader() {
                this._littleEndian = false;
                this._tiffData = [];
                this._fileDirectories = [];
              }

              var _proto = TiffReader.prototype;

              _proto.getUint8 = function getUint8(offset) {
                return this._tiffData[offset];
              };

              _proto.getUint16 = function getUint16(offset) {
                if (this._littleEndian) return this._tiffData[offset + 1] << 8 | this._tiffData[offset];else return this._tiffData[offset] << 8 | this._tiffData[offset + 1];
              };

              _proto.getUint32 = function getUint32(offset) {
                var 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];
              };

              _proto.checkLittleEndian = function checkLittleEndian() {
                var 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;
              };

              _proto.hasTowel = function hasTowel() {
                if (this.getUint16(2) !== 42) {
                  throw RangeError(getError(6020));
                }

                return true;
              };

              _proto.getFieldTypeName = function getFieldTypeName(fieldType) {
                var typeNames = fieldTypeNames;

                if (fieldType in typeNames) {
                  return typeNames[fieldType];
                }

                return null;
              };

              _proto.getFieldTagName = function getFieldTagName(fieldTag) {
                var tagNames = fieldTagNames;

                if (fieldTag in tagNames) {
                  return tagNames[fieldTag];
                } else {
                  logID(6021, fieldTag);
                  return "Tag" + fieldTag;
                }
              };

              _proto.getFieldTypeLength = function 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;
              };

              _proto.getFieldValues = function getFieldValues(fieldTagName, fieldTypeName, typeCount, valueOffset) {
                var fieldValues = [];
                var fieldTypeLength = this.getFieldTypeLength(fieldTypeName);
                var fieldValueSize = fieldTypeLength * typeCount;

                if (fieldValueSize <= 4) {
                  if (this._littleEndian === false) fieldValues.push(valueOffset >>> (4 - fieldTypeLength) * 8);else fieldValues.push(valueOffset);
                } else {
                  for (var i = 0; i < typeCount; i++) {
                    var 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(function (e, i, a) {
                    a[i] = String.fromCharCode(e);
                  });
                }

                return fieldValues;
              };

              _proto.getBytes = function 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;
              };

              _proto.getBits = function getBits(numBits, byteOffset, bitOffset) {
                bitOffset = bitOffset || 0;
                var extraBytes = Math.floor(bitOffset / 8);
                var newByteOffset = byteOffset + extraBytes;
                var totalBits = bitOffset + numBits;
                var shiftRight = 32 - numBits;
                var shiftLeft = 0;
                var 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
                };
              };

              _proto.parseFileDirectory = function parseFileDirectory(offset) {
                var numDirEntries = this.getUint16(offset);
                var tiffFields = [];
                var i = 0;
                var entryCount = 0;

                for (i = offset + 2, entryCount = 0; entryCount < numDirEntries; i += 12, entryCount++) {
                  var fieldTag = this.getUint16(i);
                  var fieldType = this.getUint16(i + 2);
                  var typeCount = this.getUint32(i + 4);
                  var valueOffset = this.getUint32(i + 8);
                  var fieldTagName = this.getFieldTagName(fieldTag);
                  var fieldTypeName = this.getFieldTypeName(fieldType);
                  var fieldValues = this.getFieldValues(fieldTagName, fieldTypeName, typeCount, valueOffset);
                  tiffFields[fieldTagName] = {
                    type: fieldTypeName,
                    values: fieldValues
                  };
                }

                this._fileDirectories.push(tiffFields);

                var nextIFDByteOffset = this.getUint32(i);

                if (nextIFDByteOffset !== 0x00000000) {
                  this.parseFileDirectory(nextIFDByteOffset);
                }
              };

              _proto.clampColorSample = function clampColorSample(colorSample, bitsPerSample) {
                var multiplier = Math.pow(2, 8 - bitsPerSample);
                return Math.floor(colorSample * multiplier + (multiplier - 1));
              };

              _proto.parseTIFF = function parseTIFF(tiffData, canvas) {
                var _this = this;

                canvas = canvas || document.createElement('canvas');
                this._tiffData = tiffData;
                this._canvas = canvas;
                this.checkLittleEndian();

                if (!this.hasTowel()) {
                  return;
                }

                var firstIFDByteOffset = this.getUint32(4);
                this._fileDirectories.length = 0;
                this.parseFileDirectory(firstIFDByteOffset);
                var fileDirectory = this._fileDirectories[0];
                var imageWidth = fileDirectory.ImageWidth.values[0];
                var imageLength = fileDirectory.ImageLength.values[0];
                this._canvas.width = imageWidth;
                this._canvas.height = imageLength;
                var strips = [];
                var compression = fileDirectory.Compression ? fileDirectory.Compression.values[0] : 1;
                var samplesPerPixel = fileDirectory.SamplesPerPixel.values[0];
                var sampleProperties = [];
                var bitsPerPixel = 0;
                var hasBytesPerPixel = false;
                fileDirectory.BitsPerSample.values.forEach(function (bitsPerSample, i, bitsPerSampleValues) {
                  sampleProperties[i] = {
                    bitsPerSample: bitsPerSample,
                    hasBytesPerSample: false,
                    bytesPerSample: undefined
                  };

                  if (bitsPerSample % 8 === 0) {
                    sampleProperties[i].hasBytesPerSample = true;
                    sampleProperties[i].bytesPerSample = bitsPerSample / 8;
                  }

                  bitsPerPixel += bitsPerSample;
                }, this);
                var bytesPerPixel = 0;

                if (bitsPerPixel % 8 === 0) {
                  hasBytesPerPixel = true;
                  bytesPerPixel = bitsPerPixel / 8;
                }

                var stripOffsetValues = fileDirectory.StripOffsets.values;
                var numStripOffsetValues = stripOffsetValues.length;
                var 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));
                  }
                }

                var blockLength = 1;
                var iterations = 1;

                for (var i = 0; i < numStripOffsetValues; i++) {
                  var stripOffset = stripOffsetValues[i];
                  strips[i] = [];
                  var stripByteCount = stripByteCountValues[i];

                  for (var 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 (var m = 0; m < samplesPerPixel; m++) {
                          var s = sampleProperties[m];

                          if (s.hasBytesPerSample) {
                            var sampleOffset = s.bytesPerSample * m;
                            pixel.push(this.getBytes(s.bytesPerSample, stripOffset + byteOffset + sampleOffset));
                          } else {
                            var 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;
                          var 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 {
                          var currentByte = this.getUint8(stripOffset + byteOffset);

                          for (var _m = 0; _m < iterations; _m++) {
                            var _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) {
                  var ctx = this._canvas.getContext('2d');

                  ctx.fillStyle = 'rgba(255, 255, 255, 0)';
                  var rowsPerStrip = fileDirectory.RowsPerStrip ? fileDirectory.RowsPerStrip.values[0] : imageLength;
                  var numStrips = strips.length;
                  var imageLengthModRowsPerStrip = imageLength % rowsPerStrip;
                  var rowsInLastStrip = imageLengthModRowsPerStrip === 0 ? rowsPerStrip : imageLengthModRowsPerStrip;
                  var numRowsInStrip = rowsPerStrip;
                  var numRowsInPreviousStrip = 0;
                  var photometricInterpretation = fileDirectory.PhotometricInterpretation.values[0];
                  var extraSamplesValues = [];
                  var numExtraSamples = 0;

                  if (fileDirectory.ExtraSamples) {
                    extraSamplesValues = fileDirectory.ExtraSamples.values;
                    numExtraSamples = extraSamplesValues.length;
                  }

                  var colorMapValues = [];
                  var colorMapSampleSize = 0;

                  if (fileDirectory.ColorMap) {
                    colorMapValues = fileDirectory.ColorMap.values;
                    colorMapSampleSize = Math.pow(2, sampleProperties[0].bitsPerSample);
                  }

                  for (var _i = 0; _i < numStrips; _i++) {
                    if (_i + 1 === numStrips) {
                      numRowsInStrip = rowsInLastStrip;
                    }

                    var numPixels = strips[_i].length;
                    var yPadding = numRowsInPreviousStrip * _i;

                    for (var y = 0, j = 0; y < numRowsInStrip && j < numPixels; y++) {
                      for (var x = 0; x < imageWidth; x++, j++) {
                        var pixelSamples = strips[_i][j];
                        var red = 0;
                        var green = 0;
                        var blue = 0;
                        var opacity = 1.0;

                        if (numExtraSamples > 0) {
                          for (var k = 0; k < numExtraSamples; k++) {
                            if (extraSamplesValues[k] === 1 || extraSamplesValues[k] === 2) {
                              opacity = pixelSamples[3 + k] / 256;
                              break;
                            }
                          }
                        }

                        (function () {
                          switch (photometricInterpretation) {
                            case 0:
                              var invertValue = 0;

                              if (sampleProperties[0].hasBytesPerSample) {
                                invertValue = Math.pow(0x10, sampleProperties[0].bytesPerSample * 2);
                              }

                              pixelSamples.forEach(function (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));
                              }

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

              return TiffReader;
            }();
            var 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'
            };
            var 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'
            };

            var BASE64_KEYS$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
            var BASE64_VALUES$1 = new Array(123);

            for (var i$4 = 0; i$4 < 123; ++i$4) {
              BASE64_VALUES$1[i$4] = 64;
            }

            for (var _i$1 = 0; _i$1 < 64; ++_i$1) {
              BASE64_VALUES$1[BASE64_KEYS$1.charCodeAt(_i$1)] = _i$1;
            }

            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$1[input.charCodeAt(i++)];
                enc2 = BASE64_VALUES$1[input.charCodeAt(i++)];
                enc3 = BASE64_VALUES$1[input.charCodeAt(i++)];
                enc4 = BASE64_VALUES$1[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, os, 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();
              os = 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$1G, _dec2$1c, _dec3$T, _dec4$M, _dec5$D, _dec6$w, _dec7$u, _dec8$r, _dec9$o, _dec10$n, _dec11$m, _dec12$l, _dec13$i, _dec14$f, _dec15$f, _dec16$e, _dec17$d, _dec18$d, _dec19$d, _dec20$c, _dec21$c, _dec22$c, _dec23$c, _dec24$b, _dec25$b, _dec26$a, _dec27$8, _dec28$8, _dec29$8, _dec30$8, _dec31$8, _dec32$7, _dec33$6, _dec34$5, _dec35$4, _dec36$4, _dec37$4, _dec38$4, _dec39$4, _dec40$4, _dec41$3, _dec42$3, _dec43$3, _dec44$2, _dec45$2, _dec46$1, _dec47$1, _dec48$1, _class$1H, _class2$1u, _descriptor$1j, _descriptor2$11, _descriptor3$M, _descriptor4$F, _descriptor5$x, _descriptor6$o, _descriptor7$j, _descriptor8$j, _descriptor9$g, _descriptor10$g, _descriptor11$f, _descriptor12$c, _descriptor13$9, _descriptor14$8, _descriptor15$7, _descriptor16$7, _descriptor17$5, _descriptor18$5, _descriptor19$3, _descriptor20$3, _descriptor21$3, _descriptor22$3, _descriptor23$3, _descriptor24$3, _descriptor25$3, _descriptor26$2, _descriptor27$2, _descriptor28$2, _descriptor29$2, _descriptor30$2, _descriptor31$2, _descriptor32$2, _descriptor33$2, _descriptor34$2, _descriptor35$2, _descriptor36$1, _descriptor37$1, _descriptor38$1, _descriptor39, _descriptor40, _descriptor41, _descriptor42, _descriptor43, _class3$A, _temp$1y;
            var ImageFormat;

            (function (ImageFormat) {
              ImageFormat[ImageFormat["JPG"] = 0] = "JPG";
              ImageFormat[ImageFormat["PNG"] = 1] = "PNG";
              ImageFormat[ImageFormat["TIFF"] = 2] = "TIFF";
              ImageFormat[ImageFormat["WEBP"] = 3] = "WEBP";
              ImageFormat[ImageFormat["PVR"] = 4] = "PVR";
              ImageFormat[ImageFormat["ETC"] = 5] = "ETC";
              ImageFormat[ImageFormat["S3TC"] = 6] = "S3TC";
              ImageFormat[ImageFormat["ATITC"] = 7] = "ATITC";
              ImageFormat[ImageFormat["TGA"] = 8] = "TGA";
              ImageFormat[ImageFormat["RAWDATA"] = 9] = "RAWDATA";
              ImageFormat[ImageFormat["UNKNOWN"] = 10] = "UNKNOWN";
            })(ImageFormat || (ImageFormat = {}));

            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 ImageFormat.PNG;
              }

              if (imgData.length > 2 && (imgData[0] === 0x49 && imgData[1] === 0x49 || imgData[0] === 0x4d && imgData[1] === 0x4d || imgData[0] === 0xff && imgData[1] === 0xd8)) {
                return ImageFormat.TIFF;
              }

              return ImageFormat.UNKNOWN;
            }

            function getParticleComponents(node) {
              var parent = node.parent;
              var comp = node.getComponent(ParticleSystem2D);

              if (!parent || !comp) {
                return node.getComponentsInChildren(ParticleSystem2D);
              }

              return getParticleComponents(parent);
            }

            var ParticleSystem2D = exports('ParticleSystem2D', (_dec$1G = ccclass('cc.ParticleSystem2D'), _dec2$1c = menu(), _dec3$T = tooltip(), _dec4$M = type(ParticleAsset), _dec5$D = tooltip(), _dec6$w = type(SpriteFrame), _dec7$u = tooltip(), _dec8$r = tooltip(), _dec9$o = tooltip(), _dec10$n = tooltip(), _dec11$m = tooltip(), _dec12$l = tooltip(), _dec13$i = tooltip(), _dec14$f = tooltip(), _dec15$f = tooltip(), _dec16$e = tooltip(), _dec17$d = tooltip(), _dec18$d = tooltip(), _dec19$d = tooltip(), _dec20$c = tooltip(), _dec21$c = tooltip(), _dec22$c = tooltip(), _dec23$c = tooltip(), _dec24$b = tooltip(), _dec25$b = tooltip(), _dec26$a = tooltip(), _dec27$8 = tooltip(), _dec28$8 = type(PositionType), _dec29$8 = tooltip(), _dec30$8 = type(EmitterMode), _dec31$8 = tooltip(), _dec32$7 = tooltip(), _dec33$6 = tooltip(), _dec34$5 = tooltip(), _dec35$4 = tooltip(), _dec36$4 = tooltip(), _dec37$4 = tooltip(), _dec38$4 = tooltip(), _dec39$4 = tooltip(), _dec40$4 = tooltip(), _dec41$3 = tooltip(), _dec42$3 = tooltip(), _dec43$3 = tooltip(), _dec44$2 = tooltip(), _dec45$2 = tooltip(), _dec46$1 = tooltip(), _dec47$1 = tooltip(), _dec48$1 = tooltip(), _dec$1G(_class$1H = _dec2$1c(_class$1H = playOnFocus(_class$1H = executeInEditMode(_class$1H = (_class2$1u = (_temp$1y = _class3$A = function (_Renderable2D) {
              _inheritsLoose(ParticleSystem2D, _Renderable2D);

              function ParticleSystem2D() {
                var _this;

                _this = _Renderable2D.call(this) || this;

                _initializerDefineProperty(_this, "duration", _descriptor$1j, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "emissionRate", _descriptor2$11, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "life", _descriptor3$M, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "lifeVar", _descriptor4$F, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "angle", _descriptor5$x, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "angleVar", _descriptor6$o, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "startSize", _descriptor7$j, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "startSizeVar", _descriptor8$j, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "endSize", _descriptor9$g, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "endSizeVar", _descriptor10$g, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "startSpin", _descriptor11$f, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "startSpinVar", _descriptor12$c, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "endSpin", _descriptor13$9, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "endSpinVar", _descriptor14$8, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "sourcePos", _descriptor15$7, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "posVar", _descriptor16$7, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "emitterMode", _descriptor17$5, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "gravity", _descriptor18$5, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "speed", _descriptor19$3, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "speedVar", _descriptor20$3, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "tangentialAccel", _descriptor21$3, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "tangentialAccelVar", _descriptor22$3, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "radialAccel", _descriptor23$3, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "radialAccelVar", _descriptor24$3, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "rotationIsDir", _descriptor25$3, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "startRadius", _descriptor26$2, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "startRadiusVar", _descriptor27$2, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "endRadius", _descriptor28$2, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "endRadiusVar", _descriptor29$2, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "rotatePerS", _descriptor30$2, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "rotatePerSVar", _descriptor31$2, _assertThisInitialized(_this));

                _this.aspectRatio = 1;

                _initializerDefineProperty(_this, "playOnLoad", _descriptor32$2, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "autoRemoveOnFinish", _descriptor33$2, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "preview", _descriptor34$2, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_custom", _descriptor35$2, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_file", _descriptor36$1, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_spriteFrame", _descriptor37$1, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_totalParticles", _descriptor38$1, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_startColor", _descriptor39, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_startColorVar", _descriptor40, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_endColor", _descriptor41, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_endColorVar", _descriptor42, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_positionType", _descriptor43, _assertThisInitialized(_this));

                _this._stopped = true;
                _this._deferredloaded = false;

                _this.initProperties();

                return _this;
              }

              var _proto = ParticleSystem2D.prototype;

              _proto.onEnable = function onEnable() {
                _Renderable2D.prototype.onEnable.call(this);

                this._updateMaterial();
              };

              _proto.onDestroy = function onDestroy() {
                _Renderable2D.prototype.onDestroy.call(this);

                if (this.autoRemoveOnFinish) {
                  this.autoRemoveOnFinish = false;
                }

                this._simulator.uvFilled = 0;
              };

              _proto.initProperties = function initProperties() {
                this._previewTimer = null;
                this._focused = false;
                this.aspectRatio = 1;
                this._simulator = new Simulator(this);
              };

              _proto.onFocusInEditor = function onFocusInEditor() {
                this._focused = true;
                var components = getParticleComponents(this.node);

                for (var i = 0; i < components.length; ++i) {
                  components[i]._startPreview();
                }
              };

              _proto.onLostFocusInEditor = function onLostFocusInEditor() {
                this._focused = false;
                var components = getParticleComponents(this.node);

                for (var i = 0; i < components.length; ++i) {
                  components[i]._stopPreview();
                }
              };

              _proto._startPreview = function _startPreview() {
                if (this.preview) {
                  this.resetSystem();
                }
              };

              _proto._stopPreview = function _stopPreview() {
                if (this.preview) {
                  this.resetSystem();
                  this.stopSystem();
                }

                if (this._previewTimer) {
                  clearInterval(this._previewTimer);
                }
              };

              _proto.__preload = function __preload() {
                _Renderable2D.prototype.__preload.call(this);

                if (this._custom && this.spriteFrame && !this._renderSpriteFrame) {
                  this._applySpriteFrame();
                } else if (this._file) {
                  if (this._custom) {
                    var missCustomTexture = !this._getTexture();

                    if (missCustomTexture) {
                      this._applyFile();
                    }
                  } else {
                    this._applyFile();
                  }
                }

                {
                  if (this.playOnLoad) {
                    this.resetSystem();
                  }
                }
              };

              _proto._flushAssembler = function _flushAssembler() {
                var 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);
                }
              };

              _proto.lateUpdate = function lateUpdate(dt) {
                if (!this._simulator.finished) {
                  this._simulator.step(dt);
                }
              };

              _proto.addParticle = function addParticle() {};

              _proto.stopSystem = function stopSystem() {
                this._stopped = true;

                this._simulator.stop();
              };

              _proto.resetSystem = function resetSystem() {
                this._stopped = false;

                this._simulator.reset();

                this._renderFlag = this._canRender();
              };

              _proto.isFull = function isFull() {
                return this.particleCount >= this.totalParticles;
              };

              _proto._applyFile = function _applyFile() {
                var _this2 = this;

                var file = this._file;

                if (file) {
                  var applyTemp = function applyTemp(err) {
                    if (err || !file) {
                      errorID(6029);
                      return;
                    }

                    if (!_this2.isValid) {
                      return;
                    }

                    _this2._plistFile = file.nativeUrl;

                    if (!_this2._custom) {
                      var isDiffFrame = _this2._spriteFrame !== file.spriteFrame;
                      if (isDiffFrame) _this2.spriteFrame = file.spriteFrame;

                      _this2._initWithDictionary(file._nativeAsset);
                    }

                    if (!_this2._spriteFrame) {
                      if (file.spriteFrame) {
                        _this2.spriteFrame = file.spriteFrame;
                      } else if (_this2._custom) {
                        _this2._initTextureWithDictionary(file._nativeAsset);
                      }
                    } else if (!_this2._renderSpriteFrame && _this2._spriteFrame) {
                      _this2._applySpriteFrame();
                    }

                    _this2._deferredloaded = false;
                  };

                  if (file._nativeAsset) {
                    applyTemp(null);
                  } else {
                    this._deferredloaded = true;
                    assetManager.postLoadNative(file, applyTemp);
                  }
                }
              };

              _proto._initTextureWithDictionary = function _initTextureWithDictionary(dict) {
                var _this3 = this;

                if (dict.spriteFrameUuid) {
                  var spriteFrameUuid = dict.spriteFrameUuid;
                  assetManager.loadAny(spriteFrameUuid, function (err, spriteFrame) {
                    if (err) {
                      dict.spriteFrameUuid = undefined;

                      _this3._initTextureWithDictionary(dict);

                      error(err);
                    } else {
                      _this3.spriteFrame = spriteFrame;
                    }
                  });
                } else {
                  var imgPath = changeBasename(this._plistFile, dict.textureFileName || '');

                  if (dict.textureFileName) {
                    assetManager.loadRemote(imgPath, function (err, imageAsset) {
                      if (err) {
                        dict.textureFileName = undefined;

                        _this3._initTextureWithDictionary(dict);

                        error(err);
                      } else {
                        _this3.spriteFrame = SpriteFrame.createWithImage(imageAsset);
                      }
                    });
                  } else if (dict.textureImageData) {
                    var textureData = dict.textureImageData;

                    if (textureData && textureData.length > 0) {
                      var imageAsset = assetManager.assets.get(imgPath);

                      if (!imageAsset) {
                        var buffer = codec.unzipBase64AsArray(textureData, 1);

                        if (!buffer) {
                          warnID(6030, this._file.name);
                          return false;
                        }

                        var imageFormat = getImageFormatByData(buffer);

                        if (imageFormat !== ImageFormat.TIFF && imageFormat !== ImageFormat.PNG) {
                          warnID(6031, this._file.name);
                          return false;
                        }

                        var canvasObj = document.createElement('canvas');

                        if (imageFormat === ImageFormat.PNG) {
                          var myPngObj = new PNGReader(buffer);
                          myPngObj.render(canvasObj);
                        } else {
                          if (!this._tiffReader) {
                            this._tiffReader = new TiffReader();
                          }

                          this._tiffReader.parseTIFF(buffer, canvasObj);
                        }

                        imageAsset = new ImageAsset(canvasObj);
                        assetManager.assets.add(imgPath, imageAsset);
                      }

                      if (!imageAsset) {
                        warnID(6032, this._file.name);
                      }

                      this.spriteFrame = SpriteFrame.createWithImage(imageAsset);
                    } else {
                      return false;
                    }
                  }
                }

                return true;
              };

              _proto._initWithDictionary = function _initWithDictionary(dict) {
                this.totalParticles = parseInt(dict.maxParticles || 0);
                this.life = parseFloat(dict.particleLifespan || 0);
                this.lifeVar = parseFloat(dict.particleLifespanVariance || 0);
                var _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 || BlendFactor.SRC_ALPHA);
                this._dstBlendFactor = parseInt(dict.blendFuncDestination || BlendFactor.ONE_MINUS_SRC_ALPHA);
                var 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;
                var 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;
                var 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;
                var 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);
                  var 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;
              };

              _proto._onTextureLoaded = function _onTextureLoaded() {
                this._simulator.updateUVs(true);

                this._syncAspect();

                this._updateMaterial();

                this._stopped = false;
                this._renderFlag = this._canRender();
              };

              _proto._syncAspect = function _syncAspect() {
                if (this._renderSpriteFrame) {
                  var frameRect = this._renderSpriteFrame.rect;
                  this.aspectRatio = frameRect.width / frameRect.height;
                }
              };

              _proto._applySpriteFrame = function _applySpriteFrame() {
                this._renderSpriteFrame = this._renderSpriteFrame || this._spriteFrame;

                if (this._renderSpriteFrame) {
                  if (this._renderSpriteFrame.textureLoaded()) {
                    this._onTextureLoaded();
                  } else {
                    this._renderSpriteFrame.once('load', this._onTextureLoaded, this);
                  }
                } else {
                  this.resetSystem();
                }
              };

              _proto._getTexture = function _getTexture() {
                return this._renderSpriteFrame && this._renderSpriteFrame.texture;
              };

              _proto._updateMaterial = function _updateMaterial() {
                var mat = this.getMaterialInstance(0);
                if (mat) mat.recompileShaders({
                  USE_LOCAL: this._positionType !== PositionType.FREE
                });
              };

              _proto._finishedSimulation = function _finishedSimulation() {

                this.resetSystem();
                this.stopSystem();
                this._renderFlag = this._canRender();

                if (this.autoRemoveOnFinish && this._stopped) {
                  this.node.destroy();
                }
              };

              _proto._canRender = function _canRender() {
                return _Renderable2D.prototype._canRender.call(this) && !this._stopped && !this._deferredloaded && this._renderSpriteFrame !== null;
              };

              _proto._render = function _render(render) {
                render.commitComp(this, this._renderSpriteFrame, this._assembler, this._positionType === PositionType.RELATIVE ? this.node.parent : null);
              };

              _createClass(ParticleSystem2D, [{
                key: "custom",
                get: function get() {
                  return this._custom;
                },
                set: function set(value) {

                  if (this._custom !== value) {
                    this._custom = value;

                    this._applyFile();
                  }
                }
              }, {
                key: "file",
                get: function get() {
                  return this._file;
                },
                set: function set(value) {
                  if (this._file !== value) {
                    this._file = value;

                    if (value) {
                      this._applyFile();
                    } else {
                      this.custom = true;
                    }
                  }
                }
              }, {
                key: "spriteFrame",
                get: function get() {
                  return this._spriteFrame;
                },
                set: function set(value) {
                  var lastSprite = this._renderSpriteFrame;

                  if (lastSprite === value) {
                    return;
                  }

                  this._renderSpriteFrame = value;

                  if (!value || value._uuid) {
                    this._spriteFrame = value;
                  }

                  this._applySpriteFrame();
                }
              }, {
                key: "particleCount",
                get: function get() {
                  return this._simulator.particles.length;
                }
              }, {
                key: "totalParticles",
                get: function get() {
                  return this._totalParticles;
                },
                set: function set(value) {
                  if (this._totalParticles === value) return;
                  this._totalParticles = value;
                }
              }, {
                key: "startColor",
                get: function get() {
                  return this._startColor;
                },
                set: function set(val) {
                  this._startColor.r = val.r;
                  this._startColor.g = val.g;
                  this._startColor.b = val.b;
                  this._startColor.a = val.a;
                }
              }, {
                key: "startColorVar",
                get: function get() {
                  return this._startColorVar;
                },
                set: function set(val) {
                  this._startColorVar.r = val.r;
                  this._startColorVar.g = val.g;
                  this._startColorVar.b = val.b;
                  this._startColorVar.a = val.a;
                }
              }, {
                key: "endColor",
                get: function get() {
                  return this._endColor;
                },
                set: function set(val) {
                  this._endColor.r = val.r;
                  this._endColor.g = val.g;
                  this._endColor.b = val.b;
                  this._endColor.a = val.a;
                }
              }, {
                key: "endColorVar",
                get: function get() {
                  return this._endColorVar;
                },
                set: function set(val) {
                  this._endColorVar.r = val.r;
                  this._endColorVar.g = val.g;
                  this._endColorVar.b = val.b;
                  this._endColorVar.a = val.a;
                }
              }, {
                key: "positionType",
                get: function get() {
                  return this._positionType;
                },
                set: function set(val) {
                  this._positionType = val;

                  this._updateMaterial();
                }
              }, {
                key: "stopped",
                get: function get() {
                  return this._stopped;
                }
              }, {
                key: "active",
                get: function get() {
                  return this._simulator.active;
                }
              }, {
                key: "assembler",
                get: function get() {
                  return this._assembler;
                }
              }]);

              return ParticleSystem2D;
            }(Renderable2D), _class3$A.EmitterMode = EmitterMode, _class3$A.PositionType = PositionType, _class3$A.DURATION_INFINITY = DURATION_INFINITY, _class3$A.START_SIZE_EQUAL_TO_END_SIZE = START_SIZE_EQUAL_TO_END_SIZE, _class3$A.START_RADIUS_EQUAL_TO_END_RADIUS = START_RADIUS_EQUAL_TO_END_RADIUS, _temp$1y), (_applyDecoratedDescriptor(_class2$1u.prototype, "custom", [editable, _dec3$T], Object.getOwnPropertyDescriptor(_class2$1u.prototype, "custom"), _class2$1u.prototype), _applyDecoratedDescriptor(_class2$1u.prototype, "file", [_dec4$M, _dec5$D], Object.getOwnPropertyDescriptor(_class2$1u.prototype, "file"), _class2$1u.prototype), _applyDecoratedDescriptor(_class2$1u.prototype, "spriteFrame", [_dec6$w, _dec7$u], Object.getOwnPropertyDescriptor(_class2$1u.prototype, "spriteFrame"), _class2$1u.prototype), _applyDecoratedDescriptor(_class2$1u.prototype, "totalParticles", [editable, _dec8$r], Object.getOwnPropertyDescriptor(_class2$1u.prototype, "totalParticles"), _class2$1u.prototype), _descriptor$1j = _applyDecoratedDescriptor(_class2$1u.prototype, "duration", [serializable, editable, _dec9$o], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return -1;
              }
            }), _descriptor2$11 = _applyDecoratedDescriptor(_class2$1u.prototype, "emissionRate", [serializable, editable, _dec10$n], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 10;
              }
            }), _descriptor3$M = _applyDecoratedDescriptor(_class2$1u.prototype, "life", [serializable, editable, _dec11$m], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1;
              }
            }), _descriptor4$F = _applyDecoratedDescriptor(_class2$1u.prototype, "lifeVar", [serializable, editable, _dec12$l], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _applyDecoratedDescriptor(_class2$1u.prototype, "startColor", [editable, _dec13$i], Object.getOwnPropertyDescriptor(_class2$1u.prototype, "startColor"), _class2$1u.prototype), _applyDecoratedDescriptor(_class2$1u.prototype, "startColorVar", [editable, _dec14$f], Object.getOwnPropertyDescriptor(_class2$1u.prototype, "startColorVar"), _class2$1u.prototype), _applyDecoratedDescriptor(_class2$1u.prototype, "endColor", [editable, _dec15$f], Object.getOwnPropertyDescriptor(_class2$1u.prototype, "endColor"), _class2$1u.prototype), _applyDecoratedDescriptor(_class2$1u.prototype, "endColorVar", [editable, _dec16$e], Object.getOwnPropertyDescriptor(_class2$1u.prototype, "endColorVar"), _class2$1u.prototype), _descriptor5$x = _applyDecoratedDescriptor(_class2$1u.prototype, "angle", [serializable, editable, _dec17$d], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 90;
              }
            }), _descriptor6$o = _applyDecoratedDescriptor(_class2$1u.prototype, "angleVar", [serializable, editable, _dec18$d], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 20;
              }
            }), _descriptor7$j = _applyDecoratedDescriptor(_class2$1u.prototype, "startSize", [serializable, editable, _dec19$d], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 50;
              }
            }), _descriptor8$j = _applyDecoratedDescriptor(_class2$1u.prototype, "startSizeVar", [serializable, editable, _dec20$c], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor9$g = _applyDecoratedDescriptor(_class2$1u.prototype, "endSize", [serializable, editable, _dec21$c], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor10$g = _applyDecoratedDescriptor(_class2$1u.prototype, "endSizeVar", [serializable, editable, _dec22$c], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor11$f = _applyDecoratedDescriptor(_class2$1u.prototype, "startSpin", [serializable, editable, _dec23$c], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor12$c = _applyDecoratedDescriptor(_class2$1u.prototype, "startSpinVar", [serializable, editable, _dec24$b], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor13$9 = _applyDecoratedDescriptor(_class2$1u.prototype, "endSpin", [serializable, editable, _dec25$b], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor14$8 = _applyDecoratedDescriptor(_class2$1u.prototype, "endSpinVar", [serializable, editable, _dec26$a], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor15$7 = _applyDecoratedDescriptor(_class2$1u.prototype, "sourcePos", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return Vec2.ZERO.clone();
              }
            }), _descriptor16$7 = _applyDecoratedDescriptor(_class2$1u.prototype, "posVar", [serializable, editable, _dec27$8], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return Vec2.ZERO.clone();
              }
            }), _applyDecoratedDescriptor(_class2$1u.prototype, "positionType", [_dec28$8, _dec29$8], Object.getOwnPropertyDescriptor(_class2$1u.prototype, "positionType"), _class2$1u.prototype), _descriptor17$5 = _applyDecoratedDescriptor(_class2$1u.prototype, "emitterMode", [serializable, editable, _dec30$8, _dec31$8], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return EmitterMode.GRAVITY;
              }
            }), _descriptor18$5 = _applyDecoratedDescriptor(_class2$1u.prototype, "gravity", [serializable, editable, _dec32$7], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return Vec2.ZERO.clone();
              }
            }), _descriptor19$3 = _applyDecoratedDescriptor(_class2$1u.prototype, "speed", [serializable, editable, _dec33$6], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 180;
              }
            }), _descriptor20$3 = _applyDecoratedDescriptor(_class2$1u.prototype, "speedVar", [serializable, editable, _dec34$5], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 50;
              }
            }), _descriptor21$3 = _applyDecoratedDescriptor(_class2$1u.prototype, "tangentialAccel", [serializable, editable, _dec35$4], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 80;
              }
            }), _descriptor22$3 = _applyDecoratedDescriptor(_class2$1u.prototype, "tangentialAccelVar", [serializable, editable, _dec36$4], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor23$3 = _applyDecoratedDescriptor(_class2$1u.prototype, "radialAccel", [serializable, editable, _dec37$4], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor24$3 = _applyDecoratedDescriptor(_class2$1u.prototype, "radialAccelVar", [serializable, editable, _dec38$4], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor25$3 = _applyDecoratedDescriptor(_class2$1u.prototype, "rotationIsDir", [serializable, editable, _dec39$4], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor26$2 = _applyDecoratedDescriptor(_class2$1u.prototype, "startRadius", [serializable, editable, _dec40$4], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor27$2 = _applyDecoratedDescriptor(_class2$1u.prototype, "startRadiusVar", [serializable, editable, _dec41$3], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor28$2 = _applyDecoratedDescriptor(_class2$1u.prototype, "endRadius", [serializable, editable, _dec42$3], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor29$2 = _applyDecoratedDescriptor(_class2$1u.prototype, "endRadiusVar", [serializable, editable, _dec43$3], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor30$2 = _applyDecoratedDescriptor(_class2$1u.prototype, "rotatePerS", [serializable, editable, _dec44$2], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor31$2 = _applyDecoratedDescriptor(_class2$1u.prototype, "rotatePerSVar", [serializable, editable, _dec45$2], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor32$2 = _applyDecoratedDescriptor(_class2$1u.prototype, "playOnLoad", [serializable, editable, _dec46$1], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _descriptor33$2 = _applyDecoratedDescriptor(_class2$1u.prototype, "autoRemoveOnFinish", [serializable, editable, _dec47$1], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor34$2 = _applyDecoratedDescriptor(_class2$1u.prototype, "preview", [serializable, editable, _dec48$1], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _descriptor35$2 = _applyDecoratedDescriptor(_class2$1u.prototype, "_custom", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor36$1 = _applyDecoratedDescriptor(_class2$1u.prototype, "_file", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor37$1 = _applyDecoratedDescriptor(_class2$1u.prototype, "_spriteFrame", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor38$1 = _applyDecoratedDescriptor(_class2$1u.prototype, "_totalParticles", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 150;
              }
            }), _descriptor39 = _applyDecoratedDescriptor(_class2$1u.prototype, "_startColor", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new Color(255, 255, 255, 255);
              }
            }), _descriptor40 = _applyDecoratedDescriptor(_class2$1u.prototype, "_startColorVar", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new Color(0, 0, 0, 0);
              }
            }), _descriptor41 = _applyDecoratedDescriptor(_class2$1u.prototype, "_endColor", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new Color(255, 255, 255, 0);
              }
            }), _descriptor42 = _applyDecoratedDescriptor(_class2$1u.prototype, "_endColorVar", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return new Color(0, 0, 0, 0);
              }
            }), _descriptor43 = _applyDecoratedDescriptor(_class2$1u.prototype, "_positionType", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return PositionType.FREE;
              }
            })), _class2$1u)) || _class$1H) || _class$1H) || _class$1H) || _class$1H));

            var _dec$1H, _dec2$1d, _dec3$U, _dec4$N, _class$1I, _class2$1v, _descriptor$1k, _descriptor2$12, _descriptor3$N, _descriptor4$G, _descriptor5$y, _descriptor6$p, _class3$B, _temp$1z;

            var Point$1 = function () {
              function Point(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);
              }

              var _proto = Point.prototype;

              _proto.setPoint = function setPoint(x, y) {
                this.point.x = x;
                this.point.y = y;
              };

              _proto.setDir = function setDir(x, y) {
                this.dir.x = x;
                this.dir.y = y;
              };

              return Point;
            }();

            var MotionStreak = exports('MotionStreak', (_dec$1H = ccclass('cc.MotionStreak'), _dec2$1d = menu(), _dec3$U = help(), _dec4$N = type(Texture2D), _dec$1H(_class$1I = executeInEditMode(_class$1I = playOnFocus(_class$1I = _dec2$1d(_class$1I = _dec3$U(_class$1I = (_class2$1v = (_temp$1z = _class3$B = function (_Renderable2D) {
              _inheritsLoose(MotionStreak, _Renderable2D);

              function MotionStreak() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Renderable2D.call.apply(_Renderable2D, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "_preview", _descriptor$1k, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_fadeTime", _descriptor2$12, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_minSeg", _descriptor3$N, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_stroke", _descriptor4$G, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_texture", _descriptor5$y, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_fastMode", _descriptor6$p, _assertThisInitialized(_this));

                _this._points = [];
                return _this;
              }

              var _proto2 = MotionStreak.prototype;

              _proto2.onEnable = function onEnable() {
                _Renderable2D.prototype.onEnable.call(this);

                this.reset();
              };

              _proto2._flushAssembler = function _flushAssembler() {
                var 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;
                  }
                }
              };

              _proto2.onFocusInEditor = function onFocusInEditor() {
                if (this._preview) {
                  this.reset();
                }
              };

              _proto2.onLostFocusInEditor = function onLostFocusInEditor() {
                if (this._preview) {
                  this.reset();
                }
              };

              _proto2.reset = function reset() {
                this._points.length = 0;
                if (this._renderData) this._renderData.clear();
              };

              _proto2.lateUpdate = function lateUpdate(dt) {
                if (this._assembler) this._assembler.update(this, dt);
              };

              _proto2._render = function _render(render) {
                render.commitComp(this, this._texture, this._assembler, null);
              };

              _createClass(MotionStreak, [{
                key: "preview",
                get: function get() {
                  return this._preview;
                },
                set: function set(val) {
                  this._preview = val;
                  this.reset();
                }
              }, {
                key: "fadeTime",
                get: function get() {
                  return this._fadeTime;
                },
                set: function set(val) {
                  this._fadeTime = val;
                  this.reset();
                }
              }, {
                key: "minSeg",
                get: function get() {
                  return this._minSeg;
                },
                set: function set(val) {
                  this._minSeg = val;
                }
              }, {
                key: "stroke",
                get: function get() {
                  return this._stroke;
                },
                set: function set(val) {
                  this._stroke = val;
                }
              }, {
                key: "texture",
                get: function get() {
                  return this._texture;
                },
                set: function set(val) {
                  if (this._texture === val) return;
                  this._texture = val;
                }
              }, {
                key: "fastMode",
                get: function get() {
                  return this._fastMode;
                },
                set: function set(val) {
                  this._fastMode = val;
                }
              }, {
                key: "points",
                get: function get() {
                  return this._points;
                }
              }]);

              return MotionStreak;
            }(Renderable2D), _class3$B.Point = Point$1, _temp$1z), (_applyDecoratedDescriptor(_class2$1v.prototype, "preview", [editable], Object.getOwnPropertyDescriptor(_class2$1v.prototype, "preview"), _class2$1v.prototype), _applyDecoratedDescriptor(_class2$1v.prototype, "fadeTime", [editable], Object.getOwnPropertyDescriptor(_class2$1v.prototype, "fadeTime"), _class2$1v.prototype), _applyDecoratedDescriptor(_class2$1v.prototype, "minSeg", [editable], Object.getOwnPropertyDescriptor(_class2$1v.prototype, "minSeg"), _class2$1v.prototype), _applyDecoratedDescriptor(_class2$1v.prototype, "stroke", [editable], Object.getOwnPropertyDescriptor(_class2$1v.prototype, "stroke"), _class2$1v.prototype), _applyDecoratedDescriptor(_class2$1v.prototype, "texture", [_dec4$N], Object.getOwnPropertyDescriptor(_class2$1v.prototype, "texture"), _class2$1v.prototype), _applyDecoratedDescriptor(_class2$1v.prototype, "fastMode", [editable], Object.getOwnPropertyDescriptor(_class2$1v.prototype, "fastMode"), _class2$1v.prototype), _descriptor$1k = _applyDecoratedDescriptor(_class2$1v.prototype, "_preview", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor2$12 = _applyDecoratedDescriptor(_class2$1v.prototype, "_fadeTime", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1;
              }
            }), _descriptor3$N = _applyDecoratedDescriptor(_class2$1v.prototype, "_minSeg", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1;
              }
            }), _descriptor4$G = _applyDecoratedDescriptor(_class2$1v.prototype, "_stroke", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 64;
              }
            }), _descriptor5$y = _applyDecoratedDescriptor(_class2$1v.prototype, "_texture", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor6$p = _applyDecoratedDescriptor(_class2$1v.prototype, "_fastMode", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            })), _class2$1v)) || _class$1I) || _class$1I) || _class$1I) || _class$1I) || _class$1I));

            var _tangent = new Vec2();

            var _normal = new Vec2();

            var _vec2$3 = new Vec2();

            function normal(out, dir) {
              out.x = -dir.y;
              out.y = dir.x;
              return out;
            }

            var MotionStreakAssembler = {
              createData: function createData(comp) {
                var renderData = comp.requestRenderData();
                renderData.dataLength = 4;
                renderData.vertexCount = 16;
                renderData.indicesCount = (16 - 2) * 3;
                return renderData;
              },
              update: function update(comp, dt) {
                var stroke = comp.stroke / 2;
                var node = comp.node;
                var matrix = node.worldMatrix;
                var tx = matrix.m12;
                var ty = matrix.m13;
                var points = comp.points;
                var cur;

                if (points.length > 1) {
                  var point = points[0];
                  var difx = point.point.x - tx;
                  var dify = point.point.y - ty;

                  if (difx * difx + dify * dify < comp.minSeg) {
                    cur = point;
                  }
                }

                if (!cur) {
                  cur = new MotionStreak.Point();
                  points.splice(0, 0, cur);
                }

                cur.setPoint(tx, ty);
                cur.time = comp.fadeTime + dt;
                var verticesCount = 0;
                var indicesCount = 0;

                if (points.length < 2) {
                  return;
                }

                var renderData = comp.renderData;
                var color = comp.color;
                var cr = color.r;
                var cg = color.g;
                var cb = color.b;
                var ca = color.a;
                var prev = points[1];
                prev.distance = Vec2.subtract(_vec2$3, cur.point, prev.point).length();

                _vec2$3.normalize();

                prev.setDir(_vec2$3.x, _vec2$3.y);
                cur.setDir(_vec2$3.x, _vec2$3.y);
                renderData.dataLength = points.length * 2;
                var data = renderData.data;
                var fadeTime = comp.fadeTime;
                var findLast = false;

                for (var i = points.length - 1; i >= 0; i--) {
                  var p = points[i];
                  var _point = p.point;
                  var dir = p.dir;
                  p.time -= dt;

                  if (p.time < 0) {
                    points.splice(i, 1);
                    continue;
                  }

                  var progress = p.time / fadeTime;
                  var 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);
                  var da = progress * ca;
                  var c = (da << 24 >>> 0) + (cb << 16) + (cg << 8) + cr;
                  var offset = verticesCount;
                  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._val = c;
                  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._val = c;
                  verticesCount += 2;
                }

                indicesCount = verticesCount <= 2 ? 0 : (verticesCount - 2) * 3;
                renderData.vertexCount = verticesCount;
                renderData.indicesCount = indicesCount;
              },
              updateRenderData: function updateRenderData(comp) {},
              fillBuffers: function fillBuffers(comp, renderer) {
                var renderData = comp.renderData;
                var dataList = renderData.data;
                var node = comp.node;
                var buffer = renderer.acquireBufferBatch();
                var vertexOffset = buffer.byteOffset >> 2;
                var indicesOffset = buffer.indicesOffset;
                var vertexId = buffer.vertexOffset;
                var isRecreate = buffer.request(renderData.vertexCount, renderData.indicesCount);

                if (!isRecreate) {
                  buffer = renderer.currBufferBatch;
                  indicesOffset = 0;
                  vertexId = 0;
                }

                var vBuf = buffer.vData;
                var iBuf = buffer.iData;
                var vertexCount = renderData.vertexCount;
                var indicesCount = renderData.indicesCount;

                for (var i = 0; i < vertexCount; i++) {
                  var vert = dataList[i];
                  vBuf[vertexOffset++] = vert.x;
                  vBuf[vertexOffset++] = vert.y;
                  vBuf[vertexOffset++] = vert.z;
                  vBuf[vertexOffset++] = vert.u;
                  vBuf[vertexOffset++] = vert.v;
                  Color.toArray(vBuf, vert.color, vertexOffset);
                  vertexOffset += 4;
                }

                for (var _i = 0, l = indicesCount; _i < l; _i += 2) {
                  var start = vertexId + _i;
                  iBuf[indicesOffset++] = start;
                  iBuf[indicesOffset++] = start + 2;
                  iBuf[indicesOffset++] = start + 1;
                  iBuf[indicesOffset++] = start + 1;
                  iBuf[indicesOffset++] = start + 2;
                  iBuf[indicesOffset++] = start + 3;
                }
              }
            };
            var MotionStreakAssemblerManager = exports('MotionStreakAssemblerManager', {
              getAssembler: function getAssembler(comp) {
                return MotionStreakAssembler;
              }
            });
            MotionStreak.Assembler = MotionStreakAssemblerManager;

            var ParticleAssembler = {
              maxParticleDeltaTime: 0,
              createData: function createData(comp) {
                return MeshRenderData.add();
              },
              updateRenderData: function updateRenderData() {},
              fillBuffers: function fillBuffers(comp, renderer) {
                if (comp === null) {
                  return;
                }

                var renderData = comp._simulator.renderData;

                if (renderData.vertexCount === 0 || renderData.indicesCount === 0) {
                  return;
                }

                var buffer = renderer.acquireBufferBatch();
                var vertexOffset = buffer.byteOffset >> 2;
                var indicesOffset = buffer.indicesOffset;
                var vertexId = buffer.vertexOffset;
                var isRecreate = buffer.request(renderData.vertexCount, renderData.indicesCount);

                if (!isRecreate) {
                  buffer = renderer.currBufferBatch;
                  indicesOffset = 0;
                  vertexId = 0;
                }

                var vBuf = buffer.vData;
                var iBuf = buffer.iData;
                var vData = renderData.vData;
                var iData = renderData.iData;
                var vLen = renderData.vertexCount * 9;

                for (var i = 0; i < vLen; i++) {
                  vBuf[vertexOffset++] = vData[i];
                }

                var iLen = renderData.indicesCount;

                for (var _i = 0; _i < iLen; _i++) {
                  iBuf[indicesOffset++] = iData[_i] + vertexId;
                }
              }
            };
            var ParticleSystem2DAssembler = exports('ParticleSystem2DAssembler', {
              getAssembler: function getAssembler(comp) {
                if (!ParticleAssembler.maxParticleDeltaTime) {
                  ParticleAssembler.maxParticleDeltaTime = legacyCC.game.frameTime / 1000 * 2;
                }

                return ParticleAssembler;
              }
            });
            ParticleSystem2D.Assembler = ParticleSystem2DAssembler;

            var AudioEvent;

            (function (AudioEvent) {
              AudioEvent["PLAYED"] = "play";
              AudioEvent["PAUSED"] = "pause";
              AudioEvent["STOPPED"] = "stop";
              AudioEvent["SEEKED"] = "seeked";
              AudioEvent["ENDED"] = "ended";
              AudioEvent["INTERRUPTION_BEGIN"] = "interruptionBegin";
              AudioEvent["INTERRUPTION_END"] = "interruptionEnd";
              AudioEvent["USER_GESTURE"] = "on_gesture";
            })(AudioEvent || (AudioEvent = {}));

            var AudioType;

            (function (AudioType) {
              AudioType[AudioType["DOM_AUDIO"] = 0] = "DOM_AUDIO";
              AudioType[AudioType["WEB_AUDIO"] = 1] = "WEB_AUDIO";
              AudioType[AudioType["MINIGAME_AUDIO"] = 2] = "MINIGAME_AUDIO";
              AudioType[AudioType["NATIVE_AUDIO"] = 3] = "NATIVE_AUDIO";
              AudioType[AudioType["UNKNOWN_AUDIO"] = 4] = "UNKNOWN_AUDIO";
            })(AudioType || (AudioType = {}));

            var AudioState;

            (function (AudioState) {
              AudioState[AudioState["INIT"] = 0] = "INIT";
              AudioState[AudioState["PLAYING"] = 1] = "PLAYING";
              AudioState[AudioState["PAUSED"] = 2] = "PAUSED";
              AudioState[AudioState["STOPPED"] = 3] = "STOPPED";
              AudioState[AudioState["INTERRUPTED"] = 4] = "INTERRUPTED";
            })(AudioState || (AudioState = {}));

            var operationId = 0;

            function _tryCallingRecursively(target, opInfo) {
              var _opInfo$func;

              if (opInfo.invoking) {
                return;
              }

              opInfo.invoking = true;

              (_opInfo$func = opInfo.func).call.apply(_opInfo$func, [target].concat(opInfo.args)).then(function () {
                opInfo.invoking = false;

                target._operationQueue.shift();

                target._eventTarget.emit(opInfo.id.toString());

                var nextOpInfo = target._operationQueue[0];
                nextOpInfo && _tryCallingRecursively(target, nextOpInfo);
              })["catch"](function (e) {});
            }

            function enqueueOperation(target, propertyKey, descriptor) {
              var originalOperation = descriptor.value;

              descriptor.value = function () {
                var _this = this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                return new Promise(function (resolve) {
                  var id = operationId++;
                  var instance = _this;

                  instance._operationQueue.push({
                    id: id,
                    func: originalOperation,
                    args: args,
                    invoking: false
                  });

                  instance._eventTarget.once(id.toString(), resolve);

                  var opInfo = instance._operationQueue[0];

                  _tryCallingRecursively(instance, opInfo);
                });
              };
            }

            var _class$1J, _temp$1A;

            function ensurePlaying(domAudio) {
              return new Promise(function (resolve) {
                var promise = domAudio.play();

                if (promise === undefined) {
                  return resolve();
                }

                promise.then(resolve)["catch"](function () {
                  var onGesture = function onGesture() {
                    domAudio.play()["catch"](function (e) {});
                    resolve();
                  };

                  var canvas = document.getElementById('GameCanvas');
                  canvas === null || canvas === void 0 ? void 0 : canvas.addEventListener('touchend', onGesture, {
                    once: true
                  });
                  canvas === null || canvas === void 0 ? void 0 : canvas.addEventListener('mousedown', onGesture, {
                    once: true
                  });
                });
                return null;
              });
            }

            var OneShotAudioDOM = function () {
              function OneShotAudioDOM(nativeAudio, volume) {
                this._domAudio = void 0;
                this._onPlayCb = void 0;
                this._onEndCb = void 0;
                this._domAudio = nativeAudio;
                nativeAudio.volume = volume;
              }

              var _proto = OneShotAudioDOM.prototype;

              _proto.play = function play() {
                var _this = this;

                ensurePlaying(this._domAudio).then(function () {
                  var _this$onPlay;

                  (_this$onPlay = _this.onPlay) === null || _this$onPlay === void 0 ? void 0 : _this$onPlay.call(_this);
                })["catch"](function (e) {});
              };

              _proto.stop = function stop() {
                this._domAudio.pause();
              };

              _createClass(OneShotAudioDOM, [{
                key: "onPlay",
                get: function get() {
                  return this._onPlayCb;
                },
                set: function set(cb) {
                  this._onPlayCb = cb;
                }
              }, {
                key: "onEnd",
                get: function get() {
                  return this._onEndCb;
                },
                set: function set(cb) {
                  if (this._onEndCb) {
                    this._domAudio.removeEventListener('ended', this._onEndCb);
                  }

                  this._onEndCb = cb;

                  if (cb) {
                    this._domAudio.addEventListener('ended', cb);
                  }
                }
              }]);

              return OneShotAudioDOM;
            }();
            var AudioPlayerDOM = (_class$1J = (_temp$1A = function () {
              function AudioPlayerDOM(nativeAudio) {
                var _this2 = this;

                this._domAudio = void 0;
                this._state = AudioState.INIT;
                this._onHide = void 0;
                this._onShow = void 0;
                this._onEnded = void 0;
                this._eventTarget = new EventTarget();
                this._operationQueue = [];
                this._domAudio = nativeAudio;

                this._onHide = function () {
                  if (_this2._state === AudioState.PLAYING) {
                    _this2.pause().then(function () {
                      _this2._state = AudioState.INTERRUPTED;

                      _this2._eventTarget.emit(AudioEvent.INTERRUPTION_BEGIN);
                    })["catch"](function (e) {});
                  }
                };

                legacyCC.game.on(legacyCC.Game.EVENT_HIDE, this._onHide);

                this._onShow = function () {
                  if (_this2._state === AudioState.INTERRUPTED) {
                    _this2.play().then(function () {
                      _this2._eventTarget.emit(AudioEvent.INTERRUPTION_END);
                    })["catch"](function (e) {});
                  }
                };

                legacyCC.game.on(legacyCC.Game.EVENT_SHOW, this._onShow);

                this._onEnded = function () {
                  _this2.seek(0)["catch"](function (e) {});

                  _this2._state = AudioState.INIT;

                  _this2._eventTarget.emit(AudioEvent.ENDED);
                };

                this._domAudio.addEventListener('ended', this._onEnded);
              }

              var _proto2 = AudioPlayerDOM.prototype;

              _proto2.destroy = function destroy() {
                if (this._onShow) {
                  legacyCC.game.off(legacyCC.Game.EVENT_SHOW, this._onShow);
                  this._onShow = undefined;
                }

                if (this._onHide) {
                  legacyCC.game.off(legacyCC.Game.EVENT_HIDE, this._onHide);
                  this._onHide = undefined;
                }

                if (this._onEnded) {
                  this._domAudio.removeEventListener('ended', this._onEnded);

                  this._onEnded = undefined;
                }

                this._domAudio = undefined;
              };

              AudioPlayerDOM.load = function load(url) {
                return new Promise(function (resolve) {
                  AudioPlayerDOM.loadNative(url).then(function (domAudio) {
                    resolve(new AudioPlayerDOM(domAudio));
                  })["catch"](function (e) {});
                });
              };

              AudioPlayerDOM.loadNative = function loadNative(url) {
                return new Promise(function (resolve, reject) {
                  var domAudio = document.createElement('audio');
                  var loadedEvent = 'canplaythrough';

                  if (system.os === OS.IOS) {
                    loadedEvent = 'loadedmetadata';
                  } else if (system.browserType === BrowserType.FIREFOX) {
                    loadedEvent = 'canplay';
                  }

                  var timer = setTimeout(function () {
                    if (domAudio.readyState === 0) {
                      failure();
                    } else {
                      success();
                    }
                  }, 8000);

                  var clearEvent = function clearEvent() {
                    clearTimeout(timer);
                    domAudio.removeEventListener(loadedEvent, success, false);
                    domAudio.removeEventListener('error', failure, false);
                  };

                  var success = function success() {
                    clearEvent();
                    resolve(domAudio);
                  };

                  var failure = function failure() {
                    clearEvent();
                    var message = "load audio failure - " + url;
                    reject(message);
                  };

                  domAudio.addEventListener(loadedEvent, success, false);
                  domAudio.addEventListener('error', failure, false);
                  domAudio.src = url;
                });
              };

              AudioPlayerDOM.loadOneShotAudio = function loadOneShotAudio(url, volume) {
                return new Promise(function (resolve, reject) {
                  AudioPlayerDOM.loadNative(url).then(function (domAudio) {
                    var oneShotAudio = new OneShotAudioDOM(domAudio, volume);
                    resolve(oneShotAudio);
                  })["catch"](reject);
                });
              };

              _proto2.seek = function seek(time) {
                time = clamp(time, 0, this.duration);
                this._domAudio.currentTime = time;
                return Promise.resolve();
              };

              _proto2.play = function play() {
                var _this3 = this;

                return new Promise(function (resolve) {
                  ensurePlaying(_this3._domAudio).then(function () {
                    _this3._state = AudioState.PLAYING;
                    resolve();
                  })["catch"](function (e) {});
                });
              };

              _proto2.pause = function pause() {
                this._domAudio.pause();

                this._state = AudioState.PAUSED;
                return Promise.resolve();
              };

              _proto2.stop = function stop() {
                var _this4 = this;

                return new Promise(function (resolve) {
                  _this4._domAudio.pause();

                  _this4._domAudio.currentTime = 0;
                  _this4._state = AudioState.STOPPED;
                  resolve();
                });
              };

              _proto2.onInterruptionBegin = function onInterruptionBegin(cb) {
                this._eventTarget.on(AudioEvent.INTERRUPTION_BEGIN, cb);
              };

              _proto2.offInterruptionBegin = function offInterruptionBegin(cb) {
                this._eventTarget.off(AudioEvent.INTERRUPTION_BEGIN, cb);
              };

              _proto2.onInterruptionEnd = function onInterruptionEnd(cb) {
                this._eventTarget.on(AudioEvent.INTERRUPTION_END, cb);
              };

              _proto2.offInterruptionEnd = function offInterruptionEnd(cb) {
                this._eventTarget.off(AudioEvent.INTERRUPTION_END, cb);
              };

              _proto2.onEnded = function onEnded(cb) {
                this._eventTarget.on(AudioEvent.ENDED, cb);
              };

              _proto2.offEnded = function offEnded(cb) {
                this._eventTarget.off(AudioEvent.ENDED, cb);
              };

              _createClass(AudioPlayerDOM, [{
                key: "src",
                get: function get() {
                  return this._domAudio ? this._domAudio.src : '';
                }
              }, {
                key: "type",
                get: function get() {
                  return AudioType.DOM_AUDIO;
                }
              }, {
                key: "state",
                get: function get() {
                  return this._state;
                }
              }, {
                key: "loop",
                get: function get() {
                  return this._domAudio.loop;
                },
                set: function set(val) {
                  this._domAudio.loop = val;
                }
              }, {
                key: "volume",
                get: function get() {
                  return this._domAudio.volume;
                },
                set: function set(val) {
                  val = clamp01(val);
                  this._domAudio.volume = val;
                }
              }, {
                key: "duration",
                get: function get() {
                  return this._domAudio.duration;
                }
              }, {
                key: "currentTime",
                get: function get() {
                  return this._domAudio.currentTime;
                }
              }]);

              return AudioPlayerDOM;
            }(), _temp$1A), (_applyDecoratedDescriptor(_class$1J.prototype, "seek", [enqueueOperation], Object.getOwnPropertyDescriptor(_class$1J.prototype, "seek"), _class$1J.prototype), _applyDecoratedDescriptor(_class$1J.prototype, "play", [enqueueOperation], Object.getOwnPropertyDescriptor(_class$1J.prototype, "play"), _class$1J.prototype), _applyDecoratedDescriptor(_class$1J.prototype, "pause", [enqueueOperation], Object.getOwnPropertyDescriptor(_class$1J.prototype, "pause"), _class$1J.prototype), _applyDecoratedDescriptor(_class$1J.prototype, "stop", [enqueueOperation], Object.getOwnPropertyDescriptor(_class$1J.prototype, "stop"), _class$1J.prototype)), _class$1J);

            var _class$1K, _temp$1B;
            var AudioContextClass = window.AudioContext || window.webkitAudioContext || window.mozAudioContext;
            var AudioContextAgent = function () {
              function AudioContextAgent() {
                this._context = void 0;
                this._context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)();
              }

              var _proto = AudioContextAgent.prototype;

              _proto.decodeAudioData = function decodeAudioData(audioData) {
                var _this = this;

                return new Promise(function (resolve) {
                  var promise = _this._context.decodeAudioData(audioData, function (audioBuffer) {
                    resolve(audioBuffer);
                  }, function (err) {
                    console.error('failed to load Web Audio', err);
                  });

                  promise === null || promise === void 0 ? void 0 : promise["catch"](function (e) {});
                });
              };

              _proto.runContext = function runContext() {
                var _this2 = this;

                return new Promise(function (resolve) {
                  var context = _this2._context;

                  if (!context.resume) {
                    return resolve();
                  }

                  if (context.state === 'running') {
                    return resolve();
                  }

                  context.resume()["catch"](function (e) {});

                  if (context.state !== 'running') {
                    var canvas = document.getElementById('GameCanvas');

                    var onGesture = function onGesture() {
                      context.resume().then(resolve)["catch"](function (e) {});
                    };

                    canvas === null || canvas === void 0 ? void 0 : canvas.addEventListener('touchend', onGesture, {
                      once: true
                    });
                    canvas === null || canvas === void 0 ? void 0 : canvas.addEventListener('mousedown', onGesture, {
                      once: true
                    });
                  }

                  return null;
                });
              };

              _proto.createBufferSource = function createBufferSource(audioBuffer, loop) {
                var sourceBufferNode = this._context.createBufferSource();

                if (audioBuffer !== undefined) {
                  sourceBufferNode.buffer = audioBuffer;
                }

                if (loop !== undefined) {
                  sourceBufferNode.loop = loop;
                }

                return sourceBufferNode;
              };

              _proto.createGain = function createGain(volume) {
                if (volume === void 0) {
                  volume = 1;
                }

                var gainNode = this._context.createGain();

                this.setGainValue(gainNode, volume);
                return gainNode;
              };

              _proto.setGainValue = function setGainValue(gain, volume) {
                if (gain.gain.setTargetAtTime) {
                  try {
                    gain.gain.setTargetAtTime(volume, this._context.currentTime, 0);
                  } catch (e) {
                    gain.gain.setTargetAtTime(volume, this._context.currentTime, 0.01);
                  }
                } else {
                  gain.gain.value = volume;
                }
              };

              _proto.connectContext = function connectContext(audioNode) {
                if (!this._context) {
                  return;
                }

                audioNode.connect(this._context.destination);
              };

              _createClass(AudioContextAgent, [{
                key: "currentTime",
                get: function get() {
                  return this._context.currentTime;
                }
              }]);

              return AudioContextAgent;
            }();
            AudioContextAgent.support = !!AudioContextClass;
            var audioContextAgent;

            if (AudioContextAgent.support) {
              audioContextAgent = new AudioContextAgent();
            }

            var OneShotAudioWeb = function () {
              function OneShotAudioWeb(audioBuffer, volume) {
                this._duration = void 0;
                this._bufferSourceNode = void 0;
                this._onPlayCb = void 0;
                this._onEndCb = void 0;
                this._duration = audioBuffer.duration;
                this._bufferSourceNode = audioContextAgent.createBufferSource(audioBuffer, false);
                var gainNode = audioContextAgent.createGain(volume);

                this._bufferSourceNode.connect(gainNode);

                audioContextAgent.connectContext(gainNode);
              }

              var _proto2 = OneShotAudioWeb.prototype;

              _proto2.play = function play() {
                var _this3 = this;

                audioContextAgent.runContext().then(function () {
                  var _this3$onPlay;

                  _this3._bufferSourceNode.start();

                  (_this3$onPlay = _this3.onPlay) === null || _this3$onPlay === void 0 ? void 0 : _this3$onPlay.call(_this3);
                  window.setTimeout(function () {
                    var _this3$onEnd;

                    (_this3$onEnd = _this3.onEnd) === null || _this3$onEnd === void 0 ? void 0 : _this3$onEnd.call(_this3);
                  }, _this3._duration * 1000);
                })["catch"](function (e) {});
              };

              _proto2.stop = function stop() {
                this._bufferSourceNode.stop();
              };

              _createClass(OneShotAudioWeb, [{
                key: "onPlay",
                get: function get() {
                  return this._onPlayCb;
                },
                set: function set(cb) {
                  this._onPlayCb = cb;
                }
              }, {
                key: "onEnd",
                get: function get() {
                  return this._onEndCb;
                },
                set: function set(cb) {
                  this._onEndCb = cb;
                }
              }]);

              return OneShotAudioWeb;
            }();
            var AudioPlayerWeb = (_class$1K = (_temp$1B = function () {
              function AudioPlayerWeb(audioBuffer, url) {
                var _this4 = this;

                this._src = void 0;
                this._audioBuffer = void 0;
                this._sourceNode = void 0;
                this._gainNode = void 0;
                this._currentTimer = 0;
                this._volume = 1;
                this._loop = false;
                this._startTime = 0;
                this._playTimeOffset = 0;
                this._state = AudioState.INIT;
                this._eventTarget = new EventTarget();
                this._operationQueue = [];
                this._onHide = void 0;
                this._onShow = void 0;
                this._audioBuffer = audioBuffer;
                this._gainNode = audioContextAgent.createGain();
                audioContextAgent.connectContext(this._gainNode);
                this._src = url;

                this._onHide = function () {
                  if (_this4._state === AudioState.PLAYING) {
                    _this4.pause().then(function () {
                      _this4._state = AudioState.INTERRUPTED;

                      _this4._eventTarget.emit(AudioEvent.INTERRUPTION_BEGIN);
                    })["catch"](function (e) {});
                  }
                };

                legacyCC.game.on(legacyCC.Game.EVENT_HIDE, this._onHide);

                this._onShow = function () {
                  if (_this4._state === AudioState.INTERRUPTED) {
                    _this4.play().then(function () {
                      _this4._eventTarget.emit(AudioEvent.INTERRUPTION_END);
                    })["catch"](function (e) {});
                  }
                };

                legacyCC.game.on(legacyCC.Game.EVENT_SHOW, this._onShow);
              }

              var _proto3 = AudioPlayerWeb.prototype;

              _proto3.destroy = function destroy() {
                if (this._audioBuffer) {
                  this._audioBuffer = undefined;
                }

                if (this._onShow) {
                  legacyCC.game.off(legacyCC.Game.EVENT_SHOW, this._onShow);
                  this._onShow = undefined;
                }

                if (this._onHide) {
                  legacyCC.game.off(legacyCC.Game.EVENT_HIDE, this._onHide);
                  this._onHide = undefined;
                }
              };

              AudioPlayerWeb.load = function load(url) {
                return new Promise(function (resolve) {
                  AudioPlayerWeb.loadNative(url).then(function (audioBuffer) {
                    resolve(new AudioPlayerWeb(audioBuffer, url));
                  })["catch"](function (e) {});
                });
              };

              AudioPlayerWeb.loadNative = function loadNative(url) {
                return new Promise(function (resolve, reject) {
                  var xhr = new XMLHttpRequest();
                  var errInfo = "load audio failed: " + url + ", status: ";
                  xhr.open('GET', url, true);
                  xhr.responseType = 'arraybuffer';

                  xhr.onload = function () {
                    if (xhr.status === 200 || xhr.status === 0) {
                      audioContextAgent.decodeAudioData(xhr.response).then(function (buffer) {
                        resolve(buffer);
                      })["catch"](function (e) {});
                    } else {
                      reject(new Error("" + errInfo + xhr.status + "(no response)"));
                    }
                  };

                  xhr.onerror = function () {
                    reject(new Error("" + errInfo + xhr.status + "(error)"));
                  };

                  xhr.ontimeout = function () {
                    reject(new Error("" + errInfo + xhr.status + "(time out)"));
                  };

                  xhr.onabort = function () {
                    reject(new Error("" + errInfo + xhr.status + "(abort)"));
                  };

                  xhr.send(null);
                });
              };

              AudioPlayerWeb.loadOneShotAudio = function loadOneShotAudio(url, volume) {
                return new Promise(function (resolve, reject) {
                  AudioPlayerWeb.loadNative(url).then(function (audioBuffer) {
                    var oneShotAudio = new OneShotAudioWeb(audioBuffer, volume);
                    resolve(oneShotAudio);
                  })["catch"](reject);
                });
              };

              _proto3.seek = function seek(time) {
                var _this5 = this;

                return new Promise(function (resolve) {
                  _this5._playTimeOffset = clamp(time, 0, _this5._audioBuffer.duration);

                  if (_this5._state === AudioState.PLAYING) {
                    _this5._doPlay().then(resolve)["catch"](function (e) {});
                  } else {
                    resolve();
                  }
                });
              };

              _proto3.play = function play() {

                return this._doPlay();
              };

              _proto3._doPlay = function _doPlay() {
                var _this6 = this;

                return new Promise(function (resolve) {
                  audioContextAgent.runContext().then(function () {
                    _this6._stopSourceNode();

                    _this6._sourceNode = audioContextAgent.createBufferSource(_this6._audioBuffer, _this6.loop);

                    _this6._sourceNode.connect(_this6._gainNode);

                    _this6._sourceNode.start(0, _this6._playTimeOffset);

                    _this6._state = AudioState.PLAYING;
                    _this6._startTime = audioContextAgent.currentTime;

                    var checkEnded = function checkEnded() {
                      _this6._playTimeOffset = 0;
                      _this6._startTime = audioContextAgent.currentTime;

                      if (_this6.loop) {
                        _this6._currentTimer = window.setTimeout(checkEnded, _this6._audioBuffer.duration * 1000);
                      } else {
                        _this6._eventTarget.emit(AudioEvent.ENDED);

                        _this6._state = AudioState.INIT;
                      }
                    };

                    window.clearTimeout(_this6._currentTimer);
                    _this6._currentTimer = window.setTimeout(checkEnded, (_this6._audioBuffer.duration - _this6._playTimeOffset) * 1000);
                    resolve();
                  })["catch"](function (e) {});
                });
              };

              _proto3._stopSourceNode = function _stopSourceNode() {
                try {
                  var _this$_sourceNode;

                  (_this$_sourceNode = this._sourceNode) === null || _this$_sourceNode === void 0 ? void 0 : _this$_sourceNode.stop();
                } catch (e) {}
              };

              _proto3.pause = function pause() {
                if (this._state !== AudioState.PLAYING || !this._sourceNode) {
                  return Promise.resolve();
                }

                this._playTimeOffset = (audioContextAgent.currentTime - this._startTime + this._playTimeOffset) % this._audioBuffer.duration;
                this._state = AudioState.PAUSED;
                window.clearTimeout(this._currentTimer);

                this._stopSourceNode();

                return Promise.resolve();
              };

              _proto3.stop = function stop() {
                if (!this._sourceNode) {
                  return Promise.resolve();
                }

                this._playTimeOffset = 0;
                this._state = AudioState.STOPPED;
                window.clearTimeout(this._currentTimer);

                this._stopSourceNode();

                return Promise.resolve();
              };

              _proto3.onInterruptionBegin = function onInterruptionBegin(cb) {
                this._eventTarget.on(AudioEvent.INTERRUPTION_BEGIN, cb);
              };

              _proto3.offInterruptionBegin = function offInterruptionBegin(cb) {
                this._eventTarget.off(AudioEvent.INTERRUPTION_BEGIN, cb);
              };

              _proto3.onInterruptionEnd = function onInterruptionEnd(cb) {
                this._eventTarget.on(AudioEvent.INTERRUPTION_END, cb);
              };

              _proto3.offInterruptionEnd = function offInterruptionEnd(cb) {
                this._eventTarget.off(AudioEvent.INTERRUPTION_END, cb);
              };

              _proto3.onEnded = function onEnded(cb) {
                this._eventTarget.on(AudioEvent.ENDED, cb);
              };

              _proto3.offEnded = function offEnded(cb) {
                this._eventTarget.off(AudioEvent.ENDED, cb);
              };

              _createClass(AudioPlayerWeb, [{
                key: "src",
                get: function get() {
                  return this._src;
                }
              }, {
                key: "type",
                get: function get() {
                  return AudioType.WEB_AUDIO;
                }
              }, {
                key: "state",
                get: function get() {
                  return this._state;
                }
              }, {
                key: "loop",
                get: function get() {
                  return this._loop;
                },
                set: function set(val) {
                  this._loop = val;
                  this._sourceNode && (this._sourceNode.loop = val);
                }
              }, {
                key: "volume",
                get: function get() {
                  return this._volume;
                },
                set: function set(val) {
                  val = clamp01(val);
                  this._volume = val;
                  audioContextAgent.setGainValue(this._gainNode, val);
                }
              }, {
                key: "duration",
                get: function get() {
                  return this._audioBuffer.duration;
                }
              }, {
                key: "currentTime",
                get: function get() {
                  if (this._state !== AudioState.PLAYING) {
                    return this._playTimeOffset;
                  }

                  return (audioContextAgent.currentTime - this._startTime + this._playTimeOffset) % this._audioBuffer.duration;
                }
              }]);

              return AudioPlayerWeb;
            }(), _temp$1B), (_applyDecoratedDescriptor(_class$1K.prototype, "seek", [enqueueOperation], Object.getOwnPropertyDescriptor(_class$1K.prototype, "seek"), _class$1K.prototype), _applyDecoratedDescriptor(_class$1K.prototype, "play", [enqueueOperation], Object.getOwnPropertyDescriptor(_class$1K.prototype, "play"), _class$1K.prototype), _applyDecoratedDescriptor(_class$1K.prototype, "pause", [enqueueOperation], Object.getOwnPropertyDescriptor(_class$1K.prototype, "pause"), _class$1K.prototype), _applyDecoratedDescriptor(_class$1K.prototype, "stop", [enqueueOperation], Object.getOwnPropertyDescriptor(_class$1K.prototype, "stop"), _class$1K.prototype)), _class$1K);

            var OneShotAudio = function () {
              function OneShotAudio(audio) {
                this._audio = void 0;
                this._audio = audio;
              }

              var _proto = OneShotAudio.prototype;

              _proto.play = function play() {
                this._audio.play();
              };

              _proto.stop = function stop() {
                this._audio.stop();
              };

              _createClass(OneShotAudio, [{
                key: "onPlay",
                get: function get() {
                  return this._audio.onPlay;
                },
                set: function set(v) {
                  this._audio.onPlay = v;
                }
              }, {
                key: "onEnd",
                get: function get() {
                  return this._audio.onEnd;
                },
                set: function set(v) {
                  this._audio.onEnd = v;
                }
              }]);

              return OneShotAudio;
            }();
            var AudioPlayer = function () {
              function AudioPlayer(player) {
                this._player = void 0;
                this._player = player;
              }

              AudioPlayer.load = function load(url, opts) {
                return new Promise(function (resolve) {
                  if ((opts === null || opts === void 0 ? void 0 : opts.audioLoadMode) === AudioType.DOM_AUDIO || !AudioContextAgent.support) {
                    if (!AudioContextAgent.support) {
                      warnID(5201);
                    }

                    AudioPlayerDOM.load(url).then(function (domPlayer) {
                      resolve(new AudioPlayer(domPlayer));
                    })["catch"](function (e) {});
                  } else {
                    AudioPlayerWeb.load(url).then(function (webPlayer) {
                      resolve(new AudioPlayer(webPlayer));
                    })["catch"](function (e) {});
                  }
                });
              };

              var _proto2 = AudioPlayer.prototype;

              _proto2.destroy = function destroy() {
                this._player.destroy();
              };

              AudioPlayer.loadNative = function loadNative(url, opts) {
                if ((opts === null || opts === void 0 ? void 0 : opts.audioLoadMode) === AudioType.DOM_AUDIO || !AudioContextAgent.support) {
                  if (!AudioContextAgent.support) {
                    warnID(5201);
                  }

                  return AudioPlayerDOM.loadNative(url);
                }

                return AudioPlayerWeb.loadNative(url);
              };

              AudioPlayer.loadOneShotAudio = function loadOneShotAudio(url, volume, opts) {
                return new Promise(function (resolve, reject) {
                  if ((opts === null || opts === void 0 ? void 0 : opts.audioLoadMode) === AudioType.DOM_AUDIO || !AudioContextAgent.support) {
                    if (!AudioContextAgent.support) {
                      warnID(5201);
                    }

                    AudioPlayerDOM.loadOneShotAudio(url, volume).then(function (oneShotAudioDOM) {
                      resolve(new OneShotAudio(oneShotAudioDOM));
                    })["catch"](reject);
                  } else {
                    AudioPlayerWeb.loadOneShotAudio(url, volume).then(function (oneShotAudioWeb) {
                      resolve(new OneShotAudio(oneShotAudioWeb));
                    })["catch"](reject);
                  }
                });
              };

              _proto2.seek = function seek(time) {
                return this._player.seek(time);
              };

              _proto2.play = function play() {
                return this._player.play();
              };

              _proto2.pause = function pause() {
                return this._player.pause();
              };

              _proto2.stop = function stop() {
                return this._player.stop();
              };

              _proto2.onInterruptionBegin = function onInterruptionBegin(cb) {
                this._player.onInterruptionBegin(cb);
              };

              _proto2.offInterruptionBegin = function offInterruptionBegin(cb) {
                this._player.offInterruptionBegin(cb);
              };

              _proto2.onInterruptionEnd = function onInterruptionEnd(cb) {
                this._player.onInterruptionEnd(cb);
              };

              _proto2.offInterruptionEnd = function offInterruptionEnd(cb) {
                this._player.offInterruptionEnd(cb);
              };

              _proto2.onEnded = function onEnded(cb) {
                this._player.onEnded(cb);
              };

              _proto2.offEnded = function offEnded(cb) {
                this._player.offEnded(cb);
              };

              _createClass(AudioPlayer, [{
                key: "src",
                get: function get() {
                  return this._player.src;
                }
              }, {
                key: "type",
                get: function get() {
                  return this._player.type;
                }
              }, {
                key: "state",
                get: function get() {
                  return this._player.state;
                }
              }, {
                key: "loop",
                get: function get() {
                  return this._player.loop;
                },
                set: function set(val) {
                  this._player.loop = val;
                }
              }, {
                key: "volume",
                get: function get() {
                  return this._player.volume;
                },
                set: function set(val) {
                  this._player.volume = val;
                }
              }, {
                key: "duration",
                get: function get() {
                  return this._player.duration;
                }
              }, {
                key: "currentTime",
                get: function get() {
                  return this._player.currentTime;
                }
              }]);

              return AudioPlayer;
            }();
            AudioPlayer.maxAudioChannel = 24;

            var _dec$1I, _class$1L, _class2$1w, _descriptor$1l, _class3$C, _temp$1C;
            var AudioClip = exports('AudioClip', (_dec$1I = ccclass('cc.AudioClip'), _dec$1I(_class$1L = (_class2$1w = (_temp$1C = _class3$C = function (_Asset) {
              _inheritsLoose(AudioClip, _Asset);

              function AudioClip() {
                var _this;

                _this = _Asset.call(this) || this;

                _initializerDefineProperty(_this, "_duration", _descriptor$1l, _assertThisInitialized(_this));

                _this._loadMode = AudioType.UNKNOWN_AUDIO;
                _this._meta = null;
                _this._player = void 0;
                _this.loaded = false;
                return _this;
              }

              var _proto = AudioClip.prototype;

              _proto.destroy = function destroy() {
                var _this$_player;

                var destroyResult = _Asset.prototype.destroy.call(this);

                (_this$_player = this._player) === null || _this$_player === void 0 ? void 0 : _this$_player.destroy();
                return destroyResult;
              };

              _proto.validate = function validate() {
                return !!this._meta;
              };

              _proto.getDuration = function getDuration() {
                if (this._duration) {
                  return this._duration;
                }

                return this._meta ? this._meta.duration : 0;
              };

              _proto.getCurrentTime = function getCurrentTime() {
                return this._player ? this._player.currentTime : 0;
              };

              _proto.getVolume = function getVolume() {
                return this._player ? this._player.volume : 0;
              };

              _proto.getLoop = function getLoop() {
                return this._player ? this._player.loop : false;
              };

              _proto.setCurrentTime = function setCurrentTime(time) {
                var _this$_player2;

                (_this$_player2 = this._player) === null || _this$_player2 === void 0 ? void 0 : _this$_player2.seek(time)["catch"](function (e) {});
              };

              _proto.setVolume = function setVolume(volume) {
                if (this._player) {
                  this._player.volume = volume;
                }
              };

              _proto.setLoop = function setLoop(loop) {
                if (this._player) {
                  this._player.loop = loop;
                }
              };

              _proto.play = function play() {
                var _this$_player3;

                (_this$_player3 = this._player) === null || _this$_player3 === void 0 ? void 0 : _this$_player3.play()["catch"](function (e) {});
              };

              _proto.pause = function pause() {
                var _this$_player4;

                (_this$_player4 = this._player) === null || _this$_player4 === void 0 ? void 0 : _this$_player4.pause()["catch"](function (e) {});
              };

              _proto.stop = function stop() {
                var _this$_player5;

                (_this$_player5 = this._player) === null || _this$_player5 === void 0 ? void 0 : _this$_player5.stop()["catch"](function (e) {});
              };

              _proto.playOneShot = function playOneShot(volume) {
                if (volume === void 0) {
                  volume = 1;
                }

                if (this._nativeAsset) {
                  AudioPlayer.loadOneShotAudio(this._nativeAsset.url, volume).then(function (oneShotAudio) {
                    oneShotAudio.play();
                  })["catch"](function (e) {});
                }
              };

              _createClass(AudioClip, [{
                key: "_nativeAsset",
                get: function get() {
                  return this._meta;
                },
                set: function set(meta) {
                  this._meta = meta;

                  if (meta) {
                    this.loaded = true;
                    this._loadMode = meta.type;
                    this._player = meta.player;
                    this.emit('load');
                  } else {
                    this._meta = null;
                    this._loadMode = AudioType.UNKNOWN_AUDIO;
                    this._duration = 0;
                    this.loaded = false;
                  }
                }
              }, {
                key: "_nativeDep",
                get: function get() {
                  return {
                    uuid: this._uuid,
                    audioLoadMode: this.loadMode,
                    ext: this._native,
                    __isNative__: true
                  };
                }
              }, {
                key: "loadMode",
                get: function get() {
                  return this._loadMode;
                }
              }, {
                key: "state",
                get: function get() {
                  return this._player ? this._player.state : AudioState.INIT;
                }
              }]);

              return AudioClip;
            }(Asset), _class3$C.AudioType = AudioType, _temp$1C), (_descriptor$1l = _applyDecoratedDescriptor(_class2$1w.prototype, "_duration", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _applyDecoratedDescriptor(_class2$1w.prototype, "_nativeDep", [override], Object.getOwnPropertyDescriptor(_class2$1w.prototype, "_nativeDep"), _class2$1w.prototype)), _class2$1w)) || _class$1L));
            legacyCC.AudioClip = AudioClip;

            function loadAudioPlayer(url, options, onComplete) {
              AudioPlayer.load(url, {
                audioLoadMode: options.audioLoadMode
              }).then(function (player) {
                var audioMeta = {
                  player: player,
                  url: url,
                  duration: player.duration,
                  type: player.type
                };
                onComplete(null, audioMeta);
              })["catch"](function (err) {
                onComplete(err);
              });
            }

            function createAudioClip(id, data, options, onComplete) {
              var out = new AudioClip();
              out._nativeUrl = id;
              out._nativeAsset = data;
              out._duration = data.duration;
              onComplete(null, out);
            }

            downloader.register({
              '.mp3': loadAudioPlayer,
              '.ogg': loadAudioPlayer,
              '.wav': loadAudioPlayer,
              '.m4a': loadAudioPlayer
            });
            factory.register({
              '.mp3': createAudioClip,
              '.ogg': createAudioClip,
              '.wav': createAudioClip,
              '.m4a': createAudioClip
            });

            var AudioManager = function () {
              function AudioManager() {
                this._oneShotAudioInfoList = [];
                this._audioPlayerInfoList = [];
              }

              var _proto = AudioManager.prototype;

              _proto._findIndex = function _findIndex(audioInfoList, audio) {
                return audioInfoList.findIndex(function (item) {
                  return item.audio === audio;
                });
              };

              _proto._tryAddPlaying = function _tryAddPlaying(audioInfoList, audio) {
                var idx = this._findIndex(audioInfoList, audio);

                if (idx > -1) {
                  audioInfoList[idx].playTime = performance.now();
                  return false;
                }

                audioInfoList.push({
                  audio: audio,
                  playTime: performance.now()
                });
                return true;
              };

              _proto.addPlaying = function addPlaying(audio) {
                if (audio instanceof AudioPlayer) {
                  if (this._tryAddPlaying(this._audioPlayerInfoList, audio)) {
                    return;
                  }
                } else {
                  this._tryAddPlaying(this._oneShotAudioInfoList, audio);
                }
              };

              _proto._tryRemovePlaying = function _tryRemovePlaying(audioInfoList, audio) {
                var idx = this._findIndex(audioInfoList, audio);

                if (idx === -1) {
                  return false;
                }

                fastRemoveAt(audioInfoList, idx);
                return true;
              };

              _proto.removePlaying = function removePlaying(audio) {
                if (audio instanceof AudioPlayer) {
                  if (this._tryRemovePlaying(this._audioPlayerInfoList, audio)) {
                    return;
                  }
                } else {
                  this._tryRemovePlaying(this._oneShotAudioInfoList, audio);
                }
              };

              _proto.discardOnePlayingIfNeeded = function discardOnePlayingIfNeeded() {
                if (this._audioPlayerInfoList.length + this._oneShotAudioInfoList.length < AudioPlayer.maxAudioChannel) {
                  return;
                }

                var audioInfoToDiscard;

                if (this._oneShotAudioInfoList.length > 0) {
                  this._oneShotAudioInfoList.forEach(function (audioInfo) {
                    if (!audioInfoToDiscard || audioInfo.playTime < audioInfoToDiscard.playTime) {
                      audioInfoToDiscard = audioInfo;
                    }
                  });
                } else {
                  this._audioPlayerInfoList.forEach(function (audioInfo) {
                    if (!audioInfoToDiscard || audioInfo.playTime < audioInfoToDiscard.playTime) {
                      audioInfoToDiscard = audioInfo;
                    }
                  });
                }

                if (audioInfoToDiscard) {
                  audioInfoToDiscard.audio.stop();
                  this.removePlaying(audioInfoToDiscard.audio);
                }
              };

              return AudioManager;
            }();
            var audioManager = new AudioManager();

            var _dec$1J, _dec2$1e, _dec3$V, _dec4$O, _dec5$E, _dec6$x, _dec7$v, _dec8$s, _dec9$p, _dec10$o, _class$1M, _class2$1x, _descriptor$1m, _descriptor2$13, _descriptor3$O, _descriptor4$H, _class3$D, _temp$1D;
            var AudioSource = function (v) { return exports({ AudioSource: v, AudioSourceComponent: v }), v; }((_dec$1J = ccclass('cc.AudioSource'), _dec2$1e = help(), _dec3$V = menu(), _dec4$O = type(AudioClip), _dec5$E = type(AudioClip), _dec6$x = tooltip(), _dec7$v = tooltip(), _dec8$s = tooltip(), _dec9$p = range(), _dec10$o = tooltip(), _dec$1J(_class$1M = _dec2$1e(_class$1M = _dec3$V(_class$1M = (_class2$1x = (_temp$1D = _class3$D = function (_Component) {
              _inheritsLoose(AudioSource, _Component);

              function AudioSource() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Component.call.apply(_Component, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "_clip", _descriptor$1m, _assertThisInitialized(_this));

                _this._player = null;

                _initializerDefineProperty(_this, "_loop", _descriptor2$13, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_playOnAwake", _descriptor3$O, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_volume", _descriptor4$H, _assertThisInitialized(_this));

                _this._cachedCurrentTime = 0;
                _this._operationsBeforeLoading = [];
                _this._isLoaded = false;
                _this._lastSetClip = void 0;
                return _this;
              }

              var _proto = AudioSource.prototype;

              _proto._syncPlayer = function _syncPlayer() {
                var _this2 = this;

                var clip = this._clip;
                this._isLoaded = false;

                if (!clip || this._lastSetClip === clip) {
                  return;
                }

                if (!clip._nativeAsset) {
                  console.error('Invalid audio clip');
                  return;
                }

                this._lastSetClip = clip;
                AudioPlayer.load(clip._nativeAsset.url, {
                  audioLoadMode: clip.loadMode
                }).then(function (player) {
                  if (_this2._lastSetClip !== clip) {
                    return;
                  }

                  _this2._isLoaded = true;

                  if (_this2._player) {
                    _this2._player.offEnded();

                    _this2._player.offInterruptionBegin();

                    _this2._player.offInterruptionEnd();

                    _this2._player.destroy();
                  }

                  _this2._player = player;
                  player.onEnded(function () {
                    audioManager.removePlaying(player);
                  });
                  player.onInterruptionBegin(function () {
                    audioManager.removePlaying(player);
                  });
                  player.onInterruptionEnd(function () {
                    audioManager.addPlaying(player);
                  });

                  _this2._syncStates();
                })["catch"](function (e) {});
              };

              _proto.onLoad = function onLoad() {
                this._syncPlayer();
              };

              _proto.onEnable = function onEnable() {
                if (this._playOnAwake && !this.playing) {
                  this.play();
                }
              };

              _proto.onDisable = function onDisable() {
                this.pause();
              };

              _proto.onDestroy = function onDestroy() {
                this.stop();
              };

              _proto.play = function play() {
                var _this$_player2,
                    _this3 = this;

                if (!this._isLoaded) {
                  this._operationsBeforeLoading.push('play');

                  return;
                }

                audioManager.discardOnePlayingIfNeeded();

                if (this.state === AudioState.PLAYING) {
                  var _this$_player;

                  (_this$_player = this._player) === null || _this$_player === void 0 ? void 0 : _this$_player.stop()["catch"](function (e) {});
                }

                (_this$_player2 = this._player) === null || _this$_player2 === void 0 ? void 0 : _this$_player2.play().then(function () {
                  audioManager.addPlaying(_this3._player);
                })["catch"](function (e) {});
              };

              _proto.pause = function pause() {
                var _this$_player3,
                    _this4 = this;

                if (!this._isLoaded) {
                  this._operationsBeforeLoading.push('pause');

                  return;
                }

                (_this$_player3 = this._player) === null || _this$_player3 === void 0 ? void 0 : _this$_player3.pause().then(function () {
                  audioManager.removePlaying(_this4._player);
                })["catch"](function (e) {});
              };

              _proto.stop = function stop() {
                var _this$_player4,
                    _this5 = this;

                if (!this._isLoaded) {
                  this._operationsBeforeLoading.push('stop');

                  return;
                }

                (_this$_player4 = this._player) === null || _this$_player4 === void 0 ? void 0 : _this$_player4.stop().then(function () {
                  audioManager.removePlaying(_this5._player);
                })["catch"](function (e) {});
              };

              _proto.playOneShot = function playOneShot(clip, volumeScale) {
                if (volumeScale === void 0) {
                  volumeScale = 1;
                }

                if (!clip._nativeAsset) {
                  console.error('Invalid audio clip');
                  return;
                }

                AudioPlayer.loadOneShotAudio(clip._nativeAsset.url, this._volume * volumeScale, {
                  audioLoadMode: clip.loadMode
                }).then(function (oneShotAudio) {
                  audioManager.discardOnePlayingIfNeeded();

                  oneShotAudio.onPlay = function () {
                    audioManager.addPlaying(oneShotAudio);
                  };

                  oneShotAudio.onEnd = function () {
                    audioManager.removePlaying(oneShotAudio);
                  };

                  oneShotAudio.play();
                })["catch"](function (e) {});
              };

              _proto._syncStates = function _syncStates() {
                var _this6 = this;

                if (!this._player) {
                  return;
                }

                this._player.seek(this._cachedCurrentTime).then(function () {
                  if (_this6._player) {
                    _this6._player.loop = _this6._loop;
                    _this6._player.volume = _this6._volume;

                    _this6._operationsBeforeLoading.forEach(function (opName) {
                      var _this6$opName;

                      (_this6$opName = _this6[opName]) === null || _this6$opName === void 0 ? void 0 : _this6$opName.call(_this6);
                    });

                    _this6._operationsBeforeLoading.length = 0;
                  }
                })["catch"](function (e) {});
              };

              _createClass(AudioSource, [{
                key: "clip",
                get: function get() {
                  return this._clip;
                },
                set: function set(val) {
                  if (val === this._clip) {
                    return;
                  }

                  this._clip = val;

                  this._syncPlayer();
                }
              }, {
                key: "loop",
                get: function get() {
                  return this._loop;
                },
                set: function set(val) {
                  this._loop = val;
                  this._player && (this._player.loop = val);
                }
              }, {
                key: "playOnAwake",
                get: function get() {
                  return this._playOnAwake;
                },
                set: function set(val) {
                  this._playOnAwake = val;
                }
              }, {
                key: "volume",
                get: function get() {
                  return this._volume;
                },
                set: function set(val) {
                  if (Number.isNaN(val)) {
                    console.warn('illegal audio volume!');
                    return;
                  }

                  val = clamp(val, 0, 1);

                  if (this._player) {
                    this._player.volume = val;
                    this._volume = this._player.volume;
                  } else {
                    this._volume = val;
                  }
                }
              }, {
                key: "currentTime",
                get: function get() {
                  return this._player ? this._player.currentTime : this._cachedCurrentTime;
                },
                set: function set(num) {
                  var _this$_player5;

                  if (Number.isNaN(num)) {
                    console.warn('illegal audio time!');
                    return;
                  }

                  num = clamp(num, 0, this.duration);
                  this._cachedCurrentTime = num;
                  (_this$_player5 = this._player) === null || _this$_player5 === void 0 ? void 0 : _this$_player5.seek(this._cachedCurrentTime)["catch"](function (e) {});
                }
              }, {
                key: "duration",
                get: function get() {
                  var _this$_clip$getDurati, _this$_clip;

                  return (_this$_clip$getDurati = (_this$_clip = this._clip) === null || _this$_clip === void 0 ? void 0 : _this$_clip.getDuration()) !== null && _this$_clip$getDurati !== void 0 ? _this$_clip$getDurati : this._player ? this._player.currentTime : 0;
                }
              }, {
                key: "state",
                get: function get() {
                  return this._player ? this._player.state : AudioState.INIT;
                }
              }, {
                key: "playing",
                get: function get() {
                  return this.state === AudioSource.AudioState.PLAYING;
                }
              }], [{
                key: "maxAudioChannel",
                get: function get() {
                  return AudioPlayer.maxAudioChannel;
                }
              }]);

              return AudioSource;
            }(Component), _class3$D.AudioState = AudioState, _temp$1D), (_descriptor$1m = _applyDecoratedDescriptor(_class2$1x.prototype, "_clip", [_dec4$O], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor2$13 = _applyDecoratedDescriptor(_class2$1x.prototype, "_loop", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor3$O = _applyDecoratedDescriptor(_class2$1x.prototype, "_playOnAwake", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _descriptor4$H = _applyDecoratedDescriptor(_class2$1x.prototype, "_volume", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1;
              }
            }), _applyDecoratedDescriptor(_class2$1x.prototype, "clip", [_dec5$E, _dec6$x], Object.getOwnPropertyDescriptor(_class2$1x.prototype, "clip"), _class2$1x.prototype), _applyDecoratedDescriptor(_class2$1x.prototype, "loop", [_dec7$v], Object.getOwnPropertyDescriptor(_class2$1x.prototype, "loop"), _class2$1x.prototype), _applyDecoratedDescriptor(_class2$1x.prototype, "playOnAwake", [_dec8$s], Object.getOwnPropertyDescriptor(_class2$1x.prototype, "playOnAwake"), _class2$1x.prototype), _applyDecoratedDescriptor(_class2$1x.prototype, "volume", [_dec9$p, _dec10$o], Object.getOwnPropertyDescriptor(_class2$1x.prototype, "volume"), _class2$1x.prototype)), _class2$1x)) || _class$1M) || _class$1M) || _class$1M));

            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(function (item) {
              return {
                name: item,
                suggest: "please use AudioSource.prototype." + item + " instead"
              };
            }));

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

            var _dec$1K, _class$1N, _class2$1y, _descriptor$1n, _temp$1E;
            var VideoClip = exports('VideoClip', (_dec$1K = ccclass('cc.VideoClip'), _dec$1K(_class$1N = (_class2$1y = (_temp$1E = function (_Asset) {
              _inheritsLoose(VideoClip, _Asset);

              function VideoClip() {
                var _this;

                _this = _Asset.call(this) || this;

                _initializerDefineProperty(_this, "_duration", _descriptor$1n, _assertThisInitialized(_this));

                _this._video = null;
                _this.loaded = false;
                return _this;
              }

              _createClass(VideoClip, [{
                key: "_nativeAsset",
                get: function get() {
                  return this._video;
                },
                set: function set(clip) {
                  this._video = clip;

                  if (clip) {
                    this._duration = clip.duration;
                    this.loaded = true;
                  } else {
                    this._duration = 0;
                    this.loaded = false;
                  }
                }
              }]);

              return VideoClip;
            }(Asset), _temp$1E), (_descriptor$1n = _applyDecoratedDescriptor(_class2$1y.prototype, "_duration", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            })), _class2$1y)) || _class$1N));

            function downloadVideo(url, options, onComplete) {
              var video = document.createElement('video');
              var source = document.createElement('source');
              video.appendChild(source);
              var 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() {
                var message = "load video failure - " + url;
                log(message);
                onComplete(new Error(message));
              };

              req.send();
            }

            function createVideoClip(id, data, options, onComplete) {
              var out = new VideoClip();
              out._nativeUrl = id;
              out._nativeAsset = data;
              onComplete(null, out);
            }

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

            var ResourceType = Enum({
              REMOTE: 0,
              LOCAL: 1
            });
            var EventType$7;

            (function (EventType) {
              EventType["NONE"] = "none";
              EventType["PLAYING"] = "playing";
              EventType["PAUSED"] = "paused";
              EventType["STOPPED"] = "stopped";
              EventType["COMPLETED"] = "completed";
              EventType["META_LOADED"] = "meta-loaded";
              EventType["READY_TO_PLAY"] = "ready-to-play";
              EventType["ERROR"] = "error";
              EventType["CLICKED"] = "clicked";
            })(EventType$7 || (EventType$7 = {}));

            var READY_STATE;

            (function (READY_STATE) {
              READY_STATE[READY_STATE["HAVE_NOTHING"] = 0] = "HAVE_NOTHING";
              READY_STATE[READY_STATE["HAVE_METADATA"] = 1] = "HAVE_METADATA";
              READY_STATE[READY_STATE["HAVE_CURRENT_DATA"] = 2] = "HAVE_CURRENT_DATA";
              READY_STATE[READY_STATE["HAVE_FUTURE_DATA"] = 3] = "HAVE_FUTURE_DATA";
              READY_STATE[READY_STATE["HAVE_ENOUGH_DATA"] = 4] = "HAVE_ENOUGH_DATA";
            })(READY_STATE || (READY_STATE = {}));

            var VideoPlayerImpl = function () {
              function VideoPlayerImpl(component) {
                var _this = this;

                this._componentEventList = new Map();
                this._state = EventType$7.NONE;
                this._video = null;
                this._onHide = void 0;
                this._onShow = 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._onHide = function () {
                  if (!_this.video || _this._state !== EventType$7.PLAYING) {
                    return;
                  }

                  _this.video.pause();

                  _this._interrupted = true;
                };

                this._onShow = function () {
                  if (!_this._interrupted || !_this.video) {
                    return;
                  }

                  _this.video.play();

                  _this._interrupted = false;
                };

                legacyCC.game.on(legacyCC.Game.EVENT_HIDE, this._onHide);
                legacyCC.game.on(legacyCC.Game.EVENT_SHOW, this._onShow);
              }

              var _proto = VideoPlayerImpl.prototype;

              _proto.onLoadedMetadata = function onLoadedMetadata(e) {
                this._loadedMeta = true;
                this._forceUpdate = true;

                if (this._visible) {
                  this.enable();
                } else {
                  this.disable();
                }

                this.dispatchEvent(EventType$7.META_LOADED);
                var video = e.target;

                if (this._keepAspectRatio && video) {
                  this.syncUITransform(video.videoWidth, video.videoHeight);
                }

                this.delayedFullScreen();
                this.delayedPlay();
              };

              _proto.onCanPlay = function onCanPlay(e) {
                this._loaded = true;
                this.dispatchEvent(EventType$7.READY_TO_PLAY);
              };

              _proto.onPlay = function onPlay(e) {
                this._playing = true;
                this.dispatchEvent(EventType$7.PLAYING);
              };

              _proto.onPlaying = function onPlaying(e) {
                this.dispatchEvent(EventType$7.PLAYING);
              };

              _proto.onPause = function onPause(e) {
                if (this._ignorePause) {
                  this._ignorePause = false;
                  return;
                }

                this._playing = false;
                this.dispatchEvent(EventType$7.PAUSED);
              };

              _proto.onStoped = function onStoped(e) {
                this._playing = false;
                this._ignorePause = false;
                this.dispatchEvent(EventType$7.STOPPED);
              };

              _proto.onEnded = function onEnded(e) {
                this.dispatchEvent(EventType$7.COMPLETED);
              };

              _proto.onClick = function onClick(e) {
                this.dispatchEvent(EventType$7.CLICKED);
              };

              _proto.onError = function onError(e) {
                this.dispatchEvent(EventType$7.ERROR);
                var video = e.target;

                if (video && video.error) {
                  error("Error " + video.error.code + "; details: " + video.error.message);
                }
              };

              _proto.play = function play() {
                if (this._loadedMeta || this._loaded) {
                  this.canPlay();
                } else {
                  this._waitingPlay = true;
                }
              };

              _proto.delayedPlay = function delayedPlay() {
                if (this._waitingPlay) {
                  this.canPlay();
                  this._waitingPlay = false;
                }
              };

              _proto.syncFullScreenOnAwake = function syncFullScreenOnAwake(enabled) {
                this._fullScreenOnAwake = enabled;

                if (this._loadedMeta || this._loaded) {
                  this.canFullScreen(enabled);
                } else {
                  this._waitingFullscreen = true;
                }
              };

              _proto.delayedFullScreen = function delayedFullScreen() {
                if (this._waitingFullscreen) {
                  this.canFullScreen(this._fullScreenOnAwake);
                  this._waitingFullscreen = false;
                }
              };

              _proto.dispatchEvent = function dispatchEvent(key) {
                var callback = this._componentEventList.get(key);

                if (callback) {
                  this._state = key;
                  callback.call(this);
                }
              };

              _proto.syncUITransform = function syncUITransform(width, height) {
                if (this._uiTrans) {
                  this._uiTrans.width = width;
                  this._uiTrans.height = height;
                }
              };

              _proto.syncCurrentTime = function syncCurrentTime() {
                if (!this.video) {
                  return;
                }

                if (this._cachedCurrentTime !== -1 && this.video.currentTime !== this._cachedCurrentTime) {
                  this.seekTo(this._cachedCurrentTime);
                  this._cachedCurrentTime = -1;
                }
              };

              _proto.destroy = function destroy() {
                this.removeVideoPlayer();

                this._componentEventList.clear();

                legacyCC.game.off(legacyCC.Game.EVENT_HIDE, this._onHide);
                legacyCC.game.off(legacyCC.Game.EVENT_SHOW, this._onShow);
              };

              _createClass(VideoPlayerImpl, [{
                key: "fullScreenOnAwake",
                get: function get() {
                  return this._fullScreenOnAwake;
                }
              }, {
                key: "loaded",
                get: function get() {
                  return this._loaded;
                }
              }, {
                key: "componentEventList",
                get: function get() {
                  return this._componentEventList;
                }
              }, {
                key: "video",
                get: function get() {
                  return this._video;
                }
              }, {
                key: "state",
                get: function get() {
                  return this._state;
                }
              }, {
                key: "isPlaying",
                get: function get() {
                  return this._playing;
                }
              }, {
                key: "UICamera",
                get: function get() {
                  return director.root.batcher2D.getFirstRenderCamera(this._node);
                }
              }]);

              return VideoPlayerImpl;
            }();
            legacyCC.internal.VideoPlayerImpl = VideoPlayerImpl;

            var MIN_ZINDEX = -Math.pow(2, 15);

            var _mat4_temp$2 = mat4();

            var VideoPlayerImplWeb = function (_VideoPlayerImpl) {
              _inheritsLoose(VideoPlayerImplWeb, _VideoPlayerImpl);

              function VideoPlayerImplWeb(component) {
                var _this;

                _this = _VideoPlayerImpl.call(this, component) || this;
                _this._eventList = new Map();
                _this._clearColorA = -1;
                _this._clearFlag = void 0;
                return _this;
              }

              var _proto = VideoPlayerImplWeb.prototype;

              _proto.addListener = function addListener(type, handler) {
                if (!this._video) {
                  return;
                }

                this._eventList.set(type, handler);

                this._video.addEventListener(type, handler);
              };

              _proto.removeAllListeners = function removeAllListeners() {
                var _this2 = this;

                this._eventList.forEach(function (handler, type) {
                  if (!_this2._video) {
                    return;
                  }

                  _this2._video.removeEventListener(type, handler);
                });

                this._eventList.clear();
              };

              _proto.canPlay = function canPlay() {
                var _this3 = this;

                if (this.video) {
                  var promise = this.video.play();

                  if (window.Promise && promise instanceof Promise) {
                    promise["catch"](function (error) {}).then(function () {
                      _this3.syncCurrentTime();
                    });
                  }
                }
              };

              _proto.pause = function pause() {
                if (this.video) {
                  this.video.pause();
                  this._cachedCurrentTime = this.video.currentTime;
                }
              };

              _proto.resume = function resume() {
                this.play();
              };

              _proto.stop = function stop() {
                var _this4 = this;

                if (this.video) {
                  this._ignorePause = true;
                  this.video.currentTime = 0;
                  this.video.pause();
                  this._cachedCurrentTime = 0;
                  setTimeout(function () {
                    _this4._ignorePause = false;

                    _this4.dispatchEvent(EventType$7.STOPPED);
                  }, 0);
                }
              };

              _proto.syncClip = function syncClip(clip) {
                this.removeVideoPlayer();

                if (!clip) {
                  return;
                }

                this.createVideoPlayer(clip.nativeUrl);
              };

              _proto.syncURL = function syncURL(url) {
                this.removeVideoPlayer();

                if (!url) {
                  return;
                }

                this.createVideoPlayer(url);
              };

              _proto.syncPlaybackRate = function syncPlaybackRate(val) {
                if (system.browserType === BrowserType.UC) {
                  warn('playbackRate is not supported by the uc mobile browser.');
                  return;
                }

                if (this.video) {
                  this.video.playbackRate = val;
                }
              };

              _proto.syncVolume = function syncVolume(val) {
                if (this.video) {
                  this.video.volume = val;
                }
              };

              _proto.syncMute = function syncMute(enabled) {
                if (this.video) {
                  this.video.muted = enabled;
                }
              };

              _proto.syncLoop = function syncLoop(enabled) {
                if (this.video) {
                  this.video.loop = enabled;
                }
              };

              _proto.getDuration = function getDuration() {
                if (!this.video) {
                  return 0;
                }

                return this.video.duration;
              };

              _proto.getCurrentTime = function getCurrentTime() {
                if (this.video) {
                  return this.video.currentTime;
                }

                return -1;
              };

              _proto.seekTo = function seekTo(val) {
                if (this.video) {
                  this.video.currentTime = val;
                }
              };

              _proto.canFullScreen = function canFullScreen(enabled) {
                var _this5 = this;

                var video = this._video;

                if (!video || video.readyState !== READY_STATE.HAVE_ENOUGH_DATA) {
                  return;
                }

                if (system.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 (system.browserType === BrowserType.IE) {
                    video.style.transform = '';
                  }

                  video.setAttribute('x5-video-player-fullscreen', 'true');
                  screen.requestFullScreen(video, function (document) {
                    var fullscreenElement = system.browserType === BrowserType.IE ? document.msFullscreenElement : document.fullscreenElement;
                    _this5._fullScreenOnAwake = fullscreenElement === video;
                  }, function () {
                    _this5._fullScreenOnAwake = false;
                  });
                } else {
                  video.removeAttribute('x5-video-player-fullscreen');
                  screen.exitFullScreen();
                }
              };

              _proto.syncStayOnBottom = function syncStayOnBottom(enabled) {
                if (this._video) {
                  this._video.style['z-index'] = enabled ? MIN_ZINDEX : 0;
                  this._stayOnBottom = enabled;
                }

                this._dirty = true;
              };

              _proto.syncKeepAspectRatio = function syncKeepAspectRatio(enabled) {
                this._keepAspectRatio = enabled;

                if (enabled && this._loadedMeta && this._video) {
                  this.syncUITransform(this._video.videoWidth, this._video.videoHeight);
                }
              };

              _proto.removeVideoPlayer = function removeVideoPlayer() {
                var 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;
              };

              _proto.createVideoPlayer = function createVideoPlayer(url) {
                var video = this._video = document.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);
                var source = document.createElement('source');
                video.appendChild(source);
                source.src = url;
              };

              _proto._bindDomEvent = function _bindDomEvent() {
                var video = 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));
              };

              _proto.onCanPlay = function onCanPlay(e) {
                var video = e.target;

                if (this._loaded && video) {
                  return;
                }

                switch (video.readyState) {
                  case READY_STATE.HAVE_METADATA:
                  case READY_STATE.HAVE_ENOUGH_DATA:
                    {
                      _VideoPlayerImpl.prototype.onCanPlay.call(this, e);

                      break;
                    }
                }
              };

              _proto.enable = function enable() {
                if (this._video) {
                  this._visible = true;

                  if (this._video.style.visibility === 'visible') {
                    return;
                  }

                  this._video.style.visibility = 'visible';
                }
              };

              _proto.disable = function 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';
                }
              };

              _proto.syncMatrix = function syncMatrix() {
                if (!this._video || !this._visible || !this._component) return;
                var 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 = ClearFlagBit.ALL;
                  } 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$2);

                camera.update(true);
                camera.worldMatrixToScreen(_mat4_temp$2, _mat4_temp$2, game.canvas.width, game.canvas.height);
                var width = 0;
                var 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$2.m00 && this._m01 === _mat4_temp$2.m01 && this._m04 === _mat4_temp$2.m04 && this._m05 === _mat4_temp$2.m05 && this._m12 === _mat4_temp$2.m12 && this._m13 === _mat4_temp$2.m13 && this._w === width && this._h === height) {
                  return;
                }

                this._m00 = _mat4_temp$2.m00;
                this._m01 = _mat4_temp$2.m01;
                this._m04 = _mat4_temp$2.m04;
                this._m05 = _mat4_temp$2.m05;
                this._m12 = _mat4_temp$2.m12;
                this._m13 = _mat4_temp$2.m13;
                this._w = width;
                this._h = height;
                var dpr = view.getDevicePixelRatio();
                var scaleX = 1 / dpr;
                var scaleY = 1 / dpr;
                var container = game.container;
                var sx = _mat4_temp$2.m00 * scaleX;
                var b = _mat4_temp$2.m01;
                var c = _mat4_temp$2.m04;
                var sy = _mat4_temp$2.m05 * scaleY;
                this._video.style.width = this._w + "px";
                this._video.style.height = this._h + "px";

                if (system.browserType !== BrowserType.MOBILE_QQ) {
                  this._video.style.objectFit = this._keepAspectRatio ? 'none' : 'fill';
                } else {
                  warn('keepAspectRatio is not supported by the qq mobile browser.');
                }

                var w = this._w * scaleX;
                var h = this._h * scaleY;
                var _anchorPoint = this._uiTrans.anchorPoint,
                    x = _anchorPoint.x,
                    y = _anchorPoint.y;
                var appx = w * _mat4_temp$2.m00 * x;
                var appy = h * _mat4_temp$2.m05 * y;
                var offsetX = container && container.style.paddingLeft ? parseInt(container.style.paddingLeft) : 0;
                var offsetY = container && container.style.paddingBottom ? parseInt(container.style.paddingBottom) : 0;
                var tx = _mat4_temp$2.m12 * scaleX - appx + offsetX;
                var ty = _mat4_temp$2.m13 * scaleY - appy + offsetY;
                var matrix = "matrix(" + sx + "," + -b + "," + -c + "," + sy + "," + tx + "," + -ty + ")";
                this._video.style.transform = matrix;
                this._video.style['-webkit-transform'] = matrix;

                if (system.browserType !== BrowserType.IE) {
                  this._forceUpdate = false;
                }
              };

              return VideoPlayerImplWeb;
            }(VideoPlayerImpl);

            var VideoPlayerImplManager = function () {
              function VideoPlayerImplManager() {}

              VideoPlayerImplManager.getImpl = function getImpl(component) {
                return new VideoPlayerImplWeb(component);
              };

              return VideoPlayerImplManager;
            }();
            legacyCC.internal.VideoPlayerImplManager = VideoPlayerImplManager;

            var _dec$1L, _dec2$1f, _dec3$W, _dec4$P, _dec5$F, _dec6$y, _dec7$w, _dec8$t, _dec9$q, _dec10$p, _dec11$n, _dec12$m, _dec13$j, _dec14$g, _dec15$g, _dec16$f, _dec17$e, _dec18$e, _dec19$e, _dec20$d, _dec21$d, _dec22$d, _dec23$d, _class$1O, _class2$1z, _descriptor$1o, _descriptor2$14, _descriptor3$P, _descriptor4$I, _descriptor5$z, _descriptor6$q, _descriptor7$k, _descriptor8$k, _descriptor9$h, _descriptor10$h, _descriptor11$g, _descriptor12$d, _class3$E, _temp$1F;
            var VideoPlayer = exports('VideoPlayer', (_dec$1L = ccclass('cc.VideoPlayer'), _dec2$1f = help(), _dec3$W = menu(), _dec4$P = requireComponent(UITransform), _dec5$F = type(VideoClip), _dec6$y = type(ResourceType), _dec7$w = tooltip(), _dec8$t = tooltip(), _dec9$q = type(VideoClip), _dec10$p = tooltip(), _dec11$n = tooltip(), _dec12$m = range(), _dec13$j = tooltip(), _dec14$g = range(), _dec15$g = tooltip(), _dec16$f = tooltip(), _dec17$e = tooltip(), _dec18$e = tooltip(), _dec19$e = tooltip(), _dec20$d = tooltip(), _dec21$d = type([EventHandler]), _dec22$d = displayOrder(), _dec23$d = tooltip(), _dec$1L(_class$1O = _dec2$1f(_class$1O = _dec3$W(_class$1O = _dec4$P(_class$1O = executeInEditMode(_class$1O = (_class2$1z = (_temp$1F = _class3$E = function (_Component) {
              _inheritsLoose(VideoPlayer, _Component);

              function VideoPlayer() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Component.call.apply(_Component, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "_resourceType", _descriptor$1o, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_remoteURL", _descriptor2$14, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_clip", _descriptor3$P, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_playOnAwake", _descriptor4$I, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_volume", _descriptor5$z, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_mute", _descriptor6$q, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_playbackRate", _descriptor7$k, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_loop", _descriptor8$k, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_fullScreenOnAwake", _descriptor9$h, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_stayOnBottom", _descriptor10$h, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_keepAspectRatio", _descriptor11$g, _assertThisInitialized(_this));

                _this._impl = null;
                _this._cachedCurrentTime = 0;

                _initializerDefineProperty(_this, "videoPlayerEvent", _descriptor12$d, _assertThisInitialized(_this));

                return _this;
              }

              var _proto = VideoPlayer.prototype;

              _proto.syncSource = function syncSource() {
                if (!this._impl) {
                  return;
                }

                if (this._resourceType === ResourceType.REMOTE) {
                  this._impl.syncURL(this._remoteURL);
                } else {
                  this._impl.syncClip(this._clip);
                }
              };

              _proto.__preload = function __preload() {

                this._impl = VideoPlayerImplManager.getImpl(this);
                this.syncSource();

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

                this._impl.componentEventList.set(EventType$7.META_LOADED, this.onMetaLoaded.bind(this));

                this._impl.componentEventList.set(EventType$7.READY_TO_PLAY, this.onReadyToPlay.bind(this));

                this._impl.componentEventList.set(EventType$7.PLAYING, this.onPlaying.bind(this));

                this._impl.componentEventList.set(EventType$7.PAUSED, this.onPasued.bind(this));

                this._impl.componentEventList.set(EventType$7.STOPPED, this.onStopped.bind(this));

                this._impl.componentEventList.set(EventType$7.COMPLETED, this.onCompleted.bind(this));

                this._impl.componentEventList.set(EventType$7.ERROR, this.onError.bind(this));

                if (this._playOnAwake && this._impl.loaded) {
                  this.play();
                }
              };

              _proto.onEnable = function onEnable() {
                if (this._impl) {
                  this._impl.enable();
                }
              };

              _proto.onDisable = function onDisable() {
                if (this._impl) {
                  this._impl.disable();
                }
              };

              _proto.onDestroy = function onDestroy() {
                if (this._impl) {
                  this._impl.destroy();

                  this._impl = null;
                }
              };

              _proto.update = function update(dt) {
                if (this._impl) {
                  this._impl.syncMatrix();
                }
              };

              _proto.onMetaLoaded = function onMetaLoaded() {
                EventHandler.emitEvents(this.videoPlayerEvent, this, EventType$7.META_LOADED);
                this.node.emit('meta-loaded', this);
              };

              _proto.onReadyToPlay = function onReadyToPlay() {
                if (this._playOnAwake && !this.isPlaying) {
                  this.play();
                }

                EventHandler.emitEvents(this.videoPlayerEvent, this, EventType$7.READY_TO_PLAY);
                this.node.emit(EventType$7.READY_TO_PLAY, this);
              };

              _proto.onPlaying = function onPlaying() {
                EventHandler.emitEvents(this.videoPlayerEvent, this, EventType$7.PLAYING);
                this.node.emit(EventType$7.PLAYING, this);
              };

              _proto.onPasued = function onPasued() {
                EventHandler.emitEvents(this.videoPlayerEvent, this, EventType$7.PAUSED);
                this.node.emit(EventType$7.PAUSED, this);
              };

              _proto.onStopped = function onStopped() {
                EventHandler.emitEvents(this.videoPlayerEvent, this, EventType$7.STOPPED);
                this.node.emit(EventType$7.STOPPED, this);
              };

              _proto.onCompleted = function onCompleted() {
                EventHandler.emitEvents(this.videoPlayerEvent, this, EventType$7.COMPLETED);
                this.node.emit(EventType$7.COMPLETED, this);
              };

              _proto.onError = function onError() {
                EventHandler.emitEvents(this.videoPlayerEvent, this, EventType$7.ERROR);
                this.node.emit(EventType$7.ERROR, this);
              };

              _proto.play = function play() {
                if (this._impl) {
                  this._impl.play();
                }
              };

              _proto.resume = function resume() {
                if (this._impl) {
                  this._impl.resume();
                }
              };

              _proto.pause = function pause() {
                if (this._impl) {
                  this._impl.pause();
                }
              };

              _proto.stop = function stop() {
                if (this._impl) {
                  this._impl.stop();
                }
              };

              _createClass(VideoPlayer, [{
                key: "resourceType",
                get: function get() {
                  return this._resourceType;
                },
                set: function set(val) {
                  if (this._resourceType !== val) {
                    this._resourceType = val;
                    this.syncSource();
                  }
                }
              }, {
                key: "remoteURL",
                get: function get() {
                  return this._remoteURL;
                },
                set: function set(val) {
                  if (this._remoteURL !== val) {
                    this._remoteURL = val;
                    this.syncSource();
                  }
                }
              }, {
                key: "clip",
                get: function get() {
                  return this._clip;
                },
                set: function set(val) {
                  if (this._clip !== val) {
                    this._clip = val;
                    this.syncSource();
                  }
                }
              }, {
                key: "playOnAwake",
                get: function get() {
                  return this._playOnAwake;
                },
                set: function set(value) {
                  this._playOnAwake = value;
                }
              }, {
                key: "playbackRate",
                get: function get() {
                  return this._playbackRate;
                },
                set: function set(value) {
                  this._playbackRate = value;

                  if (this._impl) {
                    this._impl.syncPlaybackRate(value);
                  }
                }
              }, {
                key: "volume",
                get: function get() {
                  return this._volume;
                },
                set: function set(value) {
                  this._volume = value;

                  if (this._impl) {
                    this._impl.syncVolume(value);
                  }
                }
              }, {
                key: "mute",
                get: function get() {
                  return this._mute;
                },
                set: function set(value) {
                  this._mute = value;

                  if (this._impl) {
                    this._impl.syncMute(value);
                  }
                }
              }, {
                key: "loop",
                get: function get() {
                  return this._loop;
                },
                set: function set(value) {
                  this._loop = value;

                  if (this._impl) {
                    this._impl.syncLoop(value);
                  }
                }
              }, {
                key: "keepAspectRatio",
                get: function get() {
                  return this._keepAspectRatio;
                },
                set: function set(value) {
                  if (this._keepAspectRatio !== value) {
                    this._keepAspectRatio = value;

                    if (this._impl) {
                      this._impl.syncKeepAspectRatio(value);
                    }
                  }
                }
              }, {
                key: "fullScreenOnAwake",
                get: function get() {
                  {
                    if (this._impl) {
                      this._fullScreenOnAwake = this._impl.fullScreenOnAwake;
                      return this._fullScreenOnAwake;
                    }
                  }

                  return this._fullScreenOnAwake;
                },
                set: function set(value) {
                  if (this._fullScreenOnAwake !== value) {
                    this._fullScreenOnAwake = value;

                    if (this._impl) {
                      this._impl.syncFullScreenOnAwake(value);
                    }
                  }
                }
              }, {
                key: "stayOnBottom",
                get: function get() {
                  return this._stayOnBottom;
                },
                set: function set(value) {
                  if (this._stayOnBottom !== value) {
                    this._stayOnBottom = value;

                    if (this._impl) {
                      this._impl.syncStayOnBottom(value);
                    }
                  }
                }
              }, {
                key: "nativeVideo",
                get: function get() {
                  return this._impl && this._impl.video || null;
                }
              }, {
                key: "currentTime",
                get: function get() {
                  if (!this._impl) {
                    return this._cachedCurrentTime;
                  }

                  return this._impl.getCurrentTime();
                },
                set: function set(val) {
                  if (Number.isNaN(val)) {
                    warn("illegal video time! value:" + val);
                    return;
                  }

                  val = clamp(val, 0, this.duration);
                  this._cachedCurrentTime = val;

                  if (this._impl) {
                    this._impl.seekTo(val);
                  }
                }
              }, {
                key: "duration",
                get: function get() {
                  if (!this._impl) {
                    return 0;
                  }

                  return this._impl.getDuration();
                }
              }, {
                key: "state",
                get: function get() {
                  if (!this._impl) {
                    return EventType$7.NONE;
                  }

                  return this._impl.state;
                }
              }, {
                key: "isPlaying",
                get: function get() {
                  if (!this._impl) {
                    return false;
                  }

                  return this._impl.isPlaying;
                }
              }]);

              return VideoPlayer;
            }(Component), _class3$E.EventType = EventType$7, _class3$E.ResourceType = ResourceType, _temp$1F), (_descriptor$1o = _applyDecoratedDescriptor(_class2$1z.prototype, "_resourceType", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return ResourceType.LOCAL;
              }
            }), _descriptor2$14 = _applyDecoratedDescriptor(_class2$1z.prototype, "_remoteURL", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return '';
              }
            }), _descriptor3$P = _applyDecoratedDescriptor(_class2$1z.prototype, "_clip", [_dec5$F, serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor4$I = _applyDecoratedDescriptor(_class2$1z.prototype, "_playOnAwake", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _descriptor5$z = _applyDecoratedDescriptor(_class2$1z.prototype, "_volume", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1.0;
              }
            }), _descriptor6$q = _applyDecoratedDescriptor(_class2$1z.prototype, "_mute", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor7$k = _applyDecoratedDescriptor(_class2$1z.prototype, "_playbackRate", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1;
              }
            }), _descriptor8$k = _applyDecoratedDescriptor(_class2$1z.prototype, "_loop", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor9$h = _applyDecoratedDescriptor(_class2$1z.prototype, "_fullScreenOnAwake", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor10$h = _applyDecoratedDescriptor(_class2$1z.prototype, "_stayOnBottom", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor11$g = _applyDecoratedDescriptor(_class2$1z.prototype, "_keepAspectRatio", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _applyDecoratedDescriptor(_class2$1z.prototype, "resourceType", [_dec6$y, _dec7$w], Object.getOwnPropertyDescriptor(_class2$1z.prototype, "resourceType"), _class2$1z.prototype), _applyDecoratedDescriptor(_class2$1z.prototype, "remoteURL", [_dec8$t], Object.getOwnPropertyDescriptor(_class2$1z.prototype, "remoteURL"), _class2$1z.prototype), _applyDecoratedDescriptor(_class2$1z.prototype, "clip", [_dec9$q, _dec10$p], Object.getOwnPropertyDescriptor(_class2$1z.prototype, "clip"), _class2$1z.prototype), _applyDecoratedDescriptor(_class2$1z.prototype, "playOnAwake", [_dec11$n], Object.getOwnPropertyDescriptor(_class2$1z.prototype, "playOnAwake"), _class2$1z.prototype), _applyDecoratedDescriptor(_class2$1z.prototype, "playbackRate", [slide, _dec12$m, _dec13$j], Object.getOwnPropertyDescriptor(_class2$1z.prototype, "playbackRate"), _class2$1z.prototype), _applyDecoratedDescriptor(_class2$1z.prototype, "volume", [slide, _dec14$g, _dec15$g], Object.getOwnPropertyDescriptor(_class2$1z.prototype, "volume"), _class2$1z.prototype), _applyDecoratedDescriptor(_class2$1z.prototype, "mute", [_dec16$f], Object.getOwnPropertyDescriptor(_class2$1z.prototype, "mute"), _class2$1z.prototype), _applyDecoratedDescriptor(_class2$1z.prototype, "loop", [_dec17$e], Object.getOwnPropertyDescriptor(_class2$1z.prototype, "loop"), _class2$1z.prototype), _applyDecoratedDescriptor(_class2$1z.prototype, "keepAspectRatio", [_dec18$e], Object.getOwnPropertyDescriptor(_class2$1z.prototype, "keepAspectRatio"), _class2$1z.prototype), _applyDecoratedDescriptor(_class2$1z.prototype, "fullScreenOnAwake", [_dec19$e], Object.getOwnPropertyDescriptor(_class2$1z.prototype, "fullScreenOnAwake"), _class2$1z.prototype), _applyDecoratedDescriptor(_class2$1z.prototype, "stayOnBottom", [_dec20$d], Object.getOwnPropertyDescriptor(_class2$1z.prototype, "stayOnBottom"), _class2$1z.prototype), _descriptor12$d = _applyDecoratedDescriptor(_class2$1z.prototype, "videoPlayerEvent", [serializable, _dec21$d, _dec22$d, _dec23$d], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            })), _class2$1z)) || _class$1O) || _class$1O) || _class$1O) || _class$1O) || _class$1O));
            legacyCC.internal.VideoPlayer = VideoPlayer;

            var EventType$8;

            (function (EventType) {
              EventType["NONE"] = "none";
              EventType["LOADING"] = "loading";
              EventType["LOADED"] = "loaded";
              EventType["ERROR"] = "error";
            })(EventType$8 || (EventType$8 = {}));

            var WebViewImpl = function () {
              function WebViewImpl(component) {
                this._componentEventList = new Map();
                this._state = EventType$8.NONE;
                this._warpper = 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();
              }

              var _proto = WebViewImpl.prototype;

              _proto.reset = function reset() {
                this._warpper = 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 = EventType$8.NONE;
                this._forceUpdate = false;
              };

              _proto.dispatchEvent = function dispatchEvent(key) {
                var callback = this._componentEventList.get(key);

                if (callback) {
                  this._state = key;

                  for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
                    args[_key - 1] = arguments[_key];
                  }

                  callback.call(this, args);
                }
              };

              _proto.destroy = function destroy() {
                this.removeWebView();
                this._warpper = null;
                this._webview = null;
                this._loaded = false;
                this._component = null;
                this._uiTrans = null;
                this._forceUpdate = false;

                this._componentEventList.clear();
              };

              _createClass(WebViewImpl, [{
                key: "loaded",
                get: function get() {
                  return this._loaded;
                }
              }, {
                key: "componentEventList",
                get: function get() {
                  return this._componentEventList;
                }
              }, {
                key: "webview",
                get: function get() {
                  return this._webview;
                }
              }, {
                key: "state",
                get: function get() {
                  return this._state;
                }
              }, {
                key: "UICamera",
                get: function get() {
                  return director.root.batcher2D.getFirstRenderCamera(this._node);
                }
              }]);

              return WebViewImpl;
            }();
            legacyCC.internal.WebViewImpl = WebViewImpl;

            var _mat4_temp$3 = mat4();

            var WebViewImplWeb = function (_WebViewImpl) {
              _inheritsLoose(WebViewImplWeb, _WebViewImpl);

              function WebViewImplWeb(component) {
                return _WebViewImpl.call(this, component) || this;
              }

              var _proto = WebViewImplWeb.prototype;

              _proto._bindDomEvent = function _bindDomEvent() {
                var _this = this;

                if (!this.webview) {
                  return;
                }

                var onLoaded = function onLoaded(e) {
                  _this._forceUpdate = true;

                  _this.dispatchEvent(EventType$8.LOADED);

                  var iframe = e.target;
                  var body = iframe.contentDocument && iframe.contentDocument.body;

                  if (body && body.innerHTML.includes('404')) {
                    _this.dispatchEvent(EventType$8.ERROR, body.innerHTML);
                  }
                };

                this.webview.addEventListener('load', onLoaded);
              };

              _proto.loadURL = function loadURL(url) {
                if (this.webview) {
                  this.webview.src = url;
                  this.dispatchEvent(EventType$8.LOADING);
                }
              };

              _proto.createWebView = function createWebView() {
                var warpper = document.createElement('div');
                this._warpper = warpper;
                warpper.id = 'webview-wrapper';
                warpper.style['-webkit-overflow'] = 'auto';
                warpper.style['-webkit-overflow-scrolling'] = 'touch';
                warpper.style.position = 'absolute';
                warpper.style.bottom = '0px';
                warpper.style.left = '0px';
                warpper.style.transformOrigin = '0px 100% 0px';
                warpper.style['-webkit-transform-origin'] = '0px 100% 0px';
                game.container.appendChild(warpper);
                var webview = document.createElement('iframe');
                this._webview = webview;
                webview.id = 'webview';
                webview.style.border = 'none';
                webview.style.width = '100%';
                webview.style.height = '100%';
                warpper.appendChild(webview);

                this._bindDomEvent();
              };

              _proto.removeWebView = function removeWebView() {
                var warpper = this._warpper;

                if (contains$1(game.container, warpper)) {
                  game.container.removeChild(warpper);
                }

                this.reset();
              };

              _proto.enable = function enable() {
                if (this._warpper) {
                  this._warpper.style.visibility = 'visible';
                }
              };

              _proto.disable = function disable() {
                if (this._warpper) {
                  this._warpper.style.visibility = 'hidden';
                }
              };

              _proto.evaluateJS = function evaluateJS(str) {
                if (this.webview) {
                  var win = this.webview.contentWindow;

                  if (win) {
                    try {
                      win.eval(str);
                    } catch (e) {
                      this.dispatchEvent(EventType$8.ERROR, e);
                      error(e);
                    }
                  }
                }
              };

              _proto.setOnJSCallback = function setOnJSCallback(callback) {
                warn('The platform does not support');
              };

              _proto.setJavascriptInterfaceScheme = function setJavascriptInterfaceScheme(scheme) {
                warn('The platform does not support');
              };

              _proto.syncMatrix = function syncMatrix() {
                if (!this._warpper || !this._uiTrans || !this._component || this._warpper.style.visibility === 'hidden') return;
                var camera = this.UICamera;

                if (!camera) {
                  return;
                }

                this._component.node.getWorldMatrix(_mat4_temp$3);

                camera.update(true);
                camera.worldMatrixToScreen(_mat4_temp$3, _mat4_temp$3, game.canvas.width, game.canvas.height);
                var _this$_uiTrans$conten = this._uiTrans.contentSize,
                    width = _this$_uiTrans$conten.width,
                    height = _this$_uiTrans$conten.height;

                if (!this._forceUpdate && this._m00 === _mat4_temp$3.m00 && this._m01 === _mat4_temp$3.m01 && this._m04 === _mat4_temp$3.m04 && this._m05 === _mat4_temp$3.m05 && this._m12 === _mat4_temp$3.m12 && this._m13 === _mat4_temp$3.m13 && this._w === width && this._h === height) {
                  return;
                }

                this._m00 = _mat4_temp$3.m00;
                this._m01 = _mat4_temp$3.m01;
                this._m04 = _mat4_temp$3.m04;
                this._m05 = _mat4_temp$3.m05;
                this._m12 = _mat4_temp$3.m12;
                this._m13 = _mat4_temp$3.m13;
                this._w = width;
                this._h = height;
                var dpr = view.getDevicePixelRatio();
                var scaleX = 1 / dpr;
                var scaleY = 1 / dpr;
                var container = game.container;
                var sx = _mat4_temp$3.m00 * scaleX;
                var b = _mat4_temp$3.m01;
                var c = _mat4_temp$3.m04;
                var sy = _mat4_temp$3.m05 * scaleY;
                this._warpper.style.width = width + "px";
                this._warpper.style.height = height + "px";
                var w = this._w * scaleX;
                var h = this._h * scaleY;
                var appx = w * _mat4_temp$3.m00 * this._uiTrans.anchorX;
                var appy = h * _mat4_temp$3.m05 * this._uiTrans.anchorY;
                var offsetX = container && container.style.paddingLeft ? parseInt(container.style.paddingLeft) : 0;
                var offsetY = container && container.style.paddingBottom ? parseInt(container.style.paddingBottom) : 0;
                var tx = _mat4_temp$3.m12 * scaleX - appx + offsetX;
                var ty = _mat4_temp$3.m13 * scaleY - appy + offsetY;
                var matrix = "matrix(" + sx + "," + -b + "," + -c + "," + sy + "," + tx + "," + -ty + ")";
                this._warpper.style.transform = matrix;
                this._warpper.style['-webkit-transform'] = matrix;
                this._forceUpdate = false;
              };

              return WebViewImplWeb;
            }(WebViewImpl);

            var WebViewImplManager = function () {
              function WebViewImplManager() {}

              WebViewImplManager.getImpl = function getImpl(component) {
                return new WebViewImplWeb(component);
              };

              return WebViewImplManager;
            }();
            legacyCC.internal.WebViewImplManager = WebViewImplManager;

            var _dec$1M, _dec2$1g, _dec3$X, _dec4$Q, _dec5$G, _dec6$z, _dec7$x, _dec8$u, _class$1P, _class2$1A, _descriptor$1p, _descriptor2$15, _class3$F, _temp$1G;
            var WebView = exports('WebView', (_dec$1M = ccclass('cc.WebView'), _dec2$1g = help(), _dec3$X = menu(), _dec4$Q = requireComponent(UITransform), _dec5$G = tooltip(), _dec6$z = type([EventHandler]), _dec7$x = displayOrder(), _dec8$u = tooltip(), _dec$1M(_class$1P = _dec2$1g(_class$1P = _dec3$X(_class$1P = _dec4$Q(_class$1P = executeInEditMode(_class$1P = (_class2$1A = (_temp$1G = _class3$F = function (_Component) {
              _inheritsLoose(WebView, _Component);

              function WebView() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Component.call.apply(_Component, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "_url", _descriptor$1p, _assertThisInitialized(_this));

                _this._impl = null;

                _initializerDefineProperty(_this, "webviewEvents", _descriptor2$15, _assertThisInitialized(_this));

                return _this;
              }

              var _proto = WebView.prototype;

              _proto.setJavascriptInterfaceScheme = function setJavascriptInterfaceScheme(scheme) {
                if (this._impl) {
                  this._impl.setJavascriptInterfaceScheme(scheme);
                }
              };

              _proto.setOnJSCallback = function setOnJSCallback(callback) {
                if (this._impl) {
                  this._impl.setOnJSCallback(callback);
                }
              };

              _proto.evaluateJS = function evaluateJS(str) {
                if (this._impl) {
                  this._impl.evaluateJS(str);
                }
              };

              _proto.__preload = function __preload() {

                this._impl = WebViewImplManager.getImpl(this);

                this._impl.componentEventList.set(EventType$8.LOADING, this.onLoading.bind(this));

                this._impl.componentEventList.set(EventType$8.LOADED, this.onLoaded.bind(this));

                this._impl.componentEventList.set(EventType$8.ERROR, this.onError.bind(this));

                this._impl.loadURL(this._url);
              };

              _proto.onLoading = function onLoading() {
                EventHandler.emitEvents(this.webviewEvents, this, EventType$8.LOADING);
                this.node.emit(EventType$8.LOADING, this);
              };

              _proto.onLoaded = function onLoaded() {
                EventHandler.emitEvents(this.webviewEvents, this, EventType$8.LOADED);
                this.node.emit(EventType$8.LOADED, this);
              };

              _proto.onError = function onError() {
                for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
                  args[_key2] = arguments[_key2];
                }

                EventHandler.emitEvents(this.webviewEvents, this, EventType$8.ERROR, args);
                this.node.emit(EventType$8.ERROR, this, args);
              };

              _proto.onEnable = function onEnable() {
                if (this._impl) {
                  this._impl.enable();
                }
              };

              _proto.onDisable = function onDisable() {
                if (this._impl) {
                  this._impl.disable();
                }
              };

              _proto.onDestroy = function onDestroy() {
                if (this._impl) {
                  this._impl.destroy();

                  this._impl = null;
                }
              };

              _proto.update = function update(dt) {
                if (this._impl) {
                  this._impl.syncMatrix();
                }
              };

              _createClass(WebView, [{
                key: "url",
                get: function get() {
                  return this._url;
                },
                set: function set(val) {
                  this._url = val;

                  if (this._impl) {
                    this._impl.loadURL(val);
                  }
                }
              }, {
                key: "nativeWebView",
                get: function get() {
                  return this._impl && this._impl.webview || null;
                }
              }, {
                key: "state",
                get: function get() {
                  if (!this._impl) {
                    return EventType$8.NONE;
                  }

                  return this._impl.state;
                }
              }]);

              return WebView;
            }(Component), _class3$F.EventType = EventType$8, _temp$1G), (_descriptor$1p = _applyDecoratedDescriptor(_class2$1A.prototype, "_url", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 'https://cocos.com';
              }
            }), _applyDecoratedDescriptor(_class2$1A.prototype, "url", [_dec5$G], Object.getOwnPropertyDescriptor(_class2$1A.prototype, "url"), _class2$1A.prototype), _descriptor2$15 = _applyDecoratedDescriptor(_class2$1A.prototype, "webviewEvents", [serializable, _dec6$z, _dec7$x, _dec8$u], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            })), _class2$1A)) || _class$1P) || _class$1P) || _class$1P) || _class$1P) || _class$1P));
            legacyCC.internal.WebView = WebView;

            var Action = function () {
              function Action() {
                this.originalTarget = null;
                this.target = null;
                this.tag = Action.TAG_INVALID;
              }

              var _proto = Action.prototype;

              _proto.clone = function clone() {
                var action = new Action();
                action.originalTarget = null;
                action.target = null;
                action.tag = this.tag;
                return action;
              };

              _proto.isDone = function isDone() {
                return true;
              };

              _proto.startWithTarget = function startWithTarget(target) {
                this.originalTarget = target;
                this.target = target;
              };

              _proto.stop = function stop() {
                this.target = null;
              };

              _proto.step = function step(dt) {
                logID(1006);
              };

              _proto.update = function update(dt) {
                logID(1007);
              };

              _proto.getTarget = function getTarget() {
                return this.target;
              };

              _proto.setTarget = function setTarget(target) {
                this.target = target;
              };

              _proto.getOriginalTarget = function getOriginalTarget() {
                return this.originalTarget;
              };

              _proto.setOriginalTarget = function setOriginalTarget(originalTarget) {
                this.originalTarget = originalTarget;
              };

              _proto.getTag = function getTag() {
                return this.tag;
              };

              _proto.setTag = function setTag(tag) {
                this.tag = tag;
              };

              _proto.reverse = function reverse() {
                logID(1008);
                return null;
              };

              _proto.retain = function retain() {};

              _proto.release = function release() {};

              return Action;
            }();
            Action.TAG_INVALID = -1;
            var FiniteTimeAction = function (_Action) {
              _inheritsLoose(FiniteTimeAction, _Action);

              function FiniteTimeAction() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Action.call.apply(_Action, [this].concat(args)) || this;
                _this._duration = 0;
                _this._timesForRepeat = 1;
                return _this;
              }

              var _proto2 = FiniteTimeAction.prototype;

              _proto2.getDuration = function getDuration() {
                return this._duration * (this._timesForRepeat || 1);
              };

              _proto2.setDuration = function setDuration(duration) {
                this._duration = duration;
              };

              _proto2.clone = function clone() {
                return new FiniteTimeAction();
              };

              return FiniteTimeAction;
            }(Action);
            var Speed = function (_Action2) {
              _inheritsLoose(Speed, _Action2);

              function Speed(action, speed) {
                var _this2;

                if (speed === void 0) {
                  speed = 1;
                }

                _this2 = _Action2.call(this) || this;
                _this2._speed = 0;
                _this2._innerAction = null;
                action && _this2.initWithAction(action, speed);
                return _this2;
              }

              var _proto3 = Speed.prototype;

              _proto3.getSpeed = function getSpeed() {
                return this._speed;
              };

              _proto3.setSpeed = function setSpeed(speed) {
                this._speed = speed;
              };

              _proto3.initWithAction = function initWithAction(action, speed) {
                if (!action) {
                  errorID(1021);
                  return false;
                }

                this._innerAction = action;
                this._speed = speed;
                return true;
              };

              _proto3.clone = function clone() {
                var action = new Speed();
                action.initWithAction(this._innerAction.clone(), this._speed);
                return action;
              };

              _proto3.startWithTarget = function startWithTarget(target) {
                Action.prototype.startWithTarget.call(this, target);

                this._innerAction.startWithTarget(target);
              };

              _proto3.stop = function stop() {
                this._innerAction.stop();

                Action.prototype.stop.call(this);
              };

              _proto3.step = function step(dt) {
                this._innerAction.step(dt * this._speed);
              };

              _proto3.isDone = function isDone() {
                return this._innerAction.isDone();
              };

              _proto3.reverse = function reverse() {
                return new Speed(this._innerAction.reverse(), this._speed);
              };

              _proto3.setInnerAction = function setInnerAction(action) {
                if (this._innerAction !== action) {
                  this._innerAction = action;
                }
              };

              _proto3.getInnerAction = function getInnerAction() {
                return this._innerAction;
              };

              return Speed;
            }(Action);

            var ID_COUNTER = 0;

            var HashElement = function HashElement() {
              this.actions = [];
              this.target = null;
              this.actionIndex = 0;
              this.currentAction = null;
              this.paused = false;
              this.lock = false;
            };

            var ActionManager = function () {
              function ActionManager() {
                this._hashTargets = new Map();
                this._arrayTargets = [];
                this._elementPool = [];
              }

              var _proto = ActionManager.prototype;

              _proto._searchElementByTarget = function _searchElementByTarget(arr, target) {
                for (var k = 0; k < arr.length; k++) {
                  if (target === arr[k].target) return arr[k];
                }

                return null;
              };

              _proto._getElement = function _getElement(target, paused) {
                var element = this._elementPool.pop();

                if (!element) {
                  element = new HashElement();
                }

                element.target = target;
                element.paused = !!paused;
                return element;
              };

              _proto._putElement = function _putElement(element) {
                element.actions.length = 0;
                element.actionIndex = 0;
                element.currentAction = null;
                element.paused = false;
                element.target = null;
                element.lock = false;

                this._elementPool.push(element);
              };

              _proto.addAction = function addAction(action, target, paused) {
                if (!action || !target) {
                  errorID(1000);
                  return;
                }

                if (target.uuid == null) {
                  target.uuid = "_TWEEN_UUID_" + ID_COUNTER++;
                }

                var element = this._hashTargets.get(target);

                if (!element) {
                  element = this._getElement(target, paused);

                  this._hashTargets.set(target, element);

                  this._arrayTargets.push(element);
                } else if (!element.actions) {
                  element.actions = [];
                }

                element.target = target;
                element.actions.push(action);
                action.startWithTarget(target);
              };

              _proto.removeAllActions = function removeAllActions() {
                var locTargets = this._arrayTargets;

                for (var i = 0; i < locTargets.length; i++) {
                  var element = locTargets[i];
                  if (element) this._putElement(element);
                }

                this._arrayTargets.length = 0;
                this._hashTargets = new Map();
              };

              _proto.removeAllActionsFromTarget = function removeAllActionsFromTarget(target) {
                if (target == null) return;

                var element = this._hashTargets.get(target);

                if (element) {
                  element.actions.length = 0;

                  this._deleteHashElement(element);
                }
              };

              _proto.removeAction = function removeAction(action) {
                if (action == null) return;
                var target = action.getOriginalTarget();

                var element = this._hashTargets.get(target);

                if (element) {
                  for (var i = 0; i < element.actions.length; i++) {
                    if (element.actions[i] === action) {
                      element.actions.splice(i, 1);
                      if (element.actionIndex >= i) element.actionIndex--;
                      break;
                    }
                  }
                }
              };

              _proto._removeActionByTag = function _removeActionByTag(tag, element, target) {
                for (var i = 0, l = element.actions.length; i < l; ++i) {
                  var action = element.actions[i];

                  if (action && action.getTag() === tag) {
                    if (target && action.getOriginalTarget() !== target) {
                      continue;
                    }

                    this._removeActionAtIndex(i, element);

                    break;
                  }
                }
              };

              _proto.removeActionByTag = function removeActionByTag(tag, target) {
                var _this = this;

                if (tag === Action.TAG_INVALID) logID(1002);
                var hashTargets = this._hashTargets;

                if (target) {
                  var element = hashTargets.get(target);

                  if (element) {
                    this._removeActionByTag(tag, element, target);
                  }
                } else {
                  hashTargets.forEach(function (element) {
                    _this._removeActionByTag(tag, element);
                  });
                }
              };

              _proto.getActionByTag = function getActionByTag(tag, target) {
                if (tag === Action.TAG_INVALID) logID(1004);

                var element = this._hashTargets.get(target);

                if (element) {
                  if (element.actions != null) {
                    for (var i = 0; i < element.actions.length; ++i) {
                      var action = element.actions[i];

                      if (action && action.getTag() === tag) {
                        return action;
                      }
                    }
                  }

                  logID(1005, tag);
                }

                return null;
              };

              _proto.getNumberOfRunningActionsInTarget = function getNumberOfRunningActionsInTarget(target) {
                var element = this._hashTargets.get(target);

                if (element) {
                  return element.actions ? element.actions.length : 0;
                }

                return 0;
              };

              _proto.pauseTarget = function pauseTarget(target) {
                var element = this._hashTargets.get(target);

                if (element) element.paused = true;
              };

              _proto.resumeTarget = function resumeTarget(target) {
                var element = this._hashTargets.get(target);

                if (element) element.paused = false;
              };

              _proto.pauseAllRunningActions = function pauseAllRunningActions() {
                var idsWithActions = [];
                var locTargets = this._arrayTargets;

                for (var i = 0; i < locTargets.length; i++) {
                  var element = locTargets[i];

                  if (element && !element.paused) {
                    element.paused = true;
                    idsWithActions.push(element.target);
                  }
                }

                return idsWithActions;
              };

              _proto.resumeTargets = function resumeTargets(targetsToResume) {
                if (!targetsToResume) return;

                for (var i = 0; i < targetsToResume.length; i++) {
                  if (targetsToResume[i]) this.resumeTarget(targetsToResume[i]);
                }
              };

              _proto.pauseTargets = function pauseTargets(targetsToPause) {
                if (!targetsToPause) return;

                for (var i = 0; i < targetsToPause.length; i++) {
                  if (targetsToPause[i]) this.pauseTarget(targetsToPause[i]);
                }
              };

              _proto.purgeSharedManager = function purgeSharedManager() {
                legacyCC.director.getScheduler().unscheduleUpdate(this);
              };

              _proto._removeActionAtIndex = function _removeActionAtIndex(index, element) {
                var action = element.actions[index];
                element.actions.splice(index, 1);
                if (element.actionIndex >= index) element.actionIndex--;

                if (element.actions.length === 0) {
                  this._deleteHashElement(element);
                }
              };

              _proto._deleteHashElement = function _deleteHashElement(element) {
                var ret = false;

                if (element && !element.lock) {
                  if (this._hashTargets.get(element.target)) {
                    this._hashTargets["delete"](element.target);

                    var targets = this._arrayTargets;

                    for (var i = 0, l = targets.length; i < l; i++) {
                      if (targets[i] === element) {
                        targets.splice(i, 1);
                        break;
                      }
                    }

                    this._putElement(element);

                    ret = true;
                  }
                }

                return ret;
              };

              _proto.update = function update(dt) {
                var locTargets = this._arrayTargets;
                var locCurrTarget;

                for (var elt = 0; elt < locTargets.length; elt++) {
                  this._currentTarget = locTargets[elt];
                  locCurrTarget = this._currentTarget;
                  var target = locCurrTarget.target;

                  if (target instanceof CCObject && !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 * (locCurrTarget.currentAction._speedMethod ? locCurrTarget.currentAction._speed : 1));

                      if (locCurrTarget.currentAction && locCurrTarget.currentAction.isDone()) {
                        locCurrTarget.currentAction.stop();
                        var action = locCurrTarget.currentAction;
                        locCurrTarget.currentAction = null;
                        this.removeAction(action);
                      }

                      locCurrTarget.currentAction = null;
                    }

                    locCurrTarget.lock = false;
                  }

                  if (locCurrTarget.actions.length === 0) {
                    if (this._deleteHashElement(locCurrTarget)) {
                      elt--;
                    }
                  }
                }
              };

              return ActionManager;
            }();

            var TweenSystem = exports('TweenSystem', function (_System) {
              _inheritsLoose(TweenSystem, _System);

              function TweenSystem() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _System.call.apply(_System, [this].concat(args)) || this;
                _this.actionMgr = new ActionManager();
                return _this;
              }

              var _proto = TweenSystem.prototype;

              _proto.update = function update(dt) {
                {
                  this.actionMgr.update(dt);
                }
              };

              _createClass(TweenSystem, [{
                key: "ActionManager",
                get: function get() {
                  return this.actionMgr;
                }
              }]);

              return TweenSystem;
            }(System$1));
            TweenSystem.ID = 'TWEEN';
            TweenSystem.instance = void 0;
            director.on(Director.EVENT_INIT, function () {
              var sys = new TweenSystem();
              TweenSystem.instance = sys;
              director.registerSystem(TweenSystem.ID, sys, 100);
            });

            var ActionInstant = function (_FiniteTimeAction) {
              _inheritsLoose(ActionInstant, _FiniteTimeAction);

              function ActionInstant() {
                return _FiniteTimeAction.apply(this, arguments) || this;
              }

              var _proto = ActionInstant.prototype;

              _proto.isDone = function isDone() {
                return true;
              };

              _proto.step = function step(dt) {
                this.update(1);
              };

              _proto.update = function update(dt) {};

              _proto.reverse = function reverse() {
                return this.clone();
              };

              _proto.clone = function clone() {
                return new ActionInstant();
              };

              return ActionInstant;
            }(FiniteTimeAction);
            var Show = function (_ActionInstant) {
              _inheritsLoose(Show, _ActionInstant);

              function Show() {
                return _ActionInstant.apply(this, arguments) || this;
              }

              var _proto2 = Show.prototype;

              _proto2.update = function update(dt) {
                var _renderComps = this.target.getComponentsInChildren(RenderableComponent);

                for (var i = 0; i < _renderComps.length; ++i) {
                  var render = _renderComps[i];
                  render.enabled = true;
                }
              };

              _proto2.reverse = function reverse() {
                return new Hide();
              };

              _proto2.clone = function clone() {
                return new Show();
              };

              return Show;
            }(ActionInstant);
            function show() {
              return new Show();
            }
            var Hide = function (_ActionInstant2) {
              _inheritsLoose(Hide, _ActionInstant2);

              function Hide() {
                return _ActionInstant2.apply(this, arguments) || this;
              }

              var _proto3 = Hide.prototype;

              _proto3.update = function update(dt) {
                var _renderComps = this.target.getComponentsInChildren(RenderableComponent);

                for (var i = 0; i < _renderComps.length; ++i) {
                  var render = _renderComps[i];
                  render.enabled = false;
                }
              };

              _proto3.reverse = function reverse() {
                return new Show();
              };

              _proto3.clone = function clone() {
                return new Hide();
              };

              return Hide;
            }(ActionInstant);
            function hide() {
              return new Hide();
            }
            var ToggleVisibility = function (_ActionInstant3) {
              _inheritsLoose(ToggleVisibility, _ActionInstant3);

              function ToggleVisibility() {
                return _ActionInstant3.apply(this, arguments) || this;
              }

              var _proto4 = ToggleVisibility.prototype;

              _proto4.update = function update(dt) {
                var _renderComps = this.target.getComponentsInChildren(RenderableComponent);

                for (var i = 0; i < _renderComps.length; ++i) {
                  var render = _renderComps[i];
                  render.enabled = !render.enabled;
                }
              };

              _proto4.reverse = function reverse() {
                return new ToggleVisibility();
              };

              _proto4.clone = function clone() {
                return new ToggleVisibility();
              };

              return ToggleVisibility;
            }(ActionInstant);
            var RemoveSelf = function (_ActionInstant4) {
              _inheritsLoose(RemoveSelf, _ActionInstant4);

              function RemoveSelf(isNeedCleanUp) {
                var _this;

                _this = _ActionInstant4.call(this) || this;
                _this._isNeedCleanUp = true;
                isNeedCleanUp !== undefined && _this.init(isNeedCleanUp);
                return _this;
              }

              var _proto5 = RemoveSelf.prototype;

              _proto5.update = function update(dt) {
                this.target.removeFromParent();

                if (this._isNeedCleanUp) {
                  this.target.destroy();
                }
              };

              _proto5.init = function init(isNeedCleanUp) {
                this._isNeedCleanUp = isNeedCleanUp;
                return true;
              };

              _proto5.reverse = function reverse() {
                return new RemoveSelf(this._isNeedCleanUp);
              };

              _proto5.clone = function clone() {
                return new RemoveSelf(this._isNeedCleanUp);
              };

              return RemoveSelf;
            }(ActionInstant);
            function removeSelf(isNeedCleanUp) {
              return new RemoveSelf(isNeedCleanUp);
            }
            var CallFunc = function (_ActionInstant5) {
              _inheritsLoose(CallFunc, _ActionInstant5);

              function CallFunc(selector, selectorTarget, data) {
                var _this2;

                _this2 = _ActionInstant5.call(this) || this;
                _this2._selectorTarget = null;
                _this2._function = null;
                _this2._data = null;

                _this2.initWithFunction(selector, selectorTarget, data);

                return _this2;
              }

              var _proto6 = CallFunc.prototype;

              _proto6.initWithFunction = function initWithFunction(selector, selectorTarget, data) {
                if (selector) {
                  this._function = selector;
                }

                if (selectorTarget) {
                  this._selectorTarget = selectorTarget;
                }

                if (data !== undefined) {
                  this._data = data;
                }

                return true;
              };

              _proto6.execute = function execute() {
                if (this._function) {
                  this._function.call(this._selectorTarget, this.target, this._data);
                }
              };

              _proto6.update = function update(dt) {
                this.execute();
              };

              _proto6.getTargetCallback = function getTargetCallback() {
                return this._selectorTarget;
              };

              _proto6.setTargetCallback = function setTargetCallback(sel) {
                if (sel !== this._selectorTarget) {
                  if (this._selectorTarget) {
                    this._selectorTarget = null;
                  }

                  this._selectorTarget = sel;
                }
              };

              _proto6.clone = function clone() {
                var action = new CallFunc();
                action.initWithFunction(this._function, this._selectorTarget, this._data);
                return action;
              };

              return CallFunc;
            }(ActionInstant);
            function callFunc(selector, selectorTarget, data) {
              return new CallFunc(selector, selectorTarget, data);
            }

            var ActionInterval = function (_FiniteTimeAction) {
              _inheritsLoose(ActionInterval, _FiniteTimeAction);

              function ActionInterval(d) {
                var _this;

                _this = _FiniteTimeAction.call(this) || this;
                _this.MAX_VALUE = 2;
                _this._elapsed = 0;
                _this._firstTick = false;
                _this._easeList = [];
                _this._speed = 1;
                _this._repeatForever = false;
                _this._repeatMethod = false;
                _this._speedMethod = false;

                if (d !== undefined && !isNaN(d)) {
                  _this.initWithDuration(d);
                }

                return _this;
              }

              var _proto = ActionInterval.prototype;

              _proto.getElapsed = function getElapsed() {
                return this._elapsed;
              };

              _proto.initWithDuration = function initWithDuration(d) {
                this._duration = d === 0 ? macro.FLT_EPSILON : d;
                this._elapsed = 0;
                this._firstTick = true;
                return true;
              };

              _proto.isDone = function isDone() {
                return this._elapsed >= this._duration;
              };

              _proto._cloneDecoration = function _cloneDecoration(action) {
                action._repeatForever = this._repeatForever;
                action._speed = this._speed;
                action._timesForRepeat = this._timesForRepeat;
                action._easeList = this._easeList;
                action._speedMethod = this._speedMethod;
                action._repeatMethod = this._repeatMethod;
              };

              _proto._reverseEaseList = function _reverseEaseList(action) {
                if (this._easeList) {
                  action._easeList = [];

                  for (var i = 0; i < this._easeList.length; i++) {
                    action._easeList.push(this._easeList[i]);
                  }
                }
              };

              _proto.clone = function clone() {
                var action = new ActionInterval(this._duration);

                this._cloneDecoration(action);

                return action;
              };

              _proto.easing = function easing(easeObj) {
                if (this._easeList) this._easeList.length = 0;else this._easeList = [];

                for (var i = 0; i < arguments.length; i++) {
                  this._easeList.push(arguments[i]);
                }

                return this;
              };

              _proto._computeEaseTime = function _computeEaseTime(dt) {
                return dt;
              };

              _proto.step = function step(dt) {
                if (this._firstTick) {
                  this._firstTick = false;
                  this._elapsed = 0;
                } else this._elapsed += dt;

                var t = this._elapsed / (this._duration > 0.0000001192092896 ? this._duration : 0.0000001192092896);
                t = t < 1 ? t : 1;
                this.update(t > 0 ? t : 0);

                if (this._repeatMethod && this._timesForRepeat > 1 && this.isDone()) {
                  if (!this._repeatForever) {
                    this._timesForRepeat--;
                  }

                  this.startWithTarget(this.target);
                  this.step(this._elapsed - this._duration);
                }
              };

              _proto.startWithTarget = function startWithTarget(target) {
                Action.prototype.startWithTarget.call(this, target);
                this._elapsed = 0;
                this._firstTick = true;
              };

              _proto.reverse = function reverse() {
                logID(1010);
                return this;
              };

              _proto.setAmplitudeRate = function setAmplitudeRate(amp) {
                logID(1011);
              };

              _proto.getAmplitudeRate = function getAmplitudeRate() {
                logID(1012);
                return 0;
              };

              _proto.speed = function speed(_speed) {
                if (_speed <= 0) {
                  logID(1013);
                  return this;
                }

                this._speedMethod = true;
                this._speed *= _speed;
                return this;
              };

              _proto.getSpeed = function getSpeed() {
                return this._speed;
              };

              _proto.setSpeed = function setSpeed(speed) {
                this._speed = speed;
                return this;
              };

              _proto.repeat = function repeat(times) {
                times = Math.round(times);

                if (isNaN(times) || times < 1) {
                  logID(1014);
                  return this;
                }

                this._repeatMethod = true;
                this._timesForRepeat *= times;
                return this;
              };

              _proto.repeatForever = function repeatForever() {
                this._repeatMethod = true;
                this._timesForRepeat = this.MAX_VALUE;
                this._repeatForever = true;
                return this;
              };

              return ActionInterval;
            }(FiniteTimeAction);
            var Sequence = function (_ActionInterval) {
              _inheritsLoose(Sequence, _ActionInterval);

              function Sequence(tempArray) {
                var _this2;

                _this2 = _ActionInterval.call(this) || this;
                _this2._actions = [];
                _this2._split = 0;
                _this2._last = 0;
                _this2._reversed = false;
                var paramArray = tempArray instanceof Array ? tempArray : arguments;

                if (paramArray.length === 1) {
                  errorID(1019);
                  return _assertThisInitialized(_this2);
                }

                var last = paramArray.length - 1;
                if (last >= 0 && paramArray[last] == null) logID(1015);

                if (last >= 0) {
                  var prev = paramArray[0];
                  var action1;

                  for (var i = 1; i < last; i++) {
                    if (paramArray[i]) {
                      action1 = prev;
                      prev = Sequence._actionOneTwo(action1, paramArray[i]);
                    }
                  }

                  _this2.initWithTwoActions(prev, paramArray[last]);
                }

                return _this2;
              }

              var _proto2 = Sequence.prototype;

              _proto2.initWithTwoActions = function initWithTwoActions(actionOne, actionTwo) {
                if (!actionOne || !actionTwo) {
                  errorID(1025);
                  return false;
                }

                var durationOne = actionOne._duration;
                var durationTwo = actionTwo._duration;
                durationOne *= actionOne._repeatMethod ? actionOne._timesForRepeat : 1;
                durationTwo *= actionTwo._repeatMethod ? actionTwo._timesForRepeat : 1;
                var d = durationOne + durationTwo;
                this.initWithDuration(d);
                this._actions[0] = actionOne;
                this._actions[1] = actionTwo;
                return true;
              };

              _proto2.clone = function clone() {
                var action = new Sequence();

                this._cloneDecoration(action);

                action.initWithTwoActions(this._actions[0].clone(), this._actions[1].clone());
                return action;
              };

              _proto2.startWithTarget = function startWithTarget(target) {
                ActionInterval.prototype.startWithTarget.call(this, target);
                this._split = this._actions[0]._duration / this._duration;
                this._split *= this._actions[0]._repeatMethod ? this._actions[0]._timesForRepeat : 1;
                this._last = -1;
              };

              _proto2.stop = function stop() {
                if (this._last !== -1) this._actions[this._last].stop();
                Action.prototype.stop.call(this);
              };

              _proto2.update = function update(dt) {
                var new_t;
                var found = 0;
                var locSplit = this._split;
                var locActions = this._actions;
                var locLast = this._last;
                var actionFound;
                dt = this._computeEaseTime(dt);

                if (dt < locSplit) {
                  new_t = locSplit !== 0 ? dt / locSplit : 1;

                  if (found === 0 && locLast === 1 && this._reversed) {
                    locActions[1].update(0);
                    locActions[1].stop();
                  }
                } else {
                  found = 1;
                  new_t = locSplit === 1 ? 1 : (dt - locSplit) / (1 - locSplit);

                  if (locLast === -1) {
                    locActions[0].startWithTarget(this.target);
                    locActions[0].update(1);
                    locActions[0].stop();
                  }

                  if (locLast === 0) {
                    locActions[0].update(1);
                    locActions[0].stop();
                  }
                }

                actionFound = locActions[found];
                if (locLast === found && actionFound.isDone()) return;
                if (locLast !== found) actionFound.startWithTarget(this.target);
                new_t *= actionFound._timesForRepeat;
                actionFound.update(new_t > 1 ? new_t % 1 : new_t);
                this._last = found;
              };

              _proto2.reverse = function reverse() {
                var action = Sequence._actionOneTwo(this._actions[1].reverse(), this._actions[0].reverse());

                this._cloneDecoration(action);

                this._reverseEaseList(action);

                action._reversed = true;
                return action;
              };

              return Sequence;
            }(ActionInterval);

            Sequence._actionOneTwo = function (actionOne, actionTwo) {
              var sequence = new Sequence();
              sequence.initWithTwoActions(actionOne, actionTwo);
              return sequence;
            };

            function sequence(tempArray) {
              var paramArray = tempArray instanceof Array ? tempArray : arguments;

              if (paramArray.length === 1) {
                errorID(1019);
                return null;
              }

              var last = paramArray.length - 1;
              if (last >= 0 && paramArray[last] == null) logID(1015);
              var result = null;

              if (last >= 0) {
                result = paramArray[0];

                for (var i = 1; i <= last; i++) {
                  if (paramArray[i]) {
                    result = Sequence._actionOneTwo(result, paramArray[i]);
                  }
                }
              }

              return result;
            }
            var Repeat = function (_ActionInterval2) {
              _inheritsLoose(Repeat, _ActionInterval2);

              function Repeat(action, times) {
                var _this3;

                _this3 = _ActionInterval2.call(this) || this;
                _this3._times = 0;
                _this3._total = 0;
                _this3._nextDt = 0;
                _this3._actionInstant = false;
                _this3._innerAction = null;
                times !== undefined && _this3.initWithAction(action, times);
                return _this3;
              }

              var _proto3 = Repeat.prototype;

              _proto3.initWithAction = function initWithAction(action, times) {
                var duration = action._duration * times;

                if (this.initWithDuration(duration)) {
                  this._times = times;
                  this._innerAction = action;

                  if (action instanceof ActionInstant) {
                    this._actionInstant = true;
                    this._times -= 1;
                  }

                  this._total = 0;
                  return true;
                }

                return false;
              };

              _proto3.clone = function clone() {
                var action = new Repeat();

                this._cloneDecoration(action);

                action.initWithAction(this._innerAction.clone(), this._times);
                return action;
              };

              _proto3.startWithTarget = function startWithTarget(target) {
                this._total = 0;
                this._nextDt = this._innerAction._duration / this._duration;
                ActionInterval.prototype.startWithTarget.call(this, target);

                this._innerAction.startWithTarget(target);
              };

              _proto3.stop = function stop() {
                this._innerAction.stop();

                Action.prototype.stop.call(this);
              };

              _proto3.update = function update(dt) {
                dt = this._computeEaseTime(dt);
                var locInnerAction = this._innerAction;
                var locDuration = this._duration;
                var locTimes = this._times;
                var locNextDt = this._nextDt;

                if (dt >= locNextDt) {
                  while (dt > locNextDt && this._total < locTimes) {
                    locInnerAction.update(1);
                    this._total++;
                    locInnerAction.stop();
                    locInnerAction.startWithTarget(this.target);
                    locNextDt += locInnerAction._duration / locDuration;
                    this._nextDt = locNextDt > 1 ? 1 : locNextDt;
                  }

                  if (dt >= 1.0 && this._total < locTimes) {
                    locInnerAction.update(1);
                    this._total++;
                  }

                  if (!this._actionInstant) {
                    if (this._total === locTimes) {
                      locInnerAction.stop();
                    } else {
                      locInnerAction.update(dt - (locNextDt - locInnerAction._duration / locDuration));
                    }
                  }
                } else {
                  locInnerAction.update(dt * locTimes % 1.0);
                }
              };

              _proto3.isDone = function isDone() {
                return this._total === this._times;
              };

              _proto3.reverse = function reverse() {
                var action = new Repeat(this._innerAction.reverse(), this._times);

                this._cloneDecoration(action);

                this._reverseEaseList(action);

                return action;
              };

              _proto3.setInnerAction = function setInnerAction(action) {
                if (this._innerAction !== action) {
                  this._innerAction = action;
                }
              };

              _proto3.getInnerAction = function getInnerAction() {
                return this._innerAction;
              };

              return Repeat;
            }(ActionInterval);
            function repeat$1(action, times) {
              return new Repeat(action, times);
            }
            var RepeatForever = function (_ActionInterval3) {
              _inheritsLoose(RepeatForever, _ActionInterval3);

              function RepeatForever(action) {
                var _this4;

                _this4 = _ActionInterval3.call(this) || this;
                _this4._innerAction = null;
                action && _this4.initWithAction(action);
                return _this4;
              }

              var _proto4 = RepeatForever.prototype;

              _proto4.initWithAction = function initWithAction(action) {
                if (!action) {
                  errorID(1026);
                  return false;
                }

                this._innerAction = action;
                return true;
              };

              _proto4.clone = function clone() {
                var action = new RepeatForever();

                this._cloneDecoration(action);

                action.initWithAction(this._innerAction.clone());
                return action;
              };

              _proto4.startWithTarget = function startWithTarget(target) {
                ActionInterval.prototype.startWithTarget.call(this, target);

                this._innerAction.startWithTarget(target);
              };

              _proto4.step = function step(dt) {
                var locInnerAction = this._innerAction;
                locInnerAction.step(dt);

                if (locInnerAction.isDone()) {
                  locInnerAction.startWithTarget(this.target);
                  locInnerAction.step(locInnerAction.getElapsed() - locInnerAction._duration);
                }
              };

              _proto4.isDone = function isDone() {
                return false;
              };

              _proto4.reverse = function reverse() {
                var action = new RepeatForever(this._innerAction.reverse());

                this._cloneDecoration(action);

                this._reverseEaseList(action);

                return action;
              };

              _proto4.setInnerAction = function setInnerAction(action) {
                if (this._innerAction !== action) {
                  this._innerAction = action;
                }
              };

              _proto4.getInnerAction = function getInnerAction() {
                return this._innerAction;
              };

              return RepeatForever;
            }(ActionInterval);
            function repeatForever(action) {
              return new RepeatForever(action);
            }
            var Spawn = function (_ActionInterval4) {
              _inheritsLoose(Spawn, _ActionInterval4);

              function Spawn(tempArray) {
                var _this5;

                _this5 = _ActionInterval4.call(this) || this;
                _this5._one = null;
                _this5._two = null;
                var paramArray = tempArray instanceof Array ? tempArray : arguments;

                if (paramArray.length === 1) {
                  errorID(1020);
                  return _assertThisInitialized(_this5);
                }

                var last = paramArray.length - 1;
                if (last >= 0 && paramArray[last] == null) logID(1015);

                if (last >= 0) {
                  var prev = paramArray[0];
                  var action1;

                  for (var i = 1; i < last; i++) {
                    if (paramArray[i]) {
                      action1 = prev;
                      prev = Spawn._actionOneTwo(action1, paramArray[i]);
                    }
                  }

                  _this5.initWithTwoActions(prev, paramArray[last]);
                }

                return _this5;
              }

              var _proto5 = Spawn.prototype;

              _proto5.initWithTwoActions = function initWithTwoActions(action1, action2) {
                if (!action1 || !action2) {
                  errorID(1027);
                  return false;
                }

                var ret = false;
                var d1 = action1._duration;
                var d2 = action2._duration;

                if (this.initWithDuration(Math.max(d1, d2))) {
                  this._one = action1;
                  this._two = action2;

                  if (d1 > d2) {
                    this._two = Sequence._actionOneTwo(action2, delayTime(d1 - d2));
                  } else if (d1 < d2) {
                    this._one = Sequence._actionOneTwo(action1, delayTime(d2 - d1));
                  }

                  ret = true;
                }

                return ret;
              };

              _proto5.clone = function clone() {
                var action = new Spawn();

                this._cloneDecoration(action);

                action.initWithTwoActions(this._one.clone(), this._two.clone());
                return action;
              };

              _proto5.startWithTarget = function startWithTarget(target) {
                ActionInterval.prototype.startWithTarget.call(this, target);

                this._one.startWithTarget(target);

                this._two.startWithTarget(target);
              };

              _proto5.stop = function stop() {
                this._one.stop();

                this._two.stop();

                Action.prototype.stop.call(this);
              };

              _proto5.update = function update(dt) {
                dt = this._computeEaseTime(dt);
                if (this._one) this._one.update(dt);
                if (this._two) this._two.update(dt);
              };

              _proto5.reverse = function reverse() {
                var action = Spawn._actionOneTwo(this._one.reverse(), this._two.reverse());

                this._cloneDecoration(action);

                this._reverseEaseList(action);

                return action;
              };

              return Spawn;
            }(ActionInterval);

            Spawn._actionOneTwo = function (action1, action2) {
              var pSpawn = new Spawn();
              pSpawn.initWithTwoActions(action1, action2);
              return pSpawn;
            };

            function spawn(tempArray) {
              var paramArray = tempArray instanceof Array ? tempArray : arguments;

              if (paramArray.length === 1) {
                errorID(1020);
                return null;
              }

              if (paramArray.length > 0 && paramArray[paramArray.length - 1] == null) logID(1015);
              var prev = paramArray[0];

              for (var i = 1; i < paramArray.length; i++) {
                if (paramArray[i] != null) prev = Spawn._actionOneTwo(prev, paramArray[i]);
              }

              return prev;
            }

            var DelayTime = function (_ActionInterval5) {
              _inheritsLoose(DelayTime, _ActionInterval5);

              function DelayTime() {
                return _ActionInterval5.apply(this, arguments) || this;
              }

              var _proto6 = DelayTime.prototype;

              _proto6.update = function update(dt) {};

              _proto6.reverse = function reverse() {
                var action = new DelayTime(this._duration);

                this._cloneDecoration(action);

                this._reverseEaseList(action);

                return action;
              };

              _proto6.clone = function clone() {
                var action = new DelayTime();

                this._cloneDecoration(action);

                action.initWithDuration(this._duration);
                return action;
              };

              return DelayTime;
            }(ActionInterval);

            function delayTime(d) {
              return new DelayTime(d);
            }
            var ReverseTime = function (_ActionInterval6) {
              _inheritsLoose(ReverseTime, _ActionInterval6);

              function ReverseTime(action) {
                var _this6;

                _this6 = _ActionInterval6.call(this) || this;
                _this6._other = null;
                action && _this6.initWithAction(action);
                return _this6;
              }

              var _proto7 = ReverseTime.prototype;

              _proto7.initWithAction = function initWithAction(action) {
                if (!action) {
                  errorID(1028);
                  return false;
                }

                if (action === this._other) {
                  errorID(1029);
                  return false;
                }

                if (ActionInterval.prototype.initWithDuration.call(this, action._duration)) {
                  this._other = action;
                  return true;
                }

                return false;
              };

              _proto7.clone = function clone() {
                var action = new ReverseTime();

                this._cloneDecoration(action);

                action.initWithAction(this._other.clone());
                return action;
              };

              _proto7.startWithTarget = function startWithTarget(target) {
                ActionInterval.prototype.startWithTarget.call(this, target);

                this._other.startWithTarget(target);
              };

              _proto7.update = function update(dt) {
                dt = this._computeEaseTime(dt);
                if (this._other) this._other.update(1 - dt);
              };

              _proto7.reverse = function reverse() {
                return this._other.clone();
              };

              _proto7.stop = function stop() {
                this._other.stop();

                Action.prototype.stop.call(this);
              };

              return ReverseTime;
            }(ActionInterval);
            function reverseTime(action) {
              return new ReverseTime(action);
            }

            function TweenEasinAdapter(easingName) {
              var initialChar = easingName.charAt(0);

              if (/[A-Z]/.test(initialChar)) {
                easingName = easingName.replace(initialChar, initialChar.toLowerCase());
                var arr = easingName.split('-');

                if (arr.length === 2) {
                  var str0 = arr[0];

                  if (str0 === 'linear') {
                    easingName = 'linear';
                  } else {
                    var str1 = arr[1];

                    switch (str0) {
                      case 'quadratic':
                        easingName = "quad" + str1;
                        break;

                      case 'quartic':
                        easingName = "quart" + str1;
                        break;

                      case 'quintic':
                        easingName = "quint" + str1;
                        break;

                      case 'sinusoidal':
                        easingName = "sine" + str1;
                        break;

                      case 'exponential':
                        easingName = "expo" + str1;
                        break;

                      case 'circular':
                        easingName = "circ" + str1;
                        break;

                      default:
                        easingName = str0 + str1;
                        break;
                    }
                  }
                }
              }

              return easingName;
            }

            function TweenOptionChecker(opts) {
              var header = ' [Tween:] ';
              var message = " option is not support in v + " + engineVersion;
              var _opts = opts;

              if (_opts.delay) {
                warn(header + "delay" + message);
              }

              if (_opts.repeat) {
                warn(header + "repeat" + message);
              }

              if (_opts.repeatDelay) {
                warn(header + "repeatDelay" + message);
              }

              if (_opts.interpolation) {
                warn(header + "interpolation" + message);
              }

              if (_opts.onStop) {
                warn(header + "onStop" + message);
              }
            }

            var TweenAction = function (_ActionInterval) {
              _inheritsLoose(TweenAction, _ActionInterval);

              function TweenAction(duration, props, opts) {
                var _this;

                _this = _ActionInterval.call(this) || this;
                _this._opts = void 0;
                _this._props = void 0;
                _this._originProps = void 0;

                if (opts == null) {
                  opts = Object.create(null);
                } else {
                  TweenOptionChecker(opts);

                  if (opts.easing && typeof opts.easing === 'string') {
                    opts.easing = TweenEasinAdapter(opts.easing);
                  }

                  if (!opts.progress) {
                    opts.progress = _this.progress;
                  }

                  if (opts.easing && typeof opts.easing === 'string') {
                    var easingName = opts.easing;
                    opts.easing = easing[easingName];

                    if (!opts.easing) {
                      warnID(1031, easingName);
                    }
                  }
                }

                _this._opts = opts;
                _this._props = Object.create(null);

                for (var name in props) {
                  if (!props.hasOwnProperty(name)) continue;
                  var value = props[name];

                  if (typeof value === 'function') {
                    value = value();
                  }

                  if (value == null || typeof value === 'string') continue;
                  var customEasing = void 0;
                  var progress = void 0;

                  if (value.value !== undefined && (value.easing || value.progress)) {
                    if (typeof value.easing === 'string') {
                      customEasing = easing[value.easing];
                      if (!customEasing) warnID(1031, value.easing);
                    } else {
                      customEasing = value.easing;
                    }

                    progress = value.progress;
                    value = value.value;
                  }

                  var prop = Object.create(null);
                  prop.value = value;
                  prop.easing = customEasing;
                  prop.progress = progress;
                  _this._props[name] = prop;
                }

                _this._originProps = props;

                _this.initWithDuration(duration);

                return _this;
              }

              var _proto = TweenAction.prototype;

              _proto.clone = function clone() {
                var action = new TweenAction(this._duration, this._originProps, this._opts);

                this._cloneDecoration(action);

                return action;
              };

              _proto.startWithTarget = function startWithTarget(target) {
                ActionInterval.prototype.startWithTarget.call(this, target);
                var relative = !!this._opts.relative;
                var props = this._props;

                for (var property in props) {
                  var _t = target[property];

                  if (_t === undefined) {
                    continue;
                  }

                  var prop = props[property];
                  var value = prop.value;

                  if (typeof _t === 'number') {
                    prop.start = _t;
                    prop.current = _t;
                    prop.end = relative ? _t + value : value;
                  } else if (typeof _t === 'object') {
                    if (prop.start == null) {
                      prop.start = {};
                      prop.current = {};
                      prop.end = {};
                    }

                    for (var k in value) {
                      if (isNaN(_t[k])) continue;
                      prop.start[k] = _t[k];
                      prop.current[k] = _t[k];
                      prop.end[k] = relative ? _t[k] + value[k] : value[k];
                    }
                  }
                }

                if (this._opts.onStart) {
                  this._opts.onStart(this.target);
                }
              };

              _proto.update = function update(t) {
                var target = this.target;
                if (!target) return;
                var props = this._props;
                var opts = this._opts;
                var easingTime = t;
                if (opts.easing) easingTime = opts.easing(t);
                var progress = opts.progress;

                for (var name in props) {
                  var prop = props[name];
                  var time = prop.easing ? prop.easing(t) : easingTime;
                  var interpolation = prop.progress ? prop.progress : progress;
                  var start = prop.start;
                  var end = prop.end;

                  if (typeof start === 'number') {
                    prop.current = interpolation(start, end, prop.current, time);
                  } else if (typeof start === 'object') {
                    for (var k in start) {
                      prop.current[k] = interpolation(start[k], end[k], prop.current[k], time);
                    }
                  }

                  target[name] = prop.current;
                }

                if (opts.onUpdate) {
                  opts.onUpdate(this.target, t);
                }

                if (t === 1 && opts.onComplete) {
                  opts.onComplete(this.target);
                }
              };

              _proto.progress = function progress(start, end, current, t) {
                return current = start + (end - start) * t;
              };

              return TweenAction;
            }(ActionInterval);

            var SetAction = function (_ActionInstant) {
              _inheritsLoose(SetAction, _ActionInstant);

              function SetAction(props) {
                var _this;

                _this = _ActionInstant.call(this) || this;
                _this._props = void 0;
                _this._props = {};
                props !== undefined && _this.init(props);
                return _this;
              }

              var _proto = SetAction.prototype;

              _proto.init = function init(props) {
                for (var name in props) {
                  this._props[name] = props[name];
                }

                return true;
              };

              _proto.update = function update() {
                var props = this._props;
                var target = this.target;

                for (var name in props) {
                  target[name] = props[name];
                }
              };

              _proto.clone = function clone() {
                var action = new SetAction();
                action.init(this._props);
                return action;
              };

              return SetAction;
            }(ActionInstant);

            var Tween = exports('Tween', function () {
              function Tween(target) {
                this._actions = [];
                this._finalAction = null;
                this._target = null;
                this._tag = Action.TAG_INVALID;
                this._target = target === undefined ? null : target;
              }

              var _proto = Tween.prototype;

              _proto.tag = function tag(_tag) {
                this._tag = _tag;
                return this;
              };

              _proto.then = function then(other) {
                if (other instanceof Action) {
                  this._actions.push(other.clone());
                } else {
                  this._actions.push(other._union());
                }

                return this;
              };

              _proto.target = function target(_target) {
                this._target = _target;
                return this;
              };

              _proto.start = function start() {
                if (!this._target) {
                  warn('Please set target to tween first');
                  return this;
                }

                if (this._finalAction) {
                  TweenSystem.instance.ActionManager.removeAction(this._finalAction);
                }

                this._finalAction = this._union();

                this._finalAction.setTag(this._tag);

                TweenSystem.instance.ActionManager.addAction(this._finalAction, this._target, false);
                return this;
              };

              _proto.stop = function stop() {
                if (this._finalAction) {
                  TweenSystem.instance.ActionManager.removeAction(this._finalAction);
                }

                return this;
              };

              _proto.clone = function clone(target) {
                var action = this._union();

                return tween(target).then(action.clone());
              };

              _proto.union = function union() {
                var action = this._union();

                this._actions.length = 0;

                this._actions.push(action);

                return this;
              };

              _proto.to = function to(duration, props, opts) {
                opts = opts || Object.create(null);
                opts.relative = false;
                var action = new TweenAction(duration, props, opts);

                this._actions.push(action);

                return this;
              };

              _proto.by = function by(duration, props, opts) {
                opts = opts || Object.create(null);
                opts.relative = true;
                var action = new TweenAction(duration, props, opts);

                this._actions.push(action);

                return this;
              };

              _proto.set = function set(props) {
                var action = new SetAction(props);

                this._actions.push(action);

                return this;
              };

              _proto.delay = function delay(duration) {
                var action = delayTime(duration);

                this._actions.push(action);

                return this;
              };

              _proto.call = function call(callback) {
                var action = callFunc(callback);

                this._actions.push(action);

                return this;
              };

              _proto.sequence = function sequence() {
                var action = Tween._wrappedSequence.apply(Tween, arguments);

                this._actions.push(action);

                return this;
              };

              _proto.parallel = function parallel() {
                var action = Tween._wrappedParallel.apply(Tween, arguments);

                this._actions.push(action);

                return this;
              };

              _proto.repeat = function repeat(repeatTimes, embedTween) {
                if (repeatTimes == Infinity) {
                  return this.repeatForever(embedTween);
                }

                var actions = this._actions;
                var action;

                if (embedTween instanceof Tween) {
                  action = embedTween._union();
                } else {
                  action = actions.pop();
                }

                actions.push(repeat$1(action, repeatTimes));
                return this;
              };

              _proto.repeatForever = function repeatForever$1(embedTween) {
                var actions = this._actions;
                var action;

                if (embedTween instanceof Tween) {
                  action = embedTween._union();
                } else {
                  action = actions.pop();
                }

                actions.push(repeatForever(action));
                return this;
              };

              _proto.reverseTime = function reverseTime$1(embedTween) {
                var actions = this._actions;
                var action;

                if (embedTween instanceof Tween) {
                  action = embedTween._union();
                } else {
                  action = actions.pop();
                }

                actions.push(reverseTime(action));
                return this;
              };

              _proto.hide = function hide$1() {
                var action = hide();

                this._actions.push(action);

                return this;
              };

              _proto.show = function show$1() {
                var action = show();

                this._actions.push(action);

                return this;
              };

              _proto.removeSelf = function removeSelf$1() {
                var action = removeSelf(false);

                this._actions.push(action);

                return this;
              };

              Tween.stopAll = function stopAll() {
                TweenSystem.instance.ActionManager.removeAllActions();
              };

              Tween.stopAllByTag = function stopAllByTag(tag, target) {
                TweenSystem.instance.ActionManager.removeActionByTag(tag, target);
              };

              Tween.stopAllByTarget = function stopAllByTarget(target) {
                TweenSystem.instance.ActionManager.removeAllActionsFromTarget(target);
              };

              _proto._union = function _union() {
                var actions = this._actions;
                var action;

                if (actions.length === 1) {
                  action = actions[0];
                } else {
                  action = sequence(actions);
                }

                return action;
              };

              _proto._destroy = function _destroy() {
                this.stop();
              };

              Tween._wrappedSequence = function _wrappedSequence() {
                var tmp_args = Tween._tmp_args;
                tmp_args.length = 0;

                for (var l = arguments.length, i = 0; i < l; i++) {
                  var arg = tmp_args[i] = i < 0 || arguments.length <= i ? undefined : arguments[i];

                  if (arg instanceof Tween) {
                    tmp_args[i] = arg._union();
                  }
                }

                return sequence.apply(sequence, tmp_args);
              };

              Tween._wrappedParallel = function _wrappedParallel() {
                var tmp_args = Tween._tmp_args;
                tmp_args.length = 0;

                for (var l = arguments.length, i = 0; i < l; i++) {
                  var arg = tmp_args[i] = i < 0 || arguments.length <= i ? undefined : arguments[i];

                  if (arg instanceof Tween) {
                    tmp_args[i] = arg._union();
                  }
                }

                return spawn.apply(spawn, tmp_args);
              };

              return Tween;
            }());
            Tween._tmp_args = [];
            legacyCC.Tween = Tween;
            function tween(target) {
              return new Tween(target);
            }
            legacyCC.tween = tween;
            function tweenUtil(target) {
              warn('tweenUtil\' is deprecated, please use \'tween\' instead ');
              return new Tween(target);
            }
            legacyCC.tweenUtil = tweenUtil;

            var Orientation$1;

            (function (Orientation) {
              Orientation[Orientation["ORTHO"] = 0] = "ORTHO";
              Orientation[Orientation["HEX"] = 1] = "HEX";
              Orientation[Orientation["ISO"] = 2] = "ISO";
            })(Orientation$1 || (Orientation$1 = {}));

            ccenum(Orientation$1);
            var Property;

            (function (Property) {
              Property[Property["NONE"] = 0] = "NONE";
              Property[Property["MAP"] = 1] = "MAP";
              Property[Property["LAYER"] = 2] = "LAYER";
              Property[Property["OBJECTGROUP"] = 3] = "OBJECTGROUP";
              Property[Property["OBJECT"] = 4] = "OBJECT";
              Property[Property["TILE"] = 5] = "TILE";
            })(Property || (Property = {}));

            ccenum(Property);
            var TileFlag;

            (function (TileFlag) {
              TileFlag[TileFlag["HORIZONTAL"] = 2147483648] = "HORIZONTAL";
              TileFlag[TileFlag["VERTICAL"] = 1073741824] = "VERTICAL";
              TileFlag[TileFlag["DIAGONAL"] = 536870912] = "DIAGONAL";
              TileFlag[TileFlag["FLIPPED_ALL"] = 4026531840] = "FLIPPED_ALL";
              TileFlag[TileFlag["FLIPPED_MASK"] = 268435455] = "FLIPPED_MASK";
            })(TileFlag || (TileFlag = {}));

            ccenum(TileFlag);
            var StaggerAxis;

            (function (StaggerAxis) {
              StaggerAxis[StaggerAxis["STAGGERAXIS_X"] = 0] = "STAGGERAXIS_X";
              StaggerAxis[StaggerAxis["STAGGERAXIS_Y"] = 1] = "STAGGERAXIS_Y";
            })(StaggerAxis || (StaggerAxis = {}));

            ccenum(StaggerAxis);
            var StaggerIndex;

            (function (StaggerIndex) {
              StaggerIndex[StaggerIndex["STAGGERINDEX_ODD"] = 0] = "STAGGERINDEX_ODD";
              StaggerIndex[StaggerIndex["STAGGERINDEX_EVEN"] = 1] = "STAGGERINDEX_EVEN";
            })(StaggerIndex || (StaggerIndex = {}));

            ccenum(StaggerIndex);
            var RenderOrder;

            (function (RenderOrder) {
              RenderOrder[RenderOrder["RightDown"] = 0] = "RightDown";
              RenderOrder[RenderOrder["RightUp"] = 1] = "RightUp";
              RenderOrder[RenderOrder["LeftDown"] = 2] = "LeftDown";
              RenderOrder[RenderOrder["LeftUp"] = 3] = "LeftUp";
            })(RenderOrder || (RenderOrder = {}));

            ccenum(RenderOrder);
            var TMXObjectType;

            (function (TMXObjectType) {
              TMXObjectType[TMXObjectType["RECT"] = 0] = "RECT";
              TMXObjectType[TMXObjectType["ELLIPSE"] = 1] = "ELLIPSE";
              TMXObjectType[TMXObjectType["POLYGON"] = 2] = "POLYGON";
              TMXObjectType[TMXObjectType["POLYLINE"] = 3] = "POLYLINE";
              TMXObjectType[TMXObjectType["IMAGE"] = 4] = "IMAGE";
              TMXObjectType[TMXObjectType["TEXT"] = 5] = "TEXT";
            })(TMXObjectType || (TMXObjectType = {}));

            ccenum(TMXObjectType);
            var TMXTilesetInfo = function () {
              function TMXTilesetInfo() {
                this.name = '';
                this.firstGid = 0;
                this.spacing = 0;
                this.margin = 0;
                this.sourceImage = void 0;
                this.imageName = null;
                this.imageSize = new Size(0, 0);
                this.tileOffset = new Vec2(0, 0);
                this._tileSize = new Size(0, 0);
                this.collection = false;
              }

              var _proto = TMXTilesetInfo.prototype;

              _proto.rectForGID = function rectForGID(gid_, result) {
                var rect = result || new Rect(0, 0, 0, 0);
                rect.width = this._tileSize.width;
                rect.height = this._tileSize.height;
                var gid = gid_;
                gid &= TileFlag.FLIPPED_MASK;
                gid -= this.firstGid;
                var 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;
              };

              return TMXTilesetInfo;
            }();
            var TMXObjectGroupInfo = function () {
              function TMXObjectGroupInfo() {
                this.properties = {};
                this.name = '';
                this.objects = [];
                this.visible = true;
                this.opacity = 0;
                this.color = new Color(255, 255, 255, 255);
                this.offset = new Vec2(0, 0);
                this.draworder = 'topdown';
                this.tintColor = null;
              }

              var _proto2 = TMXObjectGroupInfo.prototype;

              _proto2.getProperties = function getProperties() {
                return this.properties;
              };

              _proto2.setProperties = function setProperties(value) {
                this.properties = value;
              };

              return TMXObjectGroupInfo;
            }();
            var TMXLayerInfo = function () {
              function TMXLayerInfo() {
                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;
              }

              var _proto3 = TMXLayerInfo.prototype;

              _proto3.getProperties = function getProperties() {
                return this.properties;
              };

              _proto3.setProperties = function setProperties(value) {
                this.properties = value;
              };

              return TMXLayerInfo;
            }();
            TMXLayerInfo.ATTRIB_NONE = 1 << 0;
            TMXLayerInfo.ATTRIB_BASE64 = 1 << 1;
            TMXLayerInfo.ATTRIB_GZIP = 1 << 2;
            TMXLayerInfo.ATTRIB_ZLIB = 1 << 3;
            var TMXImageLayerInfo = function TMXImageLayerInfo() {
              this.name = '';
              this.visible = true;
              this.width = 0;
              this.height = 0;
              this.offset = new Vec2(0, 0);
              this.opacity = 0;
              this.trans = new Color(255, 255, 255, 255);
              this.sourceImage = void 0;
              this.tintColor = null;
            };

            function uint8ArrayToUint32Array(uint8Arr) {
              if (uint8Arr.length % 4 !== 0) return null;
              var arrLen = uint8Arr.length / 4;
              var retArr = window.Uint32Array ? new Uint32Array(arrLen) : [];

              for (var i = 0; i < arrLen; i++) {
                var 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) {
              var hAlign = Label.HorizontalAlign;

              switch (value) {
                case 'center':
                  return hAlign.CENTER;

                case 'right':
                  return hAlign.RIGHT;

                default:
                  return hAlign.LEFT;
              }
            }

            function strToVAlign(value) {
              var 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(0, 0, 0, 255);
              }

              value = value.indexOf('#') !== -1 ? value.substring(1) : value;

              if (value.length === 8) {
                var a = parseInt(value.substr(0, 2), 16) || 255;
                var r = parseInt(value.substr(2, 2), 16) || 0;
                var g = parseInt(value.substr(4, 2), 16) || 0;
                var b = parseInt(value.substr(6, 2), 16) || 0;
                return new Color(r, g, b, a);
              } else {
                var _r = parseInt(value.substr(0, 2), 16) || 0;

                var _g = parseInt(value.substr(2, 2), 16) || 0;

                var _b = parseInt(value.substr(4, 2), 16) || 0;

                return new Color(_r, _g, _b, 255);
              }
            }

            function getPropertyList(node, map) {
              var res = [];
              var properties = node.getElementsByTagName('properties');

              for (var i = 0; i < properties.length; ++i) {
                var property = properties[i].getElementsByTagName('property');

                for (var j = 0; j < property.length; ++j) {
                  res.push(property[j]);
                }
              }

              map = map || {};

              for (var _i = 0; _i < res.length; _i++) {
                var element = res[_i];
                var name = element.getAttribute('name');
                var type = element.getAttribute('type') || 'string';
                var 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;
            }

            var TMXMapInfo = function () {
              function TMXMapInfo(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 = RenderOrder.RightDown;
                this._supportVersion = [1, 4, 0];
                this._objectGroups = [];
                this._allChildren = [];
                this._mapSize = new Size(0, 0);
                this._tileSize = new Size(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);
              }

              var _proto = TMXMapInfo.prototype;

              _proto.getOrientation = function getOrientation() {
                return this.orientation;
              };

              _proto.setOrientation = function setOrientation(value) {
                this.orientation = value;
              };

              _proto.getStaggerAxis = function getStaggerAxis() {
                return this._staggerAxis;
              };

              _proto.setStaggerAxis = function setStaggerAxis(value) {
                this._staggerAxis = value;
              };

              _proto.getStaggerIndex = function getStaggerIndex() {
                return this._staggerIndex;
              };

              _proto.setStaggerIndex = function setStaggerIndex(value) {
                this._staggerIndex = value;
              };

              _proto.getHexSideLength = function getHexSideLength() {
                return this._hexSideLength;
              };

              _proto.setHexSideLength = function setHexSideLength(value) {
                this._hexSideLength = value;
              };

              _proto.getMapSize = function getMapSize() {
                return new Size(this._mapSize.width, this._mapSize.height);
              };

              _proto.setMapSize = function setMapSize(value) {
                this._mapSize.width = value.width;
                this._mapSize.height = value.height;
              };

              _proto.getTileSize = function getTileSize() {
                return new Size(this._tileSize.width, this._tileSize.height);
              };

              _proto.setTileSize = function setTileSize(value) {
                this._tileSize.width = value.width;
                this._tileSize.height = value.height;
              };

              _proto.getLayers = function getLayers() {
                return this._layers;
              };

              _proto.setLayers = function setLayers(value) {
                this._allChildren.push(value);

                this._layers.push(value);
              };

              _proto.getImageLayers = function getImageLayers() {
                return this._imageLayers;
              };

              _proto.setImageLayers = function setImageLayers(value) {
                this._allChildren.push(value);

                this._imageLayers.push(value);
              };

              _proto.getTilesets = function getTilesets() {
                return this._tilesets;
              };

              _proto.setTilesets = function setTilesets(value) {
                this._tilesets.push(value);
              };

              _proto.getObjectGroups = function getObjectGroups() {
                return this._objectGroups;
              };

              _proto.setObjectGroups = function setObjectGroups(value) {
                this._allChildren.push(value);

                this._objectGroups.push(value);
              };

              _proto.getAllChildren = function getAllChildren() {
                return this._allChildren;
              };

              _proto.getParentElement = function getParentElement() {
                return this.parentElement;
              };

              _proto.setParentElement = function setParentElement(value) {
                this.parentElement = value;
              };

              _proto.getParentGID = function getParentGID() {
                return this.parentGID;
              };

              _proto.setParentGID = function setParentGID(value) {
                this.parentGID = value;
              };

              _proto.getLayerAttribs = function getLayerAttribs() {
                return this.layerAttrs;
              };

              _proto.setLayerAttribs = function setLayerAttribs(value) {
                this.layerAttrs = value;
              };

              _proto.getStoringCharacters = function getStoringCharacters() {
                return this.storingCharacters;
              };

              _proto.setStoringCharacters = function setStoringCharacters(value) {
                this.storingCharacters = value;
              };

              _proto.getProperties = function getProperties() {
                return this.properties;
              };

              _proto.setProperties = function setProperties(value) {
                this.properties = value;
              };

              _proto.initWithXML = function 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);
              };

              _proto.parseXMLString = function parseXMLString(xmlStr, tilesetFirstGid) {
                var parser = new SAXParser();
                var mapXML = parser.parse(xmlStr);
                var i;
                var map = mapXML.documentElement;
                var orientationStr = map.getAttribute('orientation');
                var staggerAxisStr = map.getAttribute('staggeraxis');
                var staggerIndexStr = map.getAttribute('staggerindex');
                var hexSideLengthStr = map.getAttribute('hexsidelength');
                var renderorderStr = map.getAttribute('renderorder');
                var version = map.getAttribute('version') || '1.0.0';

                if (map.nodeName === 'map') {
                  var versionArr = version.split('.');
                  var supportVersion = this._supportVersion;

                  for (i = 0; i < supportVersion.length; i++) {
                    var v = parseInt(versionArr[i]) || 0;
                    var sv = supportVersion[i];

                    if (sv < v) {
                      logID(7216, version);
                      break;
                    }
                  }

                  if (orientationStr === 'orthogonal') this.orientation = Orientation$1.ORTHO;else if (orientationStr === 'isometric') this.orientation = Orientation$1.ISO;else if (orientationStr === 'hexagonal') this.orientation = Orientation$1.HEX;else if (orientationStr !== null) logID(7217, orientationStr);

                  if (renderorderStr === 'right-up') {
                    this.renderOrder = RenderOrder.RightUp;
                  } else if (renderorderStr === 'left-up') {
                    this.renderOrder = RenderOrder.LeftUp;
                  } else if (renderorderStr === 'left-down') {
                    this.renderOrder = RenderOrder.LeftDown;
                  } else {
                    this.renderOrder = RenderOrder.RightDown;
                  }

                  if (staggerAxisStr === 'x') {
                    this.setStaggerAxis(StaggerAxis.STAGGERAXIS_X);
                  } else if (staggerAxisStr === 'y') {
                    this.setStaggerAxis(StaggerAxis.STAGGERAXIS_Y);
                  }

                  if (staggerIndexStr === 'odd') {
                    this.setStaggerIndex(StaggerIndex.STAGGERINDEX_ODD);
                  } else if (staggerIndexStr === 'even') {
                    this.setStaggerIndex(StaggerIndex.STAGGERINDEX_EVEN);
                  }

                  if (hexSideLengthStr) {
                    this.setHexSideLength(parseFloat(hexSideLengthStr));
                  }

                  var mapSize = new Size(0, 0);
                  mapSize.width = parseFloat(map.getAttribute('width'));
                  mapSize.height = parseFloat(map.getAttribute('height'));
                  this.setMapSize(mapSize);
                  mapSize = new Size(0, 0);
                  mapSize.width = parseFloat(map.getAttribute('tilewidth'));
                  mapSize.height = parseFloat(map.getAttribute('tileheight'));
                  this.setTileSize(mapSize);
                  this.properties = getPropertyList(map);
                }

                var tilesets = map.getElementsByTagName('tileset');

                if (map.nodeName !== 'map') {
                  tilesets = [];
                  tilesets.push(map);
                }

                for (i = 0; i < tilesets.length; i++) {
                  var curTileset = tilesets[i];
                  var tsxName = curTileset.getAttribute('source');

                  if (tsxName) {
                    var currentFirstGID = parseInt(curTileset.getAttribute('firstgid'));
                    var tsxXmlString = this._tsxContentMap[tsxName];

                    if (tsxXmlString) {
                      this.parseXMLString(tsxXmlString, currentFirstGID);
                    }
                  } else {
                    var images = curTileset.getElementsByTagName('image');
                    var collection = images.length > 1;
                    var firstImage = images[0];
                    var firstImageName = firstImage.getAttribute('source');
                    firstImageName = firstImageName.replace(/\\/g, '/');
                    var tiles = curTileset.getElementsByTagName('tile');
                    var tileCount = tiles && tiles.length || 1;
                    var tile = null;
                    var tilesetName = curTileset.getAttribute('name') || '';
                    var tilesetSpacing = parseInt(curTileset.getAttribute('spacing')) || 0;
                    var tilesetMargin = parseInt(curTileset.getAttribute('margin')) || 0;
                    var fgid = tilesetFirstGid || parseInt(curTileset.getAttribute('firstgid')) || 0;
                    var tilesetSize = new Size(0, 0);
                    tilesetSize.width = parseFloat(curTileset.getAttribute('tilewidth'));
                    tilesetSize.height = parseFloat(curTileset.getAttribute('tileheight'));
                    var curTileOffset = curTileset.getElementsByTagName('tileoffset')[0];
                    var tileOffsetX = 0;
                    var tileOffsetY = 0;

                    if (curTileOffset) {
                      tileOffsetX = parseFloat(curTileOffset.getAttribute('x')) || 0;
                      tileOffsetY = parseFloat(curTileOffset.getAttribute('y')) || 0;
                    }

                    var tileset = null;

                    for (var tileIdx = 0; tileIdx < tileCount; tileIdx++) {
                      var curImage = images[tileIdx] ? images[tileIdx] : firstImage;
                      if (!curImage) continue;
                      var curImageName = curImage.getAttribute('source');
                      curImageName = curImageName.replace(/\\/g, '/');

                      if (!tileset || collection) {
                        tileset = new TMXTilesetInfo();
                        tileset.name = tilesetName;
                        tileset.firstGid = fgid & TileFlag.FLIPPED_MASK;
                        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) {
                            var nameWithPostfix = TMXMapInfo.getNameWithPostfix(curImageName);
                            tileset.imageName = nameWithPostfix;
                            tileset.sourceImage = this._spriteFrameMap[nameWithPostfix];

                            if (!tileset.sourceImage) {
                              var shortName = TMXMapInfo.getShortName(curImageName);
                              tileset.imageName = shortName;
                              tileset.sourceImage = this._spriteFrameMap[shortName];

                              if (!tileset.sourceImage) {
                                console.error("[error]: " + shortName + " not find in [" + Object.keys(this._spriteFrameMap).join(', ') + "]");
                                errorID(7221, curImageName);
                                console.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);
                      var tileImages = tile.getElementsByTagName('image');

                      if (tileImages && tileImages.length > 0) {
                        var image = tileImages[0];
                        var 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;
                        tileset._tileSize.width = tileset.imageSize.width;
                        tileset._tileSize.height = tileset.imageSize.height;
                        tileset.sourceImage = this._spriteFrameMap[imageName];

                        if (!tileset.sourceImage) {
                          var _nameWithPostfix = TMXMapInfo.getNameWithPostfix(imageName);

                          tileset.imageName = _nameWithPostfix;
                          tileset.sourceImage = this._spriteFrameMap[_nameWithPostfix];

                          if (!tileset.sourceImage) {
                            var _shortName = TMXMapInfo.getShortName(imageName);

                            tileset.imageName = _shortName;
                            tileset.sourceImage = this._spriteFrameMap[_shortName];

                            if (!tileset.sourceImage) {
                              errorID(7221, imageName);
                              console.warn("Please try asset type of " + imageName + " to 'sprite-frame'");
                            }
                          }
                        }

                        tileset.firstGid = this.parentGID & TileFlag.FLIPPED_MASK;
                      }

                      var pid = (TileFlag.FLIPPED_MASK & this.parentGID) >>> 0;

                      this._tileProperties.set(pid, getPropertyList(tile));

                      var animations = tile.getElementsByTagName('animation');

                      if (animations && animations.length > 0) {
                        var animation = animations[0];
                        var framesData = animation.getElementsByTagName('frame');
                        var animationProp = {
                          frames: [],
                          dt: 0,
                          frameIdx: 0
                        };

                        this._tileAnimations.set(pid, animationProp);

                        var frames = animationProp.frames;

                        for (var frameIdx = 0; frameIdx < framesData.length; frameIdx++) {
                          var frame = framesData[frameIdx];
                          var tileid = fgid + (parseInt(frame.getAttribute('tileid')) || 0);
                          var duration = parseFloat(frame.getAttribute('duration')) || 0;
                          frames.push({
                            tileid: tileid,
                            duration: duration / 1000,
                            grid: null
                          });
                        }
                      }
                    }
                  }
                }

                var childNodes = map.childNodes;

                for (i = 0; i < childNodes.length; i++) {
                  var childNode = childNodes[i];

                  if (this._shouldIgnoreNode(childNode)) {
                    continue;
                  }

                  if (childNode.nodeName === 'imagelayer') {
                    var imageLayer = this._parseImageLayer(childNode);

                    if (imageLayer) {
                      this.setImageLayers(imageLayer);
                    }
                  }

                  if (childNode.nodeName === 'layer') {
                    var layer = this._parseLayer(childNode);

                    this.setLayers(layer);
                  }

                  if (childNode.nodeName === 'objectgroup') {
                    var objectGroup = this._parseObjectGroup(childNode);

                    this.setObjectGroups(objectGroup);
                  }
                }

                return map;
              };

              _proto._shouldIgnoreNode = function _shouldIgnoreNode(node) {
                return node.nodeType === 3 || node.nodeType === 8 || node.nodeType === 4;
              };

              _proto._parseImageLayer = function _parseImageLayer(selLayer) {
                var datas = selLayer.getElementsByTagName('image');
                if (!datas || datas.length === 0) return null;
                var imageLayer = new TMXImageLayerInfo();
                imageLayer.name = selLayer.getAttribute('name');
                imageLayer.offset.x = parseFloat(selLayer.getAttribute('offsetx')) || 0;
                imageLayer.offset.y = parseFloat(selLayer.getAttribute('offsety')) || 0;
                var visible = selLayer.getAttribute('visible');
                imageLayer.visible = !(visible === '0');
                var opacity = selLayer.getAttribute('opacity');
                imageLayer.opacity = opacity ? Math.round(255 * parseFloat(opacity)) : 255;
                var tintColor = selLayer.getAttribute('tintcolor');
                imageLayer.tintColor = tintColor ? strToColor(tintColor) : null;
                var data = datas[0];
                var 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);
                  console.warn("Please try asset type of " + source + " to 'sprite-frame'");
                  return null;
                }

                return imageLayer;
              };

              _proto._parseLayer = function _parseLayer(selLayer) {
                var data = selLayer.getElementsByTagName('data')[0];
                var layer = new TMXLayerInfo();
                layer.name = selLayer.getAttribute('name');
                var layerSize = new Size(0, 0);
                layerSize.width = parseFloat(selLayer.getAttribute('width'));
                layerSize.height = parseFloat(selLayer.getAttribute('height'));
                layer.layerSize = layerSize;
                var visible = selLayer.getAttribute('visible');
                layer.visible = !(visible === '0');
                var 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);
                var tintColor = selLayer.getAttribute('tintcolor');
                layer.tintColor = tintColor ? strToColor(tintColor) : null;
                var nodeValue = '';

                for (var j = 0; j < data.childNodes.length; j++) {
                  nodeValue += data.childNodes[j].nodeValue;
                }

                nodeValue = nodeValue.trim();
                var compression = data.getAttribute('compression');
                var encoding = data.getAttribute('encoding');

                if (compression && compression !== 'gzip' && compression !== 'zlib') {
                  logID(7218);
                  return null;
                }

                var tiles;

                switch (compression) {
                  case 'gzip':
                    tiles = codec.unzipBase64AsArray(nodeValue, 4);
                    break;

                  case 'zlib':
                    {
                      var 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 = [];
                      var csvTiles = nodeValue.split(',');

                      for (var csvIdx = 0; csvIdx < csvTiles.length; csvIdx++) {
                        tiles.push(parseInt(csvTiles[csvIdx]));
                      }
                    } else {
                      var selDataTiles = data.getElementsByTagName('tile');
                      tiles = [];

                      for (var 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;
              };

              _proto._parseObjectGroup = function _parseObjectGroup(selGroup) {
                var objectGroup = new TMXObjectGroupInfo();
                objectGroup.name = selGroup.getAttribute('name') || '';
                objectGroup.offset = new Vec2(parseFloat(selGroup.getAttribute('offsetx')), parseFloat(selGroup.getAttribute('offsety')));
                var opacity = selGroup.getAttribute('opacity');
                if (opacity) objectGroup.opacity = Math.round(255 * parseFloat(opacity));else objectGroup.opacity = 255;
                var tintColor = selGroup.getAttribute('tintcolor');
                objectGroup.tintColor = tintColor ? strToColor(tintColor) : null;
                var visible = selGroup.getAttribute('visible');
                if (visible && parseInt(visible) === 0) objectGroup.visible = false;
                var color = selGroup.getAttribute('color');
                if (color) objectGroup.color.fromHEX(color);
                var draworder = selGroup.getAttribute('draworder');
                if (draworder) objectGroup.draworder = draworder;
                objectGroup.setProperties(getPropertyList(selGroup));
                var objects = selGroup.getElementsByTagName('object');

                if (objects) {
                  for (var j = 0; j < objects.length; j++) {
                    var selObj = objects[j];
                    var 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;
                    getPropertyList(selObj, objectProp);
                    var visibleAttr = selObj.getAttribute('visible');
                    objectProp.visible = !(visibleAttr && parseInt(visibleAttr) === 0);
                    var texts = selObj.getElementsByTagName('text');

                    if (texts && texts.length > 0) {
                      var text = texts[0];
                      objectProp.type = TMXObjectType.TEXT;
                      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;
                    }

                    var gid = selObj.getAttribute('gid');

                    if (gid) {
                      objectProp.gid = parseInt(gid);
                      objectProp.type = TMXObjectType.IMAGE;
                    }

                    var ellipse = selObj.getElementsByTagName('ellipse');

                    if (ellipse && ellipse.length > 0) {
                      objectProp.type = TMXObjectType.ELLIPSE;
                    }

                    var polygonProps = selObj.getElementsByTagName('polygon');

                    if (polygonProps && polygonProps.length > 0) {
                      objectProp.type = TMXObjectType.POLYGON;
                      var selPgPointStr = polygonProps[0].getAttribute('points');
                      if (selPgPointStr) objectProp.points = this._parsePointsString(selPgPointStr);
                    }

                    var polylineProps = selObj.getElementsByTagName('polyline');

                    if (polylineProps && polylineProps.length > 0) {
                      objectProp.type = TMXObjectType.POLYLINE;
                      var selPlPointStr = polylineProps[0].getAttribute('points');
                      if (selPlPointStr) objectProp.polylinePoints = this._parsePointsString(selPlPointStr);
                    }

                    if (!objectProp.type) {
                      objectProp.type = TMXObjectType.RECT;
                    }

                    objectGroup.objects.push(objectProp);
                  }

                  if (draworder !== 'index') {
                    objectGroup.objects.sort(function (a, b) {
                      return a.y - b.y;
                    });
                  }
                }

                return objectGroup;
              };

              _proto._parsePointsString = function _parsePointsString(pointsString) {
                if (!pointsString) return null;
                var points = [];
                var pointsStr = pointsString.split(' ');

                for (var i = 0; i < pointsStr.length; i++) {
                  var selPointStr = pointsStr[i].split(',');
                  points.push({
                    x: parseFloat(selPointStr[0]),
                    y: parseFloat(selPointStr[1])
                  });
                }

                return points;
              };

              _proto.setTileAnimations = function setTileAnimations(animations) {
                this._tileAnimations = animations;
              };

              _proto.getTileAnimations = function getTileAnimations() {
                return this._tileAnimations;
              };

              _proto.getTileProperties = function getTileProperties() {
                return this._tileProperties;
              };

              _proto.setTileProperties = function setTileProperties(tileProperties) {
                this._tileProperties = tileProperties;
              };

              _proto.getCurrentString = function getCurrentString() {
                return this.currentString;
              };

              _proto.setCurrentString = function setCurrentString(currentString) {
                this.currentString = currentString;
              };

              TMXMapInfo.getNameWithPostfix = function getNameWithPostfix(name) {
                name = name.replace(/\\/g, '/');
                var slashIndex = name.lastIndexOf('/') + 1;
                var strLen = name.length;
                return name.substring(slashIndex, strLen);
              };

              TMXMapInfo.getShortName = function getShortName(name) {
                name = name.replace(/\\/g, '/');
                var slashIndex = name.lastIndexOf('/') + 1;
                var dotIndex = name.lastIndexOf('.');
                dotIndex = dotIndex < 0 ? name.length : dotIndex;
                return name.substring(slashIndex, dotIndex);
              };

              _createClass(TMXMapInfo, [{
                key: "mapSize",
                get: function get() {
                  return this._mapSize;
                }
              }, {
                key: "tileSize",
                get: function get() {
                  return this._tileSize;
                }
              }, {
                key: "mapWidth",
                get: function get() {
                  return this._mapSize.width;
                },
                set: function set(width) {
                  this._mapSize.width = width;
                }
              }, {
                key: "mapHeight",
                get: function get() {
                  return this._mapSize.height;
                },
                set: function set(height) {
                  this._mapSize.height = height;
                }
              }, {
                key: "tileWidth",
                get: function get() {
                  return this._tileSize.width;
                },
                set: function set(width) {
                  this._tileSize.width = width;
                }
              }, {
                key: "tileHeight",
                get: function get() {
                  return this._tileSize.height;
                },
                set: function set(height) {
                  this._tileSize.height = height;
                }
              }]);

              return TMXMapInfo;
            }();

            var _dec$1N, _dec2$1h, _dec3$Y, _dec4$R, _dec5$H, _dec6$A, _dec7$y, _dec8$v, _dec9$r, _class$1Q, _class2$1B, _descriptor$1q, _descriptor2$16, _temp$1H;
            var TiledTile = exports('TiledTile', (_dec$1N = ccclass('cc.TiledTile'), _dec2$1h = help(), _dec3$Y = menu(), _dec4$R = requireComponent(UITransform), _dec5$H = type(CCInteger), _dec6$A = type(CCInteger), _dec7$y = type(CCInteger), _dec8$v = type(CCInteger), _dec9$r = type(CCInteger), _dec$1N(_class$1Q = _dec2$1h(_class$1Q = _dec3$Y(_class$1Q = _dec4$R(_class$1Q = executeInEditMode(_class$1Q = (_class2$1B = (_temp$1H = function (_Component) {
              _inheritsLoose(TiledTile, _Component);

              function TiledTile() {
                var _this;

                _this = _Component.call(this) || this;
                _this._layer = null;

                _initializerDefineProperty(_this, "_x", _descriptor$1q, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_y", _descriptor2$16, _assertThisInitialized(_this));

                return _this;
              }

              var _proto = TiledTile.prototype;

              _proto.onEnable = function onEnable() {
                var parent = this.node.parent;
                this._layer = parent.getComponent('cc.TiledLayer');

                this._resetTile();

                this.updateInfo();
              };

              _proto.onDisable = function onDisable() {
                this._resetTile();
              };

              _proto._resetTile = function _resetTile() {
                if (this._layer && this._layer.getTiledTileAt(this._x, this._y) === this) {
                  this._layer.setTiledTileAt(this._x, this._y, null);
                }
              };

              _proto.updateInfo = function updateInfo() {
                if (!this._layer) return;
                var x = this._x;
                var y = this._y;

                if (this._layer.getTiledTileAt(x, y)) {
                  warn('There is already a TiledTile at [%s, %s]', x, y);
                  return;
                }

                var p = this._layer.getPositionAt(x, y);

                this.node.setPosition(p.x, p.y);

                this._layer.setTiledTileAt(x, y, this);
              };

              _createClass(TiledTile, [{
                key: "x",
                get: function get() {
                  return this._x;
                },
                set: function set(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();
                }
              }, {
                key: "y",
                get: function get() {
                  return this._y;
                },
                set: function set(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();
                }
              }, {
                key: "grid",
                get: function get() {
                  if (this._layer) {
                    return this._layer.getTileGIDAt(this._x, this._y);
                  }

                  return 0;
                },
                set: function set(value) {
                  if (this._layer) {
                    this._layer.setTileGIDAt(value, this._x, this._y);
                  }
                }
              }]);

              return TiledTile;
            }(Component), _temp$1H), (_descriptor$1q = _applyDecoratedDescriptor(_class2$1B.prototype, "_x", [_dec5$H], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor2$16 = _applyDecoratedDescriptor(_class2$1B.prototype, "_y", [_dec6$A], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _applyDecoratedDescriptor(_class2$1B.prototype, "x", [_dec7$y], Object.getOwnPropertyDescriptor(_class2$1B.prototype, "x"), _class2$1B.prototype), _applyDecoratedDescriptor(_class2$1B.prototype, "y", [_dec8$v], Object.getOwnPropertyDescriptor(_class2$1B.prototype, "y"), _class2$1B.prototype), _applyDecoratedDescriptor(_class2$1B.prototype, "grid", [_dec9$r], Object.getOwnPropertyDescriptor(_class2$1B.prototype, "grid"), _class2$1B.prototype)), _class2$1B)) || _class$1Q) || _class$1Q) || _class$1Q) || _class$1Q) || _class$1Q));

            function fillTextureGrids(tileset, texGrids, spFrame) {
              var spf = spFrame || tileset.sourceImage;
              var tex = spf.texture;
              var collection = tileset.collection;

              if (!tileset.imageSize.width || !tileset.imageSize.height) {
                var sourceImage = tileset.sourceImage;
                tileset.imageSize.width = sourceImage.width;
                tileset.imageSize.height = sourceImage.height;
              }

              var imageWidth = tileset.imageSize.width;
              var imageHeight = tileset.imageSize.height;
              var tw = tileset._tileSize.width;
              var th = tileset._tileSize.height;
              var texWidth = spf.width;
              var texHeight = spf.height;
              var spacing = tileset.spacing;
              var margin = tileset.margin;
              var count = 1;

              if (!collection) {
                var cols = Math.floor((imageWidth - margin * 2 + spacing) / (tw + spacing));
                var rows = Math.floor((imageHeight - margin * 2 + spacing) / (th + spacing));
                count = Math.max(1, rows * cols);
              }

              var firstGid = tileset.firstGid;
              var grid = null;
              var override = !!texGrids.get(firstGid);
              var maxGid = tileset.firstGid + count;
              var gid = firstGid;

              for (; gid < maxGid; ++gid) {
                if (override && !texGrids.get(gid)) {
                  override = false;
                }

                if (!override && texGrids.get(gid)) {
                  break;
                }

                grid = {
                  tileset: 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) {
                  if (spFrame) {
                    grid._name = spFrame.name;
                    var lm = spFrame.unbiasUV[0];
                    var bm = spFrame.rotated ? spFrame.unbiasUV[1] : spFrame.unbiasUV[5];
                    grid.l = lm + (grid.x + 0.5) / texWidth;
                    grid.t = bm + (grid.y + 0.5) / texHeight;
                    grid.r = lm + (grid.x + grid.width - 0.5) / texWidth;
                    grid.b = bm + (grid.y + grid.height - 0.5) / texHeight;
                    grid._rect = new Rect(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(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);
              }
            }
            function loadAllTextures(textures, loadedCallback) {
              var totalNum = textures.length;

              if (totalNum === 0) {
                loadedCallback();
                return;
              }

              var curNum = 0;

              var itemCallback = function itemCallback() {
                curNum++;

                if (curNum >= totalNum) {
                  loadedCallback();
                }
              };

              for (var i = 0; i < totalNum; i++) {
                var tex = textures[i];

                if (!tex.loaded) {
                  tex.once('load', function () {
                    itemCallback();
                  });
                } else {
                  itemCallback();
                }
              }
            }

            var _dec$1O, _class$1R, _temp$1I, _dec2$1i, _class3$G, _temp2$6;

            var _mat4_temp$4 = new Mat4();

            var _vec2_temp$1 = new Vec2();

            var _vec3_temp = new Vec3();

            var _vec3_temp2 = new Vec3();

            var _tempRowCol = {
              row: 0,
              col: 0
            };
            var TiledUserNodeData = exports('TiledUserNodeData', (_dec$1O = ccclass('cc.TiledUserNodeData'), _dec$1O(_class$1R = (_temp$1I = function (_Component) {
              _inheritsLoose(TiledUserNodeData, _Component);

              function TiledUserNodeData() {
                var _this;

                _this = _Component.call(this) || this;
                _this._index = -1;
                _this._row = -1;
                _this._col = -1;
                _this._tiledLayer = null;
                return _this;
              }

              return TiledUserNodeData;
            }(Component), _temp$1I)) || _class$1R));
            var TiledLayer = exports('TiledLayer', (_dec2$1i = ccclass('cc.TiledLayer'), _dec2$1i(_class3$G = (_temp2$6 = function (_Renderable2D) {
              _inheritsLoose(TiledLayer, _Renderable2D);

              function TiledLayer() {
                var _this2;

                _this2 = _Renderable2D.call(this) || this;
                _this2._userNodeGrid = {};
                _this2._userNodeMap = {};
                _this2._userNodeDirty = false;
                _this2.tiledTiles = [];
                _this2._viewPort = {
                  x: -1,
                  y: -1,
                  width: -1,
                  height: -1
                };
                _this2._cullingRect = {
                  leftDown: {
                    row: -1,
                    col: -1
                  },
                  rightTop: {
                    row: -1,
                    col: -1
                  }
                };
                _this2._cullingDirty = true;
                _this2._rightTop = {
                  row: -1,
                  col: -1
                };
                _this2._layerInfo = null;
                _this2._mapInfo = null;
                _this2._topOffset = 0;
                _this2._downOffset = 0;
                _this2._leftOffset = 0;
                _this2._rightOffset = 0;
                _this2.tiles = [];
                _this2.vertices = [];
                _this2._verticesDirty = true;
                _this2._layerName = '';
                _this2._layerSize = void 0;
                _this2._minGID = void 0;
                _this2._maxGID = void 0;
                _this2._layerOrientation = null;
                _this2._opacity = void 0;
                _this2._tintColor = void 0;
                _this2.texGrids = null;
                _this2._textures = [];
                _this2._tilesets = [];
                _this2._leftDownToCenterX = 0;
                _this2._leftDownToCenterY = 0;
                _this2._hasTiledNodeGrid = false;
                _this2._hasAniGrid = false;
                _this2._animations = null;
                _this2._enableCulling = void 0;
                _this2.colorChanged = false;
                _this2._properties = void 0;
                _this2.renderOrder = void 0;
                _this2._staggerAxis = void 0;
                _this2._staggerIndex = void 0;
                _this2._hexSideLength = void 0;
                _this2._mapTileSize = void 0;
                _this2._odd_even = void 0;
                _this2._diffX1 = void 0;
                _this2._diffY1 = void 0;
                _this2._useAutomaticVertexZ = void 0;
                _this2._vertexZvalue = void 0;
                _this2._offset = void 0;
                _this2._meshRenderDataArray = null;
                _this2._meshRenderDataArrayIdx = 0;
                return _this2;
              }

              var _proto = TiledLayer.prototype;

              _proto.hasTiledNode = function hasTiledNode() {
                return this._hasTiledNodeGrid;
              };

              _proto.hasAnimation = function hasAnimation() {
                return this._hasAniGrid;
              };

              _proto.addUserNode = function addUserNode(node) {
                var 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$1);

                this._positionToRowCol(_vec2_temp$1.x, _vec2_temp$1.y, _tempRowCol);

                this._addUserNodeToGrid(dataComp, _tempRowCol);

                this._updateCullingOffsetByUserNode(node);

                node.on(SystemEventType.TRANSFORM_CHANGED, this._userNodePosChange, dataComp);
                node.on(SystemEventType.SIZE_CHANGED, this._userNodeSizeChange, dataComp);
                return true;
              };

              _proto.removeUserNode = function removeUserNode(node) {
                var dataComp = node.getComponent(TiledUserNodeData);

                if (!dataComp) {
                  warn('CCTiledLayer:removeUserNode node is not exist');
                  return false;
                }

                node.off(SystemEventType.TRANSFORM_CHANGED, this._userNodePosChange, dataComp);
                node.off(SystemEventType.SIZE_CHANGED, this._userNodeSizeChange, dataComp);

                this._removeUserNodeFromGrid(dataComp);

                delete this._userNodeMap[node.uuid];

                node._removeComponent(dataComp);

                dataComp.destroy();
                node.removeFromParent();
                return true;
              };

              _proto.destroyUserNode = function destroyUserNode(node) {
                this.removeUserNode(node);
                node.destroy();
              };

              _proto._nodeLocalPosToLayerPos = function _nodeLocalPosToLayerPos(nodePos, out) {
                out.x = nodePos.x + this._leftDownToCenterX;
                out.y = nodePos.y + this._leftDownToCenterY;
              };

              _proto.getNodesByRowCol = function getNodesByRowCol(row, col) {
                var rowData = this._userNodeGrid[row];
                if (!rowData) return null;
                return rowData[col];
              };

              _proto.getNodesCountByRow = function getNodesCountByRow(row) {
                var rowData = this._userNodeGrid[row];
                if (!rowData) return 0;
                return rowData.count;
              };

              _proto._updateAllUserNode = function _updateAllUserNode() {
                this._userNodeGrid = {};

                for (var dataId in this._userNodeMap) {
                  var dataComp = this._userNodeMap[dataId];

                  this._nodeLocalPosToLayerPos(dataComp.node.getPosition(), _vec2_temp$1);

                  this._positionToRowCol(_vec2_temp$1.x, _vec2_temp$1.y, _tempRowCol);

                  this._addUserNodeToGrid(dataComp, _tempRowCol);

                  this._updateCullingOffsetByUserNode(dataComp.node);
                }
              };

              _proto._updateCullingOffsetByUserNode = function _updateCullingOffsetByUserNode(node_) {
                var 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;
                }
              };

              _proto._userNodeSizeChange = function _userNodeSizeChange() {
                var dataComp = this;
                var node = dataComp.node;
                var self = dataComp._tiledLayer;

                self._updateCullingOffsetByUserNode(node);

                self._userNodeDirty = true;
                self.markForUpdateRenderData();
              };

              _proto._userNodePosChange = function _userNodePosChange() {
                var dataComp = this;
                var node = dataComp.node;
                var self = dataComp._tiledLayer;

                self._nodeLocalPosToLayerPos(node.getPosition(), _vec2_temp$1);

                self._positionToRowCol(_vec2_temp$1.x, _vec2_temp$1.y, _tempRowCol);

                self._limitInLayer(_tempRowCol);

                if (_tempRowCol.row === dataComp._row && _tempRowCol.col === dataComp._col) return;

                self._removeUserNodeFromGrid(dataComp);

                self._addUserNodeToGrid(dataComp, _tempRowCol);
              };

              _proto._removeUserNodeFromGrid = function _removeUserNodeFromGrid(dataComp) {
                var row = dataComp._row;
                var col = dataComp._col;
                var index = dataComp._index;
                var rowData = this._userNodeGrid[row];
                var 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();
              };

              _proto._limitInLayer = function _limitInLayer(rowCol) {
                var row = rowCol.row;
                var 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;
              };

              _proto._addUserNodeToGrid = function _addUserNodeToGrid(dataComp, tempRowCol) {
                var row = tempRowCol.row;
                var col = tempRowCol.col;
                var rowData = this._userNodeGrid[row] = this._userNodeGrid[row] || {
                  count: 0
                };
                var 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;
              };

              _proto.isUserNodeDirty = function isUserNodeDirty() {
                return this._userNodeDirty;
              };

              _proto.setUserNodeDirty = function setUserNodeDirty(value) {
                this._userNodeDirty = value;
              };

              _proto.onEnable = function onEnable() {
                _Renderable2D.prototype.onEnable.call(this);

                this.node.on(SystemEventType.ANCHOR_CHANGED, this._syncAnchorPoint, this);
                this.node.on(SystemEventType.TRANSFORM_CHANGED, this.updateCulling, this);
                this.node.on(SystemEventType.SIZE_CHANGED, this.updateCulling, this);
                this.node.parent.on(SystemEventType.TRANSFORM_CHANGED, this.updateCulling, this);
                this.node.parent.on(SystemEventType.SIZE_CHANGED, this.updateCulling, this);
                this.markForUpdateRenderData();
                this.scheduleOnce(this.updateCulling.bind(this));
              };

              _proto.onDisable = function onDisable() {
                _Renderable2D.prototype.onDisable.call(this);

                this.node.parent.off(SystemEventType.SIZE_CHANGED, this.updateCulling, this);
                this.node.parent.off(SystemEventType.TRANSFORM_CHANGED, this.updateCulling, this);
                this.node.off(SystemEventType.SIZE_CHANGED, this.updateCulling, this);
                this.node.off(SystemEventType.TRANSFORM_CHANGED, this.updateCulling, this);
                this.node.off(SystemEventType.ANCHOR_CHANGED, this._syncAnchorPoint, this);
              };

              _proto._syncAnchorPoint = function _syncAnchorPoint() {
                var node = this.node;
                var trans = node._uiProps.uiTransformComp;
                var scale = node.getScale();
                this._leftDownToCenterX = trans.width * trans.anchorX * scale.x;
                this._leftDownToCenterY = trans.height * trans.anchorY * scale.y;
                this._cullingDirty = true;
                this.markForUpdateRenderData();
              };

              _proto.onDestroy = function onDestroy() {
                _Renderable2D.prototype.onDestroy.call(this);
              };

              _proto.getLayerName = function getLayerName() {
                return this._layerName;
              };

              _proto.setLayerName = function setLayerName(layerName) {
                this._layerName = layerName;
              };

              _proto.getProperty = function getProperty(propertyName) {
                return this._properties[propertyName];
              };

              _proto.getPositionAt = function getPositionAt(pos, y) {
                var 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 Orientation$1.ORTHO:
                    return this._positionForOrthoAt(x, y);

                  case Orientation$1.ISO:
                    return this._positionForIsoAt(x, y);

                  case Orientation$1.HEX:
                    return this._positionForHexAt(x, y);
                }

                return null;
              };

              _proto.isInvalidPosition = function isInvalidPosition(x, y) {
                return x >= this._layerSize.width || y >= this._layerSize.height || x < 0 || y < 0;
              };

              _proto._positionForIsoAt = function _positionForIsoAt(x, y) {
                var offsetX = 0;
                var offsetY = 0;

                var index = Math.floor(x) + Math.floor(y) * this._layerSize.width;

                var gidAndFlags = this.tiles[index];

                if (gidAndFlags) {
                  var gid = (gidAndFlags & TileFlag.FLIPPED_MASK) >>> 0;
                  var tileset = this.texGrids.get(gid).tileset;
                  var 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);
              };

              _proto._positionForOrthoAt = function _positionForOrthoAt(x, y) {
                var offsetX = 0;
                var offsetY = 0;

                var index = Math.floor(x) + Math.floor(y) * this._layerSize.width;

                var gidAndFlags = this.tiles[index];

                if (gidAndFlags) {
                  var gid = (gidAndFlags & TileFlag.FLIPPED_MASK) >>> 0;
                  var tileset = this.texGrids.get(gid).tileset;
                  var 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);
              };

              _proto._positionForHexAt = function _positionForHexAt(col, row) {
                var tileWidth = this._mapTileSize.width;
                var tileHeight = this._mapTileSize.height;
                var rows = this._layerSize.height;

                var index = Math.floor(col) + Math.floor(row) * this._layerSize.width;

                var gid = (this.tiles[index] & TileFlag.FLIPPED_MASK) >>> 0;
                var offset;

                if (this.texGrids.get(gid)) {
                  offset = this.texGrids.get(gid).tileset.tileOffset;
                } else {
                  offset = {
                    x: 0,
                    y: 0
                  };
                }

                var odd_even = this._staggerIndex === StaggerIndex.STAGGERINDEX_ODD ? 1 : -1;
                var x = 0;
                var y = 0;
                var diffX = 0;
                var diffY = 0;

                switch (this._staggerAxis) {
                  case StaggerAxis.STAGGERAXIS_Y:
                    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 StaggerAxis.STAGGERAXIS_X:
                    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);
              };

              _proto.setTilesGIDAt = function setTilesGIDAt(gids, beginCol, beginRow, totalCols) {
                if (!gids || gids.length === 0 || totalCols <= 0) return;
                if (beginRow < 0) beginRow = 0;
                if (beginCol < 0) beginCol = 0;
                var gidsIdx = 0;
                var endCol = beginCol + totalCols;

                for (var row = beginRow;; row++) {
                  for (var col = beginCol; col < endCol; col++) {
                    if (gidsIdx >= gids.length) return;

                    this._updateTileForGID(gids[gidsIdx], col, row);

                    gidsIdx++;
                  }
                }
              };

              _proto.setTileGIDAt = function setTileGIDAt(gid, x, y, flags) {
                var ugid = (gid & TileFlag.FLIPPED_MASK) >>> 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);
              };

              _proto._updateTileForGID = function _updateTileForGID(gidAndFlags, x, y) {
                var idx = 0 | x + y * this._layerSize.width;
                if (idx >= this.tiles.length) return;
                var oldGIDAndFlags = this.tiles[idx];
                if (gidAndFlags === oldGIDAndFlags) return;
                var gid = (gidAndFlags & TileFlag.FLIPPED_MASK) >>> 0;
                var grid = this.texGrids.get(gid);

                if (grid) {
                  this.tiles[idx] = gidAndFlags;

                  this._updateVertex(x, y);
                } else {
                  this.tiles[idx] = 0;
                }

                this._cullingDirty = true;
              };

              _proto.getTileGIDAt = function getTileGIDAt(x, y) {
                if (this.isInvalidPosition(x, y)) {
                  throw new Error('cc.TiledLayer.getTileGIDAt(): invalid position');
                }

                if (!this.tiles) {
                  logID(7237);
                  return null;
                }

                var index = Math.floor(x) + Math.floor(y) * this._layerSize.width;

                var tile = this.tiles[index];
                return (tile & TileFlag.FLIPPED_MASK) >>> 0;
              };

              _proto.getTileFlagsAt = function getTileFlagsAt(x, y) {
                if (this.isInvalidPosition(x, y)) {
                  throw new Error('TiledLayer.getTileFlagsAt: invalid position');
                }

                if (!this.tiles) {
                  logID(7240);
                  return null;
                }

                var idx = Math.floor(x) + Math.floor(y) * this._layerSize.width;

                var tile = this.tiles[idx];
                return (tile & TileFlag.FLIPPED_ALL) >>> 0;
              };

              _proto.setCullingDirty = function setCullingDirty(value) {
                this._cullingDirty = value;
              };

              _proto.isCullingDirty = function isCullingDirty() {
                return this._cullingDirty;
              };

              _proto.updateViewPort = function 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;
                var reserveLine = 1;

                if (this._layerOrientation === Orientation$1.ISO) {
                  reserveLine = 2;
                }

                var vpx = this._viewPort.x - this._offset.x + this._leftDownToCenterX;
                var vpy = this._viewPort.y - this._offset.y + this._leftDownToCenterY;
                var leftDownX = vpx - this._leftOffset;
                var leftDownY = vpy - this._downOffset;
                var rightTopX = vpx + width + this._rightOffset;
                var rightTopY = vpy + height + this._topOffset;
                var leftDown = this._cullingRect.leftDown;
                var 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 > this._rightTop.row) _tempRowCol.row = this._rightTop.row;
                if (_tempRowCol.col > this._rightTop.col) _tempRowCol.col = this._rightTop.col;

                if (_tempRowCol.row !== rightTop.row || _tempRowCol.col !== rightTop.col) {
                  rightTop.row = _tempRowCol.row;
                  rightTop.col = _tempRowCol.col;
                  this._cullingDirty = true;
                  this.markForUpdateRenderData();
                }
              };

              _proto._positionToRowCol = function _positionToRowCol(x, y, result) {
                var maptw = this._mapTileSize.width;
                var mapth = this._mapTileSize.height;
                var maptw2 = maptw * 0.5;
                var mapth2 = mapth * 0.5;
                var row = 0;
                var col = 0;
                var diffX2 = 0;
                var diffY2 = 0;
                var axis = this._staggerAxis;

                switch (this._layerOrientation) {
                  case Orientation$1.ORTHO:
                    col = Math.floor(x / maptw);
                    row = Math.floor(y / mapth);
                    break;

                  case Orientation$1.ISO:
                    col = Math.floor(x / maptw2);
                    row = Math.floor(y / mapth2);
                    break;

                  case Orientation$1.HEX:
                    if (axis === StaggerAxis.STAGGERAXIS_Y) {
                      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;
              };

              _proto.updateCulling = function updateCulling() {
                if (this._enableCulling) {
                  this.node.updateWorldTransform();
                  Mat4.invert(_mat4_temp$4, this.node.getWorldMatrix());
                  var camera = director.root.batcher2D.getFirstRenderCamera(this.node);

                  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$4);
                    Vec3.transformMat4(_vec3_temp2, _vec3_temp2, _mat4_temp$4);
                    this.updateViewPort(_vec3_temp.x, _vec3_temp.y, _vec3_temp2.x - _vec3_temp.x, _vec3_temp2.y - _vec3_temp.y);
                  }
                }
              };

              _proto.getLayerOrientation = function getLayerOrientation() {
                return this._layerOrientation;
              };

              _proto.getProperties = function getProperties() {
                return this._properties;
              };

              _proto._updateVertex = function _updateVertex(col, row) {
                var FLIPPED_MASK = TileFlag.FLIPPED_MASK;
                var vertices = this.vertices;
                var layerOrientation = this._layerOrientation;
                var tiles = this.tiles;

                if (!tiles) {
                  return;
                }

                var rightTop = this._rightTop;
                var maptw = this._mapTileSize.width;
                var mapth = this._mapTileSize.height;
                var maptw2 = maptw * 0.5;
                var mapth2 = mapth * 0.5;
                var rows = this._layerSize.height;
                var cols = this._layerSize.width;
                var grids = this.texGrids;
                var left = 0;
                var bottom = 0;
                var axis;
                var diffX1;
                var diffY1;
                var odd_even;
                var diffX2;
                var diffY2;

                if (layerOrientation === Orientation$1.HEX) {
                  axis = this._staggerAxis;
                  diffX1 = this._diffX1;
                  diffY1 = this._diffY1;
                  odd_even = this._odd_even;
                }

                var cullingCol = 0;
                var cullingRow = 0;
                var gridGID = 0;
                var topBorder = 0;
                var downBorder = 0;
                var leftBorder = 0;
                var rightBorder = 0;
                var index = row * cols + col;
                var gid = tiles[index];
                gridGID = (gid & FLIPPED_MASK) >>> 0;
                var grid = grids.get(gridGID);

                if (!grid) {
                  return;
                }

                if (this._animations.get(gridGID)) {
                  this._hasAniGrid = this._hasAniGrid || true;
                }

                switch (layerOrientation) {
                  case Orientation$1.ORTHO:
                    cullingCol = col;
                    cullingRow = rows - row - 1;
                    left = cullingCol * maptw;
                    bottom = cullingRow * mapth;
                    break;

                  case Orientation$1.ISO:
                    cullingCol = rows + col - row - 1;
                    cullingRow = rows + cols - col - row - 2;
                    left = maptw2 * cullingCol;
                    bottom = mapth2 * cullingRow;
                    break;

                  case Orientation$1.HEX:
                    diffX2 = axis === StaggerAxis.STAGGERAXIS_Y && row % 2 === 1 ? maptw2 * odd_even : 0;
                    diffY2 = axis === StaggerAxis.STAGGERAXIS_X && 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;
                }

                var rowData = vertices[cullingRow] = vertices[cullingRow] || {
                  minCol: 0,
                  maxCol: 0
                };
                var colData = rowData[cullingCol] = rowData[cullingCol] || {};

                if (rowData.minCol > cullingCol) {
                  rowData.minCol = cullingCol;
                }

                if (rowData.maxCol < cullingCol) {
                  rowData.maxCol = cullingCol;
                }

                if (rightTop.row < cullingRow) {
                  rightTop.row = cullingRow;
                }

                if (rightTop.col < cullingCol) {
                  rightTop.col = cullingCol;
                }

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

              _proto._updateVertices = function _updateVertices() {
                var vertices = this.vertices;
                vertices.length = 0;
                var tiles = this.tiles;

                if (!tiles) {
                  return;
                }

                var rightTop = this._rightTop;
                rightTop.row = -1;
                rightTop.col = -1;
                var rows = this._layerSize.height;
                var cols = this._layerSize.width;
                this._topOffset = 0;
                this._downOffset = 0;
                this._leftOffset = 0;
                this._rightOffset = 0;
                this._hasAniGrid = false;

                for (var row = 0; row < rows; ++row) {
                  for (var col = 0; col < cols; ++col) {
                    this._updateVertex(col, row);
                  }
                }

                this._verticesDirty = false;
              };

              _proto.getTiledTileAt = function getTiledTileAt(x, y, forceCreate) {
                if (this.isInvalidPosition(x, y)) {
                  throw new Error('TiledLayer.getTiledTileAt: invalid position');
                }

                if (!this.tiles) {
                  logID(7236);
                  return null;
                }

                var index = Math.floor(x) + Math.floor(y) * this._layerSize.width;

                var tile = this.tiledTiles[index];

                if (!tile && forceCreate) {
                  var 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;
              };

              _proto.setTiledTileAt = function setTiledTileAt(x, y, tiledTile) {
                if (this.isInvalidPosition(x, y)) {
                  throw new Error('TiledLayer.setTiledTileAt: invalid position');
                }

                if (!this.tiles) {
                  logID(7236);
                  return null;
                }

                var 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(function (tiledNode) {
                    return !!tiledNode;
                  });
                }

                return tiledTile;
              };

              _proto.getTexture = function getTexture(index) {
                index = index || 0;

                if (this._textures && index >= 0 && this._textures.length > index) {
                  return this._textures[index];
                }

                return null;
              };

              _proto.getTextures = function getTextures() {
                return this._textures;
              };

              _proto.setTexture = function setTexture(texture) {
                this.setTextures([texture]);
              };

              _proto.setTextures = function setTextures(textures) {
                this._textures = textures;
                this.markForUpdateRenderData();
              };

              _proto.getLayerSize = function getLayerSize() {
                return this._layerSize;
              };

              _proto.getMapTileSize = function getMapTileSize() {
                return this._mapTileSize;
              };

              _proto.getTileSet = function getTileSet(index) {
                index = index || 0;

                if (this._tilesets && index >= 0 && this._tilesets.length > index) {
                  return this._tilesets[index];
                }

                return null;
              };

              _proto.getTileSets = function getTileSets() {
                return this._tilesets;
              };

              _proto.setTileSet = function setTileSet(tileset) {
                this.setTileSets([tileset]);
              };

              _proto.setTileSets = function setTileSets(tilesets) {
                var _this3 = this;

                this._tilesets = tilesets;
                var textures = this._textures = [];
                var texGrids = this.texGrids;
                texGrids.clear();

                for (var i = 0; i < tilesets.length; i++) {
                  var tileset = tilesets[i];

                  if (tileset) {
                    textures[i] = tileset.sourceImage;
                  }
                }

                loadAllTextures(textures, function () {
                  for (var _i = 0, l = tilesets.length; _i < l; ++_i) {
                    var tilesetInfo = tilesets[_i];
                    if (!tilesetInfo) continue;
                    fillTextureGrids(tilesetInfo, texGrids, tilesetInfo.sourceImage);
                  }

                  _this3._prepareToRender();
                });
              };

              _proto.init = function init(layerInfo, mapInfo, tilesets, textures, texGrids) {
                this._cullingDirty = true;
                this._layerInfo = layerInfo;
                this._mapInfo = mapInfo;
                var 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();
                var maptw = this._mapTileSize.width;
                var mapth = this._mapTileSize.height;
                var layerW = this._layerSize.width;
                var layerH = this._layerSize.height;

                if (this._layerOrientation === Orientation$1.HEX) {
                  var width = 0;
                  var height = 0;
                  this._odd_even = this._staggerIndex === StaggerIndex.STAGGERINDEX_ODD ? 1 : -1;

                  if (this._staggerAxis === StaggerAxis.STAGGERAXIS_X) {
                    this._diffX1 = (maptw - this._hexSideLength) / 2;
                    this._diffY1 = 0;
                    height = mapth * (layerH + 0.5);
                    width = (maptw + this._hexSideLength) * Math.floor(layerW / 2) + maptw * (layerW % 2);
                  } else {
                    this._diffX1 = 0;
                    this._diffY1 = (mapth - this._hexSideLength) / 2;
                    width = maptw * (layerW + 0.5);
                    height = (mapth + this._hexSideLength) * Math.floor(layerH / 2) + mapth * (layerH % 2);
                  }

                  this.node._uiProps.uiTransformComp.setContentSize(width, height);
                } else if (this._layerOrientation === Orientation$1.ISO) {
                  var 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();
              };

              _proto._prepareToRender = function _prepareToRender() {
                this._updateVertices();

                this._updateAllUserNode();
              };

              _proto.requestMeshRenderData = function requestMeshRenderData() {
                var _this4 = this;

                if (!this._meshRenderDataArray) {
                  this._meshRenderDataArray = [];
                }

                var arr = this._meshRenderDataArray;

                while (arr.length > 0 && arr[arr.length - 1].subNodes && arr[arr.length - 1].subNodes.length === 0) {
                  arr.pop();
                }

                if (arr.length > 0) {
                  var last = arr[arr.length - 1];

                  if (last.renderData && last.renderData.byteCount === 0) {
                    return last;
                  }
                }

                var renderData = new MeshRenderData();
                var comb = {
                  renderData: renderData,
                  texture: null
                };
                Object.defineProperty(renderData, 'material', {
                  get: function get() {
                    return _this4.getRenderMaterial(0);
                  }
                });

                this._meshRenderDataArray.push(comb);

                return comb;
              };

              _proto.requestSubNodesData = function requestSubNodesData() {
                if (!this._meshRenderDataArray) {
                  this._meshRenderDataArray = [];
                }

                var arr = this._meshRenderDataArray;

                while (arr.length > 0 && arr[arr.length - 1].renderData && arr[arr.length - 1].renderData.byteCount === 0) {
                  arr.pop();
                }

                if (arr.length > 0) {
                  if (arr[arr.length - 1].subNodes && arr[arr.length - 1].subNodes.length === 0) {
                    return arr[arr.length - 1];
                  }
                }

                var renderData = [];
                var comb = {
                  subNodes: renderData
                };

                this._meshRenderDataArray.push(comb);

                return comb;
              };

              _proto.destroyRenderData = function destroyRenderData() {
                if (this._meshRenderDataArray) {
                  this._meshRenderDataArray.forEach(function (rd) {
                    if (rd.renderData) rd.renderData.reset();
                  });

                  this._meshRenderDataArray.length = 0;
                }
              };

              _proto._flushAssembler = function _flushAssembler() {
                var assembler = TiledLayer.Assembler.getAssembler(this);

                if (this._assembler !== assembler) {
                  this._assembler = assembler;
                }

                if (!this._meshRenderDataArray) {
                  if (this._assembler && this._assembler.createData) {
                    this._assembler.createData(this);

                    this.markForUpdateRenderData();

                    this._updateColor();
                  }
                }
              };

              _proto._render = function _render(ui) {
                if (this._meshRenderDataArray) {
                  for (var i = 0; i < this._meshRenderDataArray.length; i++) {
                    this._meshRenderDataArrayIdx = i;
                    var m = this._meshRenderDataArray[i];

                    if (m.subNodes) {
                      m.subNodes.forEach(function (c) {
                        if (c) ui.walk(c.node);
                      });
                    } else if (m.texture) {
                      ui.commitComp(this, m.texture, this._assembler, null);
                    }
                  }

                  this.node._static = true;
                }
              };

              _createClass(TiledLayer, [{
                key: "cullingRect",
                get: function get() {
                  return this._cullingRect;
                }
              }, {
                key: "rightTop",
                get: function get() {
                  return this._rightTop;
                }
              }, {
                key: "layerSize",
                get: function get() {
                  return this._layerSize;
                }
              }, {
                key: "meshRenderDataArray",
                get: function get() {
                  return this._meshRenderDataArray;
                }
              }, {
                key: "leftDownToCenterX",
                get: function get() {
                  return this._leftDownToCenterX;
                }
              }, {
                key: "leftDownToCenterY",
                get: function get() {
                  return this._leftDownToCenterY;
                }
              }, {
                key: "enableCulling",
                get: function get() {
                  return this._enableCulling;
                },
                set: function set(value) {
                  if (this._enableCulling !== value) {
                    this._enableCulling = value;
                    this._cullingDirty = true;
                    this.markForUpdateRenderData();
                  }
                }
              }]);

              return TiledLayer;
            }(Renderable2D), _temp2$6)) || _class3$G));

            var _dec$1P, _dec2$1j, _dec3$Z, _dec4$S, _class$1S, _class2$1C, _temp$1J;
            var TiledObjectGroup = exports('TiledObjectGroup', (_dec$1P = ccclass('cc.TiledObjectGroup'), _dec2$1j = help(), _dec3$Z = requireComponent(UITransform), _dec4$S = type(CCBoolean), _dec$1P(_class$1S = _dec2$1j(_class$1S = _dec3$Z(_class$1S = (_class2$1C = (_temp$1J = function (_Component) {
              _inheritsLoose(TiledObjectGroup, _Component);

              function TiledObjectGroup() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Component.call.apply(_Component, [this].concat(args)) || this;
                _this._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 = [];
                return _this;
              }

              var _proto = TiledObjectGroup.prototype;

              _proto.getPositionOffset = function getPositionOffset() {
                return this._positionOffset;
              };

              _proto.getProperties = function getProperties() {
                return this._properties;
              };

              _proto.getGroupName = function getGroupName() {
                return this._groupName;
              };

              _proto.getProperty = function getProperty(propertyName) {
                return this._properties[propertyName.toString()];
              };

              _proto.getObject = function getObject(objectName) {
                for (var i = 0, len = this._objects.length; i < len; i++) {
                  var obj = this._objects[i];

                  if (obj && obj.name === objectName) {
                    return obj;
                  }
                }

                return null;
              };

              _proto.getObjects = function getObjects() {
                return this._objects;
              };

              _proto._init = function _init(groupInfo, mapInfo, texGrids) {
                var FLIPPED_MASK = TileFlag.FLIPPED_MASK;
                var FLAG_HORIZONTAL = TileFlag.HORIZONTAL;
                var FLAG_VERTICAL = TileFlag.VERTICAL;
                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;
                var mapSize = mapInfo.mapSize;
                var tileSize = mapInfo.tileSize;
                var width = 0;
                var height = 0;
                var colorVal = new Color();
                var iso = Orientation$1.ISO === mapInfo.orientation;

                if (mapInfo.orientation === Orientation$1.HEX) {
                  if (mapInfo.getStaggerAxis() === StaggerAxis.STAGGERAXIS_X) {
                    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) {
                  var 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;
                }

                var transComp = this.node._uiProps.uiTransformComp;
                transComp.setContentSize(width, height);
                var leftTopX = width * transComp.anchorX;
                var leftTopY = height * (1 - transComp.anchorY);
                var objects = groupInfo.objects;
                var aliveNodes = {};

                for (var i = 0, l = objects.length; i < l; i++) {
                  var object = objects[i];
                  var objType = object.type;
                  object.offset = new Vec2(object.x, object.y);
                  var points = object.points || object.polylinePoints;

                  if (points) {
                    for (var pi = 0; pi < points.length; pi++) {
                      points[pi].y *= -1;
                    }
                  }

                  if (iso) {
                    var posIdxX = object.x / tileSize.height;
                    var 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 === TMXObjectType.TEXT) {
                    var textName = "text" + object.id;
                    aliveNodes[textName] = true;
                    var 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);
                    var label = textNode.getComponent(Label);

                    if (!label) {
                      label = textNode.addComponent(Label);
                    }

                    var 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 {
                      var 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 === TMXObjectType.IMAGE) {
                    var gid = object.gid;
                    var gridGID = (gid & FLIPPED_MASK) >>> 0;
                    var grid = texGrids.get(gridGID);
                    if (!grid) continue;
                    var tileset = grid.tileset;
                    var imgName = "img" + object.id;
                    aliveNodes[imgName] = true;
                    var 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: object,
                        imgNode: imgNode,
                        gridGID: gridGID
                      });
                      this._hasAniObj = true;
                    }

                    var tileOffsetX = tileset.tileOffset.x;
                    var 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);
                    var sprite = imgNode.getComponent(Sprite);

                    if (!sprite) {
                      sprite = imgNode.addComponent(Sprite);
                    }

                    var 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 {
                      var _c = sprite.color;
                      _c.a *= this._opacity / 255;
                    }

                    sprite.sizeMode = Sprite.SizeMode.CUSTOM;
                    sprite._srcBlendFactor = this._premultiplyAlpha ? BlendFactor.ONE : BlendFactor.SRC_ALPHA;
                    sprite._dstBlendFactor = BlendFactor.ONE_MINUS_SRC_ALPHA;

                    sprite._updateBlendFunc();

                    var 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;
                var children = this.node.children;
                var uselessExp = /^(?:img|text)\d+$/;

                for (var _i = 0, n = children.length; _i < n; _i++) {
                  var _c2 = children[_i];
                  var cName = _c2.name;
                  var isUseless = uselessExp.test(cName);
                  if (isUseless && !aliveNodes[cName]) _c2.destroy();
                }
              };

              _proto.update = function update(dt) {
                if (!this._hasAniObj) {
                  return;
                }

                var aniObjects = this.aniObjects;
                var _texGrids = this._texGrids;
                var iso = Orientation$1.ISO === this._mapInfo.orientation;

                for (var i = 0, len = aniObjects.length; i < len; i++) {
                  var aniObj = aniObjects[i];
                  var gridGID = aniObj.gridGID;

                  var grid = _texGrids.get(gridGID);

                  if (!grid) {
                    continue;
                  }

                  var tileset = grid.tileset;
                  var object = aniObj.object;
                  var imgNode = aniObj.imgNode;
                  var tileOffsetX = tileset.tileOffset.x;
                  var tileOffsetY = tileset.tileOffset.y;
                  var 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;
                  }

                  var sp = imgNode.getComponent(Sprite);
                  var spf = sp.spriteFrame;
                  spf.rotated = grid._rotated;
                  spf.rect = grid._rect;
                  sp.spriteFrame = spf;
                  sp.markForUpdateRenderData();
                }
              };

              _createClass(TiledObjectGroup, [{
                key: "premultiplyAlpha",
                get: function get() {
                  return this._premultiplyAlpha;
                },
                set: function set(value) {
                  this._premultiplyAlpha = value;
                }
              }, {
                key: "offset",
                get: function get() {
                  return this._offset;
                }
              }]);

              return TiledObjectGroup;
            }(Component), _temp$1J), (_applyDecoratedDescriptor(_class2$1C.prototype, "premultiplyAlpha", [_dec4$S], Object.getOwnPropertyDescriptor(_class2$1C.prototype, "premultiplyAlpha"), _class2$1C.prototype)), _class2$1C)) || _class$1S) || _class$1S) || _class$1S));

            var _dec$1Q, _dec2$1k, _dec3$_, _dec4$T, _dec5$I, _dec6$B, _dec7$z, _dec8$w, _class$1T, _class2$1D, _descriptor$1r, _descriptor2$17, _descriptor3$Q, _descriptor4$J, _descriptor5$A, _descriptor6$r, _descriptor7$l, _descriptor8$l, _temp$1K;
            var TiledMapAsset = exports('TiledMapAsset', (_dec$1Q = ccclass('cc.TiledMapAsset'), _dec2$1k = type([TextAsset]), _dec3$_ = type([CCString]), _dec4$T = type([SpriteFrame]), _dec5$I = type([SpriteFrame]), _dec6$B = type([CCString]), _dec7$z = type([CCString]), _dec8$w = type([Size]), _dec$1Q(_class$1T = (_class2$1D = (_temp$1K = function (_Asset) {
              _inheritsLoose(TiledMapAsset, _Asset);

              function TiledMapAsset() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "tmxXmlStr", _descriptor$1r, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "tsxFiles", _descriptor2$17, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "tsxFileNames", _descriptor3$Q, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "spriteFrames", _descriptor4$J, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "imageLayerSpriteFrame", _descriptor5$A, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "imageLayerSpriteFrameNames", _descriptor6$r, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "spriteFrameNames", _descriptor7$l, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "spriteFrameSizes", _descriptor8$l, _assertThisInitialized(_this));

                return _this;
              }

              return TiledMapAsset;
            }(Asset), _temp$1K), (_descriptor$1r = _applyDecoratedDescriptor(_class2$1D.prototype, "tmxXmlStr", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return '';
              }
            }), _descriptor2$17 = _applyDecoratedDescriptor(_class2$1D.prototype, "tsxFiles", [serializable, _dec2$1k], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor3$Q = _applyDecoratedDescriptor(_class2$1D.prototype, "tsxFileNames", [serializable, _dec3$_], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor4$J = _applyDecoratedDescriptor(_class2$1D.prototype, "spriteFrames", [serializable, _dec4$T], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor5$A = _applyDecoratedDescriptor(_class2$1D.prototype, "imageLayerSpriteFrame", [serializable, _dec5$I], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor6$r = _applyDecoratedDescriptor(_class2$1D.prototype, "imageLayerSpriteFrameNames", [serializable, _dec6$B], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor7$l = _applyDecoratedDescriptor(_class2$1D.prototype, "spriteFrameNames", [serializable, _dec7$z], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor8$l = _applyDecoratedDescriptor(_class2$1D.prototype, "spriteFrameSizes", [serializable, _dec8$w], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            })), _class2$1D)) || _class$1T));

            var _dec$1R, _dec2$1l, _dec3$$, _dec4$U, _dec5$J, _dec6$C, _class$1U, _class2$1E, _descriptor$1s, _descriptor2$18, _descriptor3$R, _class3$H, _temp$1L;
            var TiledMap = exports('TiledMap', (_dec$1R = ccclass('cc.TiledMap'), _dec2$1l = help(), _dec3$$ = menu(), _dec4$U = requireComponent(UITransform), _dec5$J = type(TiledMapAsset), _dec6$C = displayOrder(), _dec$1R(_class$1U = _dec2$1l(_class$1U = _dec3$$(_class$1U = _dec4$U(_class$1U = executeInEditMode(_class$1U = (_class2$1E = (_temp$1L = _class3$H = function (_Component) {
              _inheritsLoose(TiledMap, _Component);

              function TiledMap() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Component.call.apply(_Component, [this].concat(args)) || this;
                _this._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(0, 0);
                _this._tileSize = new Size(0, 0);
                _this._preloaded = false;
                _this._mapOrientation = Orientation$1.ORTHO;

                _initializerDefineProperty(_this, "_tmxFile", _descriptor$1s, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_enableCulling", _descriptor2$18, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "cleanupImageCache", _descriptor3$R, _assertThisInitialized(_this));

                return _this;
              }

              var _proto = TiledMap.prototype;

              _proto.getMapSize = function getMapSize() {
                return this._mapSize;
              };

              _proto.getTileSize = function getTileSize() {
                return this._tileSize;
              };

              _proto.getMapOrientation = function getMapOrientation() {
                return this._mapOrientation;
              };

              _proto.getObjectGroups = function getObjectGroups() {
                return this._groups;
              };

              _proto.getObjectGroup = function getObjectGroup(groupName) {
                var groups = this._groups;

                for (var i = 0, l = groups.length; i < l; i++) {
                  var group = groups[i];

                  if (group && group.getGroupName() === groupName) {
                    return group;
                  }
                }

                return null;
              };

              _proto.getProperties = function getProperties() {
                return this._properties;
              };

              _proto.getLayers = function getLayers() {
                return this._layers;
              };

              _proto.getLayer = function getLayer(layerName) {
                var layers = this._layers;

                for (var i = 0, l = layers.length; i < l; i++) {
                  var layer = layers[i];

                  if (layer && layer.getLayerName() === layerName) {
                    return layer;
                  }
                }

                return null;
              };

              _proto._changeLayer = function _changeLayer(layerName, replaceLayer) {
                var layers = this._layers;

                for (var i = 0, l = layers.length; i < l; i++) {
                  var layer = layers[i];

                  if (layer && layer.getLayerName() === layerName) {
                    layers[i] = replaceLayer;
                    return;
                  }
                }
              };

              _proto.getProperty = function getProperty(propertyName) {
                return this._properties[propertyName.toString()];
              };

              _proto.getPropertiesForGID = function getPropertiesForGID(gid) {
                return this._tileProperties.get(gid);
              };

              _proto.__preload = function __preload() {
                this._preloaded = true;

                if (!this._tmxFile) {
                  return;
                }

                this._applyFile();
              };

              _proto.onEnable = function onEnable() {
                this.node.on(SystemEventType.ANCHOR_CHANGED, this._syncAnchorPoint, this);
              };

              _proto.onDisable = function onDisable() {
                this.node.off(SystemEventType.ANCHOR_CHANGED, this._syncAnchorPoint, this);
              };

              _proto._applyFile = function _applyFile() {
                var spriteFrames = [];
                var spriteFramesCache = {};
                var file = this._tmxFile;

                if (file) {
                  var spfNames = file.spriteFrameNames;
                  var spfSizes = file.spriteFrameSizes;
                  var fSpriteFrames = file.spriteFrames;
                  var spfTexturesMap = {};
                  var spfTextureSizeMap = {};

                  for (var i = 0; i < spfNames.length; ++i) {
                    var texName = spfNames[i];
                    spfTextureSizeMap[texName] = spfSizes[i];
                    spriteFrames[i] = fSpriteFrames[i];
                    var frame = spriteFrames[i];

                    if (frame) {
                      spriteFramesCache[frame.name] = frame;
                      spfTexturesMap[texName] = frame;
                    }
                  }

                  var imageLayerTextures = {};
                  var texValues = file.imageLayerSpriteFrame;
                  spfNames = file.imageLayerSpriteFrameNames;

                  for (var _i = 0; _i < texValues.length; ++_i) {
                    imageLayerTextures[spfNames[_i]] = texValues[_i];
                  }

                  var tsxFileNames = file.tsxFileNames;
                  var tsxFiles = file.tsxFiles;
                  var tsxContentMap = {};

                  for (var _i2 = 0; _i2 < tsxFileNames.length; ++_i2) {
                    if (tsxFileNames[_i2].length > 0) {
                      tsxContentMap[tsxFileNames[_i2]] = tsxFiles[_i2].text;
                    }
                  }

                  var mapInfo = new TMXMapInfo(file.tmxXmlStr, tsxContentMap, spfTexturesMap, spfTextureSizeMap, imageLayerTextures);
                  var tilesets = mapInfo.getTilesets();

                  if (!tilesets || tilesets.length === 0) {
                    logID(7241);
                  }

                  this._buildWithMapInfo(mapInfo);
                } else {
                  this._releaseMapInfo();
                }
              };

              _proto._releaseMapInfo = function _releaseMapInfo() {
                var layers = this._layers;

                for (var i = 0, l = layers.length; i < l; i++) {
                  layers[i].node.removeFromParent();
                  layers[i].node.destroy();
                }

                layers.length = 0;
                var groups = this._groups;

                for (var _i3 = 0, _l = groups.length; _i3 < _l; _i3++) {
                  groups[_i3].node.removeFromParent();

                  groups[_i3].node.destroy();
                }

                groups.length = 0;
                var images = this._images;

                for (var _i4 = 0, _l2 = images.length; _i4 < _l2; _i4++) {
                  images[_i4].removeFromParent();

                  images[_i4].destroy();
                }

                images.length = 0;
              };

              _proto._syncAnchorPoint = function _syncAnchorPoint() {
                var anchor = this.node._uiProps.uiTransformComp.anchorPoint;
                var leftTopX = this.node._uiProps.uiTransformComp.width * anchor.x;
                var leftTopY = this.node._uiProps.uiTransformComp.height * (1 - anchor.y);
                var i;
                var l;

                for (i = 0, l = this._layers.length; i < l; i++) {
                  var layerInfo = this._layers[i];
                  var layerNode = layerInfo.node;

                  layerNode._uiProps.uiTransformComp.setAnchorPoint(anchor);
                }

                for (i = 0, l = this._groups.length; i < l; i++) {
                  var groupInfo = this._groups[i];
                  var groupNode = groupInfo.node._uiProps.uiTransformComp;
                  groupNode.anchorX = 0.5;
                  groupNode.anchorY = 0.5;
                  var x = groupInfo.offset.x - leftTopX + groupNode.width * groupNode.anchorX;
                  var y = groupInfo.offset.y + leftTopY - groupNode.height * groupNode.anchorY;
                  groupInfo.node.setPosition(x, y);
                }

                for (i = 0, l = this._images.length; i < l; i++) {
                  var image = this._images[i]._uiProps.uiTransformComp;
                  image.anchorX = 0.5;
                  image.anchorY = 0.5;

                  var _x = this._images[i]._offset.x - leftTopX + image.width * image.anchorX;

                  var _y = this._images[i]._offset.y + leftTopY - image.height * image.anchorY;

                  this._images[i].setPosition(_x, _y);
                }
              };

              _proto._fillAniGrids = function _fillAniGrids(texGrids, animations) {
                for (var _iterator = _createForOfIteratorHelperLoose(animations.keys()), _step; !(_step = _iterator()).done;) {
                  var i = _step.value;
                  var animation = animations.get(i);
                  if (!animation) continue;
                  var frames = animation.frames;

                  for (var j = 0; j < frames.length; j++) {
                    var frame = frames[j];
                    frame.grid = texGrids.get(frame.tileid);
                  }
                }
              };

              _proto._buildLayerAndGroup = function _buildLayerAndGroup() {
                var tilesets = this._tilesets;
                var texGrids = this._texGrids;
                var animations = this._animations;
                texGrids.clear();

                for (var i = 0, l = tilesets.length; i < l; ++i) {
                  var tilesetInfo = tilesets[i];
                  if (!tilesetInfo) continue;

                  if (!tilesetInfo.sourceImage) {
                    console.warn("Can't find the spriteFrame of tilesets " + i);
                    continue;
                  }

                  fillTextureGrids(tilesetInfo, texGrids, tilesetInfo.sourceImage);
                }

                this._fillAniGrids(texGrids, animations);

                var layers = this._layers;
                var groups = this._groups;
                var images = this._images;
                var oldNodeNames = {};

                for (var _i5 = 0, n = layers.length; _i5 < n; _i5++) {
                  oldNodeNames[layers[_i5].node.name] = true;
                }

                for (var _i6 = 0, _n = groups.length; _i6 < _n; _i6++) {
                  oldNodeNames[groups[_i6].node.name] = true;
                }

                for (var _i7 = 0, _n2 = images.length; _i7 < _n2; _i7++) {
                  oldNodeNames[images[_i7].name] = true;
                }

                layers = this._layers = [];
                groups = this._groups = [];
                images = this._images = [];
                var mapInfo = this._mapInfo;
                var node = this.node;
                var layerInfos = mapInfo.getAllChildren();
                var textures = this._textures;
                var maxWidth = 0;
                var maxHeight = 0;

                if (layerInfos && layerInfos.length > 0) {
                  for (var _i8 = 0, len = layerInfos.length; _i8 < len; _i8++) {
                    var layerInfo = layerInfos[_i8];
                    var name = layerInfo.name;
                    var 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(_i8);
                    child.active = layerInfo.visible;

                    if (layerInfo instanceof TMXLayerInfo) {
                      var 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) {
                      var group = child.getComponent(TiledObjectGroup);

                      if (!group) {
                        group = child.addComponent(TiledObjectGroup);
                      }

                      group._init(layerInfo, mapInfo, texGrids);

                      groups.push(group);
                    } else if (layerInfo instanceof TMXImageLayerInfo) {
                      var texture = layerInfo.sourceImage;
                      child.layerInfo = layerInfo;
                      child._offset = new Vec2(layerInfo.offset.x, -layerInfo.offset.y);
                      var image = child.getComponent(Sprite);

                      if (!image) {
                        image = child.addComponent(Sprite);
                      }

                      var color = image.color;
                      color.a *= layerInfo.opacity;
                      image.spriteFrame = texture;

                      child._uiProps.uiTransformComp.setContentSize(texture.width, texture.height);

                      images.push(child);
                    }

                    maxWidth = Math.max(maxWidth, child._uiProps.uiTransformComp.width);
                    maxHeight = Math.max(maxHeight, child._uiProps.uiTransformComp.height);
                  }
                }

                var children = node.children;

                for (var _i9 = 0, _n3 = children.length; _i9 < _n3; _i9++) {
                  var c = children[_i9];

                  if (oldNodeNames[c.name]) {
                    c.destroy();
                  }
                }

                this.node._uiProps.uiTransformComp.setContentSize(maxWidth, maxHeight);

                this._syncAnchorPoint();
              };

              _proto._buildWithMapInfo = function _buildWithMapInfo(mapInfo) {
                var _this2 = this;

                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();
                var tilesets = this._tilesets;
                this._textures.length = 0;
                var totalTextures = [];

                for (var i = 0, l = tilesets.length; i < l; ++i) {
                  var tilesetInfo = tilesets[i];
                  if (!tilesetInfo || !tilesetInfo.sourceImage) continue;
                  this._textures[i] = tilesetInfo.sourceImage;
                  totalTextures.push(tilesetInfo.sourceImage);
                }

                for (var _i10 = 0; _i10 < this._imageLayers.length; _i10++) {
                  var imageLayer = this._imageLayers[_i10];
                  if (!imageLayer || !imageLayer.sourceImage) continue;
                  totalTextures.push(imageLayer.sourceImage);
                }

                loadAllTextures(totalTextures, function () {
                  _this2._buildLayerAndGroup();

                  if (_this2.cleanupImageCache) {
                    _this2._textures.forEach(function (tex) {
                      _this2.doCleanupImageCache(tex);
                    });
                  }
                });
              };

              _proto.doCleanupImageCache = function doCleanupImageCache(texture) {
                if (texture._image instanceof HTMLImageElement) {
                  texture._image.src = '';
                } else if (sys.capabilities.imageBitmap && texture._image instanceof ImageBitmap) {
                  if (texture._image.close) texture._image.close();
                }

                texture._image = null;
              };

              _proto.update = function update(dt) {
                var animations = this._animations;
                var texGrids = this._texGrids;

                for (var _iterator2 = _createForOfIteratorHelperLoose(animations.keys()), _step2; !(_step2 = _iterator2()).done;) {
                  var aniGID = _step2.value;
                  var animation = animations.get(aniGID);
                  var frames = animation.frames;
                  var 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);
                }

                for (var _iterator3 = _createForOfIteratorHelperLoose(this.getLayers()), _step3; !(_step3 = _iterator3()).done;) {
                  var layer = _step3.value;

                  if (layer.hasAnimation()) {
                    layer.markForUpdateRenderData();
                  }
                }
              };

              _createClass(TiledMap, [{
                key: "tmxAsset",
                get: function get() {
                  return this._tmxFile;
                },
                set: function set(value) {
                  if (this._tmxFile !== value || EDITOR) {
                    this._tmxFile = value;

                    if (this._preloaded || EDITOR) {
                      this._applyFile();
                    }
                  }
                }
              }, {
                key: "enableCulling",
                get: function get() {
                  return this._enableCulling;
                },
                set: function set(value) {
                  this._enableCulling = value;
                  var layers = this._layers;

                  for (var i = 0; i < layers.length; ++i) {
                    layers[i].enableCulling = value;
                  }
                }
              }]);

              return TiledMap;
            }(Component), _class3$H.Orientation = Orientation$1, _class3$H.Property = Property, _class3$H.TileFlag = TileFlag, _class3$H.StaggerAxis = StaggerAxis, _class3$H.StaggerIndex = StaggerIndex, _class3$H.TMXObjectType = TMXObjectType, _class3$H.RenderOrder = RenderOrder, _temp$1L), (_descriptor$1s = _applyDecoratedDescriptor(_class2$1E.prototype, "_tmxFile", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _applyDecoratedDescriptor(_class2$1E.prototype, "tmxAsset", [_dec5$J, _dec6$C], Object.getOwnPropertyDescriptor(_class2$1E.prototype, "tmxAsset"), _class2$1E.prototype), _descriptor2$18 = _applyDecoratedDescriptor(_class2$1E.prototype, "_enableCulling", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _applyDecoratedDescriptor(_class2$1E.prototype, "enableCulling", [editable], Object.getOwnPropertyDescriptor(_class2$1E.prototype, "enableCulling"), _class2$1E.prototype), _descriptor3$R = _applyDecoratedDescriptor(_class2$1E.prototype, "cleanupImageCache", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            })), _class2$1E)) || _class$1U) || _class$1U) || _class$1U) || _class$1U) || _class$1U));

            var MaxGridsLimit = Math.ceil(65535 / 6);
            var vec3_temps$3 = [];

            for (var i$5 = 0; i$5 < 4; i$5++) {
              vec3_temps$3.push(new Vec3());
            }

            var _mat4_temp$5 = new Mat4();

            var _vec3u_temp = new Vec3();

            var _leftDown = {
              row: 0,
              col: 0
            };
            var _uva = {
              x: 0,
              y: 0
            };
            var _uvb = {
              x: 0,
              y: 0
            };
            var _uvc = {
              x: 0,
              y: 0
            };
            var _uvd = {
              x: 0,
              y: 0
            };

            var _renderData$1;

            var _fillGrids = 0;
            var _vfOffset = 0;
            var _moveX = 0;
            var _moveY = 0;
            var flipTexture;
            var simple$1 = {
              createData: function createData(layer) {
                var renderData = layer.requestMeshRenderData();
                var maxGrids = layer.rightTop.col * layer.rightTop.row;

                if (maxGrids * 4 > 65535) {
                  console.error('Vertex count exceeds 65535');
                }

                return renderData;
              },
              updateRenderData: function updateRenderData(comp, ui) {
                comp.updateCulling();
                var renderData = comp.requestMeshRenderData();
                _moveX = comp.leftDownToCenterX;
                _moveY = comp.leftDownToCenterY;
                _renderData$1 = renderData;

                if (comp.colorChanged || comp.isCullingDirty() || comp.isUserNodeDirty() || comp.hasAnimation() || comp.hasTiledNode()) {
                  comp.colorChanged = false;
                  comp.destroyRenderData();
                  var leftDown;
                  var rightTop;

                  if (comp.enableCulling) {
                    var cullingRect = comp.cullingRect;
                    leftDown = cullingRect.leftDown;
                    rightTop = cullingRect.rightTop;
                  } else {
                    leftDown = _leftDown;
                    rightTop = comp.rightTop;
                  }

                  switch (comp.renderOrder) {
                    case RenderOrder.RightDown:
                      traverseGrids(leftDown, rightTop, -1, 1, comp);
                      break;

                    case RenderOrder.LeftDown:
                      traverseGrids(leftDown, rightTop, -1, -1, comp);
                      break;

                    case RenderOrder.RightUp:
                      traverseGrids(leftDown, rightTop, 1, 1, comp);
                      break;

                    case RenderOrder.LeftUp:
                    default:
                      traverseGrids(leftDown, rightTop, 1, -1, comp);
                      break;
                  }

                  comp.setCullingDirty(false);
                  comp.setUserNodeDirty(false);
                }

                _renderData$1 = null;
              },
              updateColor: function updateColor(tiled) {
                var color = tiled.color;
                var colorV = new Float32Array(4);
                colorV[0] = color.r / 255;
                colorV[1] = color.g / 255;
                colorV[2] = color.b / 255;
                colorV[0] = color.a / 255;
                var rs = tiled.meshRenderDataArray;

                if (rs) {
                  for (var _iterator = _createForOfIteratorHelperLoose(rs), _step; !(_step = _iterator()).done;) {
                    var r = _step.value;
                    if (!r.renderData) continue;
                    var renderData = r.renderData;
                    var vs = renderData.vData;

                    for (var _i = renderData.vertexStart, l = renderData.vertexCount; _i < l; _i++) {
                      vs.set(colorV, _i * 9 + 5);
                    }
                  }
                }
              },
              fillBuffers: function fillBuffers(layer, renderer) {
                if (!layer || !layer.meshRenderDataArray) return;
                var dataArray = layer.meshRenderDataArray;
                var node = layer.node;
                var buffer = renderer.acquireBufferBatch();
                var vertexOffset = buffer.byteOffset >> 2;
                var indicesOffset = buffer.indicesOffset;
                var vertexId = buffer.vertexOffset;
                var data = dataArray[layer._meshRenderDataArrayIdx];
                var renderData = data.renderData;
                var isRecreate = buffer.request(renderData.vertexCount, renderData.indicesCount);

                if (!isRecreate) {
                  buffer = renderer.currBufferBatch;
                  vertexOffset = 0;
                  indicesOffset = 0;
                  vertexId = 0;
                }

                var vBuf = buffer.vData;
                var iBuf = buffer.iData;
                var matrix = node.worldMatrix;
                var srcVBuf = renderData.vData;
                var srcVIdx = renderData.vertexStart;
                vBuf.set(srcVBuf.slice(srcVIdx, srcVIdx + renderData.vertexCount * 9), vertexOffset);

                for (var _i2 = 0; _i2 < renderData.vertexCount; _i2++) {
                  var pOffset = vertexOffset + _i2 * 9;

                  _vec3u_temp.set(vBuf[pOffset], vBuf[pOffset + 1], vBuf[pOffset + 2]);

                  _vec3u_temp.transformMat4(matrix);

                  vBuf[pOffset] = _vec3u_temp.x;
                  vBuf[pOffset + 1] = _vec3u_temp.y;
                  vBuf[pOffset + 2] = _vec3u_temp.z;
                }

                var quadCount = renderData.vertexCount / 4;

                for (var _i3 = 0; _i3 < quadCount; _i3 += 1) {
                  iBuf[indicesOffset] = vertexId;
                  iBuf[indicesOffset + 1] = vertexId + 1;
                  iBuf[indicesOffset + 2] = vertexId + 2;
                  iBuf[indicesOffset + 3] = vertexId + 2;
                  iBuf[indicesOffset + 4] = vertexId + 1;
                  iBuf[indicesOffset + 5] = vertexId + 3;
                  indicesOffset += 6;
                  vertexId += 4;
                }
              }
            };

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

              var tempVal;

              if ((gid & TileFlag.DIAGONAL) >>> 0) {
                tempVal = _uvb;
                _uvb = _uvc;
                _uvc = tempVal;
              }

              if ((gid & TileFlag.HORIZONTAL) >>> 0) {
                tempVal = _uva;
                _uva = _uvc;
                _uvc = tempVal;
                tempVal = _uvb;
                _uvb = _uvd;
                _uvd = tempVal;
              }

              if ((gid & TileFlag.VERTICAL) >>> 0) {
                tempVal = _uva;
                _uva = _uvb;
                _uvb = tempVal;
                tempVal = _uvc;
                _uvc = _uvd;
                _uvd = tempVal;
              }
            }

            function switchRenderData(curTexIdx, grid, comp) {
              if (!curTexIdx) curTexIdx = grid.texture;

              if (!_renderData$1.texture) {
                _renderData$1.texture = curTexIdx;
              }

              _renderData$1 = comp.requestMeshRenderData();
              _renderData$1.texture = grid.texture;
            }

            function traverseGrids(leftDown, rightTop, rowMoveDir, colMoveDir, comp) {
              if (!_renderData$1 || rightTop.row < 0 || rightTop.col < 0) return;

              if (!_renderData$1.renderData) {
                _renderData$1 = comp.requestMeshRenderData();
              }

              var vertexBuf = _renderData$1.renderData.vData;
              _fillGrids = 0;
              _vfOffset = 0;
              var tiledTiles = comp.tiledTiles;
              var texGrids = comp.texGrids;
              var tiles = comp.tiles;
              var vertStep = 9;
              var vertStep2 = vertStep * 2;
              var vertStep3 = vertStep * 3;
              var vertices = comp.vertices;
              var rowData;
              var col;
              var cols;
              var row;
              var rows;
              var colData;
              var tileSize;
              var grid;
              var gid = 0;
              var left = 0;
              var bottom = 0;
              var right = 0;
              var top = 0;
              var tiledNode;
              var curTexIdx = null;
              var colNodesCount = 0;
              var checkColRange = true;
              var diamondTile = false;
              flipTexture =  _flipTexture;
              var 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;
              }

              for (; (rows - row) * rowMoveDir >= 0; row += rowMoveDir) {
                rowData = vertices[row];
                colNodesCount = comp.getNodesCountByRow(row);
                checkColRange = rowData && colNodesCount === 0;

                if (colMoveDir === 1) {
                  col = checkColRange && leftDown.col < rowData.minCol ? rowData.minCol : leftDown.col;
                  cols = checkColRange && rightTop.col > rowData.maxCol ? rowData.maxCol : rightTop.col;
                } else {
                  col = checkColRange && rightTop.col > rowData.maxCol ? rowData.maxCol : rightTop.col;
                  cols = checkColRange && leftDown.col < rowData.minCol ? rowData.minCol : leftDown.col;
                }

                for (; (cols - col) * colMoveDir >= 0; col += colMoveDir) {
                  colData = rowData && rowData[col];

                  if (colNodesCount > 0) {
                    var nodes = comp.requestSubNodesData();
                    var celData = comp.getNodesByRowCol(row, col);

                    if (celData && celData.count > 0) {
                      nodes.subNodes = comp.getNodesByRowCol(row, col).list;
                      curTexIdx = null;
                      _renderData$1 = comp.requestMeshRenderData();
                    }
                  }

                  if (!colData) {
                    continue;
                  }

                  gid = tiles[colData.index];
                  grid = texGrids.get((gid & TileFlag.FLIPPED_MASK) >>> 0);
                  if (!grid) continue;

                  if (curTexIdx !== grid.texture) {
                    switchRenderData(curTexIdx, grid, comp);
                    curTexIdx = 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];

                  _renderData$1.renderData.reserve(4, 0);

                  _vfOffset = _renderData$1.renderData.vertexCount * 9;
                  vertexBuf = _renderData$1.renderData.vData;

                  if (!tiledNode) {
                    {
                      vertexBuf[_vfOffset] = left;
                      vertexBuf[_vfOffset + 1] = top;
                      vertexBuf[_vfOffset + vertStep] = left;
                      vertexBuf[_vfOffset + vertStep + 1] = bottom;
                      vertexBuf[_vfOffset + vertStep2] = right;
                      vertexBuf[_vfOffset + vertStep2 + 1] = top;
                      vertexBuf[_vfOffset + vertStep3] = right;
                      vertexBuf[_vfOffset + vertStep3 + 1] = bottom;
                    }

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

                  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;
                  _fillGrids++;

                  _renderData$1.renderData.advance(4, 6);

                  if (_fillGrids >= MaxGridsLimit) {
                    switchRenderData(curTexIdx, grid, comp);
                    curTexIdx = grid.texture;
                  }
                }
              }
            }

            function fillByTiledNode(tiledNode, color, vbuf, left, right, top, bottom, diamondTile) {
              var vertStep = 9;
              var vertStep2 = vertStep * 2;
              var vertStep3 = vertStep * 3;
              tiledNode.updateWorldTransform();
              Mat4.fromRTS(_mat4_temp$5, tiledNode.getRotation(), tiledNode.getPosition(), tiledNode.getScale());
              Vec3.set(_vec3u_temp, -(left + _moveX), -(bottom + _moveY), 0);
              Mat4.transform(_mat4_temp$5, _mat4_temp$5, _vec3u_temp);
              var m = _mat4_temp$5;
              var tx = m.m12;
              var ty = m.m13;
              var a = m.m00;
              var b = m.m01;
              var c = m.m04;
              var d = m.m05;
              var justTranslate = a === 1 && b === 0 && c === 0 && d === 1;

              if (diamondTile) {
                var centerX = (left + right) / 2;
                var centerY = (top + bottom) / 2;

                if (justTranslate) {
                  vbuf[_vfOffset] = centerX + tx;
                  vbuf[_vfOffset + 1] = top + ty;
                  vbuf[_vfOffset + vertStep] = left + tx;
                  vbuf[_vfOffset + vertStep + 1] = centerY + ty;
                  vbuf[_vfOffset + vertStep2] = right + tx;
                  vbuf[_vfOffset + vertStep2 + 1] = centerY + ty;
                  vbuf[_vfOffset + vertStep3] = centerX + tx;
                  vbuf[_vfOffset + vertStep3 + 1] = bottom + ty;
                } else {
                  vbuf[_vfOffset] = centerX * a + top * c + tx;
                  vbuf[_vfOffset + 1] = centerX * b + top * d + ty;
                  vbuf[_vfOffset + vertStep] = left * a + centerY * c + tx;
                  vbuf[_vfOffset + vertStep + 1] = left * b + centerY * d + ty;
                  vbuf[_vfOffset + vertStep2] = right * a + centerY * c + tx;
                  vbuf[_vfOffset + vertStep2 + 1] = right * b + centerY * d + ty;
                  vbuf[_vfOffset + vertStep3] = centerX * a + bottom * c + tx;
                  vbuf[_vfOffset + vertStep3 + 1] = centerX * b + bottom * d + ty;
                }
              } else 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);
            }

            var tiledLayerAssembler = exports('tiledLayerAssembler', {
              getAssembler: function getAssembler() {
                return simple$1;
              }
            });
            TiledLayer.Assembler = tiledLayerAssembler;

            var __extends = undefined && undefined.__extends || function () {
              var _extendStatics = function extendStatics(d, b) {
                _extendStatics = Object.setPrototypeOf || {
                  __proto__: []
                } instanceof Array && function (d, b) {
                  d.__proto__ = b;
                } || function (d, b) {
                  for (var p in b) {
                    if (b.hasOwnProperty(p)) d[p] = b[p];
                  }
                };

                return _extendStatics(d, b);
              };

              return function (d, b) {
                _extendStatics(d, b);

                function __() {
                  this.constructor = d;
                }

                d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
              };
            }();

            var spine;

            (function (spine) {
              var Animation = function () {
                function Animation(name, timelines, duration) {
                  if (name == null) throw new Error("name cannot be null.");
                  if (timelines == null) throw new Error("timelines cannot be null.");
                  this.name = name;
                  this.timelines = timelines;
                  this.timelineIds = [];

                  for (var i = 0; i < timelines.length; i++) {
                    this.timelineIds[timelines[i].getPropertyId()] = true;
                  }

                  this.duration = duration;
                }

                Animation.prototype.hasTimeline = function (id) {
                  return this.timelineIds[id] == true;
                };

                Animation.prototype.apply = function (skeleton, lastTime, time, loop, events, alpha, blend, direction) {
                  if (skeleton == null) throw new Error("skeleton cannot be null.");

                  if (loop && this.duration != 0) {
                    time %= this.duration;
                    if (lastTime > 0) lastTime %= this.duration;
                  }

                  var timelines = this.timelines;

                  for (var i = 0, n = timelines.length; i < n; i++) {
                    timelines[i].apply(skeleton, lastTime, time, events, alpha, blend, direction);
                  }
                };

                Animation.binarySearch = function (values, target, step) {
                  if (step === void 0) {
                    step = 1;
                  }

                  var low = 0;
                  var high = values.length / step - 2;
                  if (high == 0) return step;
                  var current = high >>> 1;

                  while (true) {
                    if (values[(current + 1) * step] <= target) low = current + 1;else high = current;
                    if (low == high) return (low + 1) * step;
                    current = low + high >>> 1;
                  }
                };

                Animation.linearSearch = function (values, target, step) {
                  for (var i = 0, last = values.length - step; i <= last; i += step) {
                    if (values[i] > target) return i;
                  }

                  return -1;
                };

                return Animation;
              }();

              spine.Animation = Animation;
              var MixBlend;

              (function (MixBlend) {
                MixBlend[MixBlend["setup"] = 0] = "setup";
                MixBlend[MixBlend["first"] = 1] = "first";
                MixBlend[MixBlend["replace"] = 2] = "replace";
                MixBlend[MixBlend["add"] = 3] = "add";
              })(MixBlend = spine.MixBlend || (spine.MixBlend = {}));

              var MixDirection;

              (function (MixDirection) {
                MixDirection[MixDirection["mixIn"] = 0] = "mixIn";
                MixDirection[MixDirection["mixOut"] = 1] = "mixOut";
              })(MixDirection = spine.MixDirection || (spine.MixDirection = {}));

              var TimelineType;

              (function (TimelineType) {
                TimelineType[TimelineType["rotate"] = 0] = "rotate";
                TimelineType[TimelineType["translate"] = 1] = "translate";
                TimelineType[TimelineType["scale"] = 2] = "scale";
                TimelineType[TimelineType["shear"] = 3] = "shear";
                TimelineType[TimelineType["attachment"] = 4] = "attachment";
                TimelineType[TimelineType["color"] = 5] = "color";
                TimelineType[TimelineType["deform"] = 6] = "deform";
                TimelineType[TimelineType["event"] = 7] = "event";
                TimelineType[TimelineType["drawOrder"] = 8] = "drawOrder";
                TimelineType[TimelineType["ikConstraint"] = 9] = "ikConstraint";
                TimelineType[TimelineType["transformConstraint"] = 10] = "transformConstraint";
                TimelineType[TimelineType["pathConstraintPosition"] = 11] = "pathConstraintPosition";
                TimelineType[TimelineType["pathConstraintSpacing"] = 12] = "pathConstraintSpacing";
                TimelineType[TimelineType["pathConstraintMix"] = 13] = "pathConstraintMix";
                TimelineType[TimelineType["twoColor"] = 14] = "twoColor";
              })(TimelineType = spine.TimelineType || (spine.TimelineType = {}));

              var CurveTimeline = function () {
                function CurveTimeline(frameCount) {
                  if (frameCount <= 0) throw new Error("frameCount must be > 0: " + frameCount);
                  this.curves = spine.Utils.newFloatArray((frameCount - 1) * CurveTimeline.BEZIER_SIZE);
                }

                CurveTimeline.prototype.getFrameCount = function () {
                  return this.curves.length / CurveTimeline.BEZIER_SIZE + 1;
                };

                CurveTimeline.prototype.setLinear = function (frameIndex) {
                  this.curves[frameIndex * CurveTimeline.BEZIER_SIZE] = CurveTimeline.LINEAR;
                };

                CurveTimeline.prototype.setStepped = function (frameIndex) {
                  this.curves[frameIndex * CurveTimeline.BEZIER_SIZE] = CurveTimeline.STEPPED;
                };

                CurveTimeline.prototype.getCurveType = function (frameIndex) {
                  var index = frameIndex * CurveTimeline.BEZIER_SIZE;
                  if (index == this.curves.length) return CurveTimeline.LINEAR;
                  var type = this.curves[index];
                  if (type == CurveTimeline.LINEAR) return CurveTimeline.LINEAR;
                  if (type == CurveTimeline.STEPPED) return CurveTimeline.STEPPED;
                  return CurveTimeline.BEZIER;
                };

                CurveTimeline.prototype.setCurve = function (frameIndex, cx1, cy1, cx2, cy2) {
                  var tmpx = (-cx1 * 2 + cx2) * 0.03,
                      tmpy = (-cy1 * 2 + cy2) * 0.03;
                  var dddfx = ((cx1 - cx2) * 3 + 1) * 0.006,
                      dddfy = ((cy1 - cy2) * 3 + 1) * 0.006;
                  var ddfx = tmpx * 2 + dddfx,
                      ddfy = tmpy * 2 + dddfy;
                  var dfx = cx1 * 0.3 + tmpx + dddfx * 0.16666667,
                      dfy = cy1 * 0.3 + tmpy + dddfy * 0.16666667;
                  var i = frameIndex * CurveTimeline.BEZIER_SIZE;
                  var curves = this.curves;
                  curves[i++] = CurveTimeline.BEZIER;
                  var x = dfx,
                      y = dfy;

                  for (var n = i + CurveTimeline.BEZIER_SIZE - 1; i < n; i += 2) {
                    curves[i] = x;
                    curves[i + 1] = y;
                    dfx += ddfx;
                    dfy += ddfy;
                    ddfx += dddfx;
                    ddfy += dddfy;
                    x += dfx;
                    y += dfy;
                  }
                };

                CurveTimeline.prototype.getCurvePercent = function (frameIndex, percent) {
                  percent = spine.MathUtils.clamp(percent, 0, 1);
                  var curves = this.curves;
                  var i = frameIndex * CurveTimeline.BEZIER_SIZE;
                  var type = curves[i];
                  if (type == CurveTimeline.LINEAR) return percent;
                  if (type == CurveTimeline.STEPPED) return 0;
                  i++;
                  var x = 0;

                  for (var start = i, n = i + CurveTimeline.BEZIER_SIZE - 1; i < n; i += 2) {
                    x = curves[i];

                    if (x >= percent) {
                      var prevX = void 0,
                          prevY = void 0;

                      if (i == start) {
                        prevX = 0;
                        prevY = 0;
                      } else {
                        prevX = curves[i - 2];
                        prevY = curves[i - 1];
                      }

                      return prevY + (curves[i + 1] - prevY) * (percent - prevX) / (x - prevX);
                    }
                  }

                  var y = curves[i - 1];
                  return y + (1 - y) * (percent - x) / (1 - x);
                };

                CurveTimeline.LINEAR = 0;
                CurveTimeline.STEPPED = 1;
                CurveTimeline.BEZIER = 2;
                CurveTimeline.BEZIER_SIZE = 10 * 2 - 1;
                return CurveTimeline;
              }();

              spine.CurveTimeline = CurveTimeline;

              var RotateTimeline = function (_super) {
                __extends(RotateTimeline, _super);

                function RotateTimeline(frameCount) {
                  var _this = _super.call(this, frameCount) || this;

                  _this.frames = spine.Utils.newFloatArray(frameCount << 1);
                  return _this;
                }

                RotateTimeline.prototype.getPropertyId = function () {
                  return (TimelineType.rotate << 24) + this.boneIndex;
                };

                RotateTimeline.prototype.setFrame = function (frameIndex, time, degrees) {
                  frameIndex <<= 1;
                  this.frames[frameIndex] = time;
                  this.frames[frameIndex + RotateTimeline.ROTATION] = degrees;
                };

                RotateTimeline.prototype.apply = function (skeleton, lastTime, time, events, alpha, blend, direction) {
                  var frames = this.frames;
                  var bone = skeleton.bones[this.boneIndex];
                  if (!bone.active) return;

                  if (time < frames[0]) {
                    switch (blend) {
                      case MixBlend.setup:
                        bone.rotation = bone.data.rotation;
                        return;

                      case MixBlend.first:
                        var r_1 = bone.data.rotation - bone.rotation;
                        bone.rotation += (r_1 - (16384 - (16384.499999999996 - r_1 / 360 | 0)) * 360) * alpha;
                    }

                    return;
                  }

                  if (time >= frames[frames.length - RotateTimeline.ENTRIES]) {
                    var r_2 = frames[frames.length + RotateTimeline.PREV_ROTATION];

                    switch (blend) {
                      case MixBlend.setup:
                        bone.rotation = bone.data.rotation + r_2 * alpha;
                        break;

                      case MixBlend.first:
                      case MixBlend.replace:
                        r_2 += bone.data.rotation - bone.rotation;
                        r_2 -= (16384 - (16384.499999999996 - r_2 / 360 | 0)) * 360;

                      case MixBlend.add:
                        bone.rotation += r_2 * alpha;
                    }

                    return;
                  }

                  var frame = Animation.binarySearch(frames, time, RotateTimeline.ENTRIES);
                  var prevRotation = frames[frame + RotateTimeline.PREV_ROTATION];
                  var frameTime = frames[frame];
                  var percent = this.getCurvePercent((frame >> 1) - 1, 1 - (time - frameTime) / (frames[frame + RotateTimeline.PREV_TIME] - frameTime));
                  var r = frames[frame + RotateTimeline.ROTATION] - prevRotation;
                  r = prevRotation + (r - (16384 - (16384.499999999996 - r / 360 | 0)) * 360) * percent;

                  switch (blend) {
                    case MixBlend.setup:
                      bone.rotation = bone.data.rotation + (r - (16384 - (16384.499999999996 - r / 360 | 0)) * 360) * alpha;
                      break;

                    case MixBlend.first:
                    case MixBlend.replace:
                      r += bone.data.rotation - bone.rotation;

                    case MixBlend.add:
                      bone.rotation += (r - (16384 - (16384.499999999996 - r / 360 | 0)) * 360) * alpha;
                  }
                };

                RotateTimeline.ENTRIES = 2;
                RotateTimeline.PREV_TIME = -2;
                RotateTimeline.PREV_ROTATION = -1;
                RotateTimeline.ROTATION = 1;
                return RotateTimeline;
              }(CurveTimeline);

              spine.RotateTimeline = RotateTimeline;

              var TranslateTimeline = function (_super) {
                __extends(TranslateTimeline, _super);

                function TranslateTimeline(frameCount) {
                  var _this = _super.call(this, frameCount) || this;

                  _this.frames = spine.Utils.newFloatArray(frameCount * TranslateTimeline.ENTRIES);
                  return _this;
                }

                TranslateTimeline.prototype.getPropertyId = function () {
                  return (TimelineType.translate << 24) + this.boneIndex;
                };

                TranslateTimeline.prototype.setFrame = function (frameIndex, time, x, y) {
                  frameIndex *= TranslateTimeline.ENTRIES;
                  this.frames[frameIndex] = time;
                  this.frames[frameIndex + TranslateTimeline.X] = x;
                  this.frames[frameIndex + TranslateTimeline.Y] = y;
                };

                TranslateTimeline.prototype.apply = function (skeleton, lastTime, time, events, alpha, blend, direction) {
                  var frames = this.frames;
                  var bone = skeleton.bones[this.boneIndex];
                  if (!bone.active) return;

                  if (time < frames[0]) {
                    switch (blend) {
                      case MixBlend.setup:
                        bone.x = bone.data.x;
                        bone.y = bone.data.y;
                        return;

                      case MixBlend.first:
                        bone.x += (bone.data.x - bone.x) * alpha;
                        bone.y += (bone.data.y - bone.y) * alpha;
                    }

                    return;
                  }

                  var x = 0,
                      y = 0;

                  if (time >= frames[frames.length - TranslateTimeline.ENTRIES]) {
                    x = frames[frames.length + TranslateTimeline.PREV_X];
                    y = frames[frames.length + TranslateTimeline.PREV_Y];
                  } else {
                    var frame = Animation.binarySearch(frames, time, TranslateTimeline.ENTRIES);
                    x = frames[frame + TranslateTimeline.PREV_X];
                    y = frames[frame + TranslateTimeline.PREV_Y];
                    var frameTime = frames[frame];
                    var percent = this.getCurvePercent(frame / TranslateTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + TranslateTimeline.PREV_TIME] - frameTime));
                    x += (frames[frame + TranslateTimeline.X] - x) * percent;
                    y += (frames[frame + TranslateTimeline.Y] - y) * percent;
                  }

                  switch (blend) {
                    case MixBlend.setup:
                      bone.x = bone.data.x + x * alpha;
                      bone.y = bone.data.y + y * alpha;
                      break;

                    case MixBlend.first:
                    case MixBlend.replace:
                      bone.x += (bone.data.x + x - bone.x) * alpha;
                      bone.y += (bone.data.y + y - bone.y) * alpha;
                      break;

                    case MixBlend.add:
                      bone.x += x * alpha;
                      bone.y += y * alpha;
                  }
                };

                TranslateTimeline.ENTRIES = 3;
                TranslateTimeline.PREV_TIME = -3;
                TranslateTimeline.PREV_X = -2;
                TranslateTimeline.PREV_Y = -1;
                TranslateTimeline.X = 1;
                TranslateTimeline.Y = 2;
                return TranslateTimeline;
              }(CurveTimeline);

              spine.TranslateTimeline = TranslateTimeline;

              var ScaleTimeline = function (_super) {
                __extends(ScaleTimeline, _super);

                function ScaleTimeline(frameCount) {
                  return _super.call(this, frameCount) || this;
                }

                ScaleTimeline.prototype.getPropertyId = function () {
                  return (TimelineType.scale << 24) + this.boneIndex;
                };

                ScaleTimeline.prototype.apply = function (skeleton, lastTime, time, events, alpha, blend, direction) {
                  var frames = this.frames;
                  var bone = skeleton.bones[this.boneIndex];
                  if (!bone.active) return;

                  if (time < frames[0]) {
                    switch (blend) {
                      case MixBlend.setup:
                        bone.scaleX = bone.data.scaleX;
                        bone.scaleY = bone.data.scaleY;
                        return;

                      case MixBlend.first:
                        bone.scaleX += (bone.data.scaleX - bone.scaleX) * alpha;
                        bone.scaleY += (bone.data.scaleY - bone.scaleY) * alpha;
                    }

                    return;
                  }

                  var x = 0,
                      y = 0;

                  if (time >= frames[frames.length - ScaleTimeline.ENTRIES]) {
                    x = frames[frames.length + ScaleTimeline.PREV_X] * bone.data.scaleX;
                    y = frames[frames.length + ScaleTimeline.PREV_Y] * bone.data.scaleY;
                  } else {
                    var frame = Animation.binarySearch(frames, time, ScaleTimeline.ENTRIES);
                    x = frames[frame + ScaleTimeline.PREV_X];
                    y = frames[frame + ScaleTimeline.PREV_Y];
                    var frameTime = frames[frame];
                    var percent = this.getCurvePercent(frame / ScaleTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + ScaleTimeline.PREV_TIME] - frameTime));
                    x = (x + (frames[frame + ScaleTimeline.X] - x) * percent) * bone.data.scaleX;
                    y = (y + (frames[frame + ScaleTimeline.Y] - y) * percent) * bone.data.scaleY;
                  }

                  if (alpha == 1) {
                    if (blend == MixBlend.add) {
                      bone.scaleX += x - bone.data.scaleX;
                      bone.scaleY += y - bone.data.scaleY;
                    } else {
                      bone.scaleX = x;
                      bone.scaleY = y;
                    }
                  } else {
                    var bx = 0,
                        by = 0;

                    if (direction == MixDirection.mixOut) {
                      switch (blend) {
                        case MixBlend.setup:
                          bx = bone.data.scaleX;
                          by = bone.data.scaleY;
                          bone.scaleX = bx + (Math.abs(x) * spine.MathUtils.signum(bx) - bx) * alpha;
                          bone.scaleY = by + (Math.abs(y) * spine.MathUtils.signum(by) - by) * alpha;
                          break;

                        case MixBlend.first:
                        case MixBlend.replace:
                          bx = bone.scaleX;
                          by = bone.scaleY;
                          bone.scaleX = bx + (Math.abs(x) * spine.MathUtils.signum(bx) - bx) * alpha;
                          bone.scaleY = by + (Math.abs(y) * spine.MathUtils.signum(by) - by) * alpha;
                          break;

                        case MixBlend.add:
                          bx = bone.scaleX;
                          by = bone.scaleY;
                          bone.scaleX = bx + (Math.abs(x) * spine.MathUtils.signum(bx) - bone.data.scaleX) * alpha;
                          bone.scaleY = by + (Math.abs(y) * spine.MathUtils.signum(by) - bone.data.scaleY) * alpha;
                      }
                    } else {
                      switch (blend) {
                        case MixBlend.setup:
                          bx = Math.abs(bone.data.scaleX) * spine.MathUtils.signum(x);
                          by = Math.abs(bone.data.scaleY) * spine.MathUtils.signum(y);
                          bone.scaleX = bx + (x - bx) * alpha;
                          bone.scaleY = by + (y - by) * alpha;
                          break;

                        case MixBlend.first:
                        case MixBlend.replace:
                          bx = Math.abs(bone.scaleX) * spine.MathUtils.signum(x);
                          by = Math.abs(bone.scaleY) * spine.MathUtils.signum(y);
                          bone.scaleX = bx + (x - bx) * alpha;
                          bone.scaleY = by + (y - by) * alpha;
                          break;

                        case MixBlend.add:
                          bx = spine.MathUtils.signum(x);
                          by = spine.MathUtils.signum(y);
                          bone.scaleX = Math.abs(bone.scaleX) * bx + (x - Math.abs(bone.data.scaleX) * bx) * alpha;
                          bone.scaleY = Math.abs(bone.scaleY) * by + (y - Math.abs(bone.data.scaleY) * by) * alpha;
                      }
                    }
                  }
                };

                return ScaleTimeline;
              }(TranslateTimeline);

              spine.ScaleTimeline = ScaleTimeline;

              var ShearTimeline = function (_super) {
                __extends(ShearTimeline, _super);

                function ShearTimeline(frameCount) {
                  return _super.call(this, frameCount) || this;
                }

                ShearTimeline.prototype.getPropertyId = function () {
                  return (TimelineType.shear << 24) + this.boneIndex;
                };

                ShearTimeline.prototype.apply = function (skeleton, lastTime, time, events, alpha, blend, direction) {
                  var frames = this.frames;
                  var bone = skeleton.bones[this.boneIndex];
                  if (!bone.active) return;

                  if (time < frames[0]) {
                    switch (blend) {
                      case MixBlend.setup:
                        bone.shearX = bone.data.shearX;
                        bone.shearY = bone.data.shearY;
                        return;

                      case MixBlend.first:
                        bone.shearX += (bone.data.shearX - bone.shearX) * alpha;
                        bone.shearY += (bone.data.shearY - bone.shearY) * alpha;
                    }

                    return;
                  }

                  var x = 0,
                      y = 0;

                  if (time >= frames[frames.length - ShearTimeline.ENTRIES]) {
                    x = frames[frames.length + ShearTimeline.PREV_X];
                    y = frames[frames.length + ShearTimeline.PREV_Y];
                  } else {
                    var frame = Animation.binarySearch(frames, time, ShearTimeline.ENTRIES);
                    x = frames[frame + ShearTimeline.PREV_X];
                    y = frames[frame + ShearTimeline.PREV_Y];
                    var frameTime = frames[frame];
                    var percent = this.getCurvePercent(frame / ShearTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + ShearTimeline.PREV_TIME] - frameTime));
                    x = x + (frames[frame + ShearTimeline.X] - x) * percent;
                    y = y + (frames[frame + ShearTimeline.Y] - y) * percent;
                  }

                  switch (blend) {
                    case MixBlend.setup:
                      bone.shearX = bone.data.shearX + x * alpha;
                      bone.shearY = bone.data.shearY + y * alpha;
                      break;

                    case MixBlend.first:
                    case MixBlend.replace:
                      bone.shearX += (bone.data.shearX + x - bone.shearX) * alpha;
                      bone.shearY += (bone.data.shearY + y - bone.shearY) * alpha;
                      break;

                    case MixBlend.add:
                      bone.shearX += x * alpha;
                      bone.shearY += y * alpha;
                  }
                };

                return ShearTimeline;
              }(TranslateTimeline);

              spine.ShearTimeline = ShearTimeline;

              var ColorTimeline = function (_super) {
                __extends(ColorTimeline, _super);

                function ColorTimeline(frameCount) {
                  var _this = _super.call(this, frameCount) || this;

                  _this.frames = spine.Utils.newFloatArray(frameCount * ColorTimeline.ENTRIES);
                  return _this;
                }

                ColorTimeline.prototype.getPropertyId = function () {
                  return (TimelineType.color << 24) + this.slotIndex;
                };

                ColorTimeline.prototype.setFrame = function (frameIndex, time, r, g, b, a) {
                  frameIndex *= ColorTimeline.ENTRIES;
                  this.frames[frameIndex] = time;
                  this.frames[frameIndex + ColorTimeline.R] = r;
                  this.frames[frameIndex + ColorTimeline.G] = g;
                  this.frames[frameIndex + ColorTimeline.B] = b;
                  this.frames[frameIndex + ColorTimeline.A] = a;
                };

                ColorTimeline.prototype.apply = function (skeleton, lastTime, time, events, alpha, blend, direction) {
                  var slot = skeleton.slots[this.slotIndex];
                  if (!slot.bone.active) return;
                  var frames = this.frames;

                  if (time < frames[0]) {
                    switch (blend) {
                      case MixBlend.setup:
                        slot.color.setFromColor(slot.data.color);
                        return;

                      case MixBlend.first:
                        var color = slot.color,
                            setup = slot.data.color;
                        color.add((setup.r - color.r) * alpha, (setup.g - color.g) * alpha, (setup.b - color.b) * alpha, (setup.a - color.a) * alpha);
                    }

                    return;
                  }

                  var r = 0,
                      g = 0,
                      b = 0,
                      a = 0;

                  if (time >= frames[frames.length - ColorTimeline.ENTRIES]) {
                    var i = frames.length;
                    r = frames[i + ColorTimeline.PREV_R];
                    g = frames[i + ColorTimeline.PREV_G];
                    b = frames[i + ColorTimeline.PREV_B];
                    a = frames[i + ColorTimeline.PREV_A];
                  } else {
                    var frame = Animation.binarySearch(frames, time, ColorTimeline.ENTRIES);
                    r = frames[frame + ColorTimeline.PREV_R];
                    g = frames[frame + ColorTimeline.PREV_G];
                    b = frames[frame + ColorTimeline.PREV_B];
                    a = frames[frame + ColorTimeline.PREV_A];
                    var frameTime = frames[frame];
                    var percent = this.getCurvePercent(frame / ColorTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + ColorTimeline.PREV_TIME] - frameTime));
                    r += (frames[frame + ColorTimeline.R] - r) * percent;
                    g += (frames[frame + ColorTimeline.G] - g) * percent;
                    b += (frames[frame + ColorTimeline.B] - b) * percent;
                    a += (frames[frame + ColorTimeline.A] - a) * percent;
                  }

                  if (alpha == 1) slot.color.set(r, g, b, a);else {
                    var color = slot.color;
                    if (blend == MixBlend.setup) color.setFromColor(slot.data.color);
                    color.add((r - color.r) * alpha, (g - color.g) * alpha, (b - color.b) * alpha, (a - color.a) * alpha);
                  }
                };

                ColorTimeline.ENTRIES = 5;
                ColorTimeline.PREV_TIME = -5;
                ColorTimeline.PREV_R = -4;
                ColorTimeline.PREV_G = -3;
                ColorTimeline.PREV_B = -2;
                ColorTimeline.PREV_A = -1;
                ColorTimeline.R = 1;
                ColorTimeline.G = 2;
                ColorTimeline.B = 3;
                ColorTimeline.A = 4;
                return ColorTimeline;
              }(CurveTimeline);

              spine.ColorTimeline = ColorTimeline;

              var TwoColorTimeline = function (_super) {
                __extends(TwoColorTimeline, _super);

                function TwoColorTimeline(frameCount) {
                  var _this = _super.call(this, frameCount) || this;

                  _this.frames = spine.Utils.newFloatArray(frameCount * TwoColorTimeline.ENTRIES);
                  return _this;
                }

                TwoColorTimeline.prototype.getPropertyId = function () {
                  return (TimelineType.twoColor << 24) + this.slotIndex;
                };

                TwoColorTimeline.prototype.setFrame = function (frameIndex, time, r, g, b, a, r2, g2, b2) {
                  frameIndex *= TwoColorTimeline.ENTRIES;
                  this.frames[frameIndex] = time;
                  this.frames[frameIndex + TwoColorTimeline.R] = r;
                  this.frames[frameIndex + TwoColorTimeline.G] = g;
                  this.frames[frameIndex + TwoColorTimeline.B] = b;
                  this.frames[frameIndex + TwoColorTimeline.A] = a;
                  this.frames[frameIndex + TwoColorTimeline.R2] = r2;
                  this.frames[frameIndex + TwoColorTimeline.G2] = g2;
                  this.frames[frameIndex + TwoColorTimeline.B2] = b2;
                };

                TwoColorTimeline.prototype.apply = function (skeleton, lastTime, time, events, alpha, blend, direction) {
                  var slot = skeleton.slots[this.slotIndex];
                  if (!slot.bone.active) return;
                  var frames = this.frames;

                  if (time < frames[0]) {
                    switch (blend) {
                      case MixBlend.setup:
                        slot.color.setFromColor(slot.data.color);
                        slot.darkColor.setFromColor(slot.data.darkColor);
                        return;

                      case MixBlend.first:
                        var light = slot.color,
                            dark = slot.darkColor,
                            setupLight = slot.data.color,
                            setupDark = slot.data.darkColor;
                        light.add((setupLight.r - light.r) * alpha, (setupLight.g - light.g) * alpha, (setupLight.b - light.b) * alpha, (setupLight.a - light.a) * alpha);
                        dark.add((setupDark.r - dark.r) * alpha, (setupDark.g - dark.g) * alpha, (setupDark.b - dark.b) * alpha, 0);
                    }

                    return;
                  }

                  var r = 0,
                      g = 0,
                      b = 0,
                      a = 0,
                      r2 = 0,
                      g2 = 0,
                      b2 = 0;

                  if (time >= frames[frames.length - TwoColorTimeline.ENTRIES]) {
                    var i = frames.length;
                    r = frames[i + TwoColorTimeline.PREV_R];
                    g = frames[i + TwoColorTimeline.PREV_G];
                    b = frames[i + TwoColorTimeline.PREV_B];
                    a = frames[i + TwoColorTimeline.PREV_A];
                    r2 = frames[i + TwoColorTimeline.PREV_R2];
                    g2 = frames[i + TwoColorTimeline.PREV_G2];
                    b2 = frames[i + TwoColorTimeline.PREV_B2];
                  } else {
                    var frame = Animation.binarySearch(frames, time, TwoColorTimeline.ENTRIES);
                    r = frames[frame + TwoColorTimeline.PREV_R];
                    g = frames[frame + TwoColorTimeline.PREV_G];
                    b = frames[frame + TwoColorTimeline.PREV_B];
                    a = frames[frame + TwoColorTimeline.PREV_A];
                    r2 = frames[frame + TwoColorTimeline.PREV_R2];
                    g2 = frames[frame + TwoColorTimeline.PREV_G2];
                    b2 = frames[frame + TwoColorTimeline.PREV_B2];
                    var frameTime = frames[frame];
                    var percent = this.getCurvePercent(frame / TwoColorTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + TwoColorTimeline.PREV_TIME] - frameTime));
                    r += (frames[frame + TwoColorTimeline.R] - r) * percent;
                    g += (frames[frame + TwoColorTimeline.G] - g) * percent;
                    b += (frames[frame + TwoColorTimeline.B] - b) * percent;
                    a += (frames[frame + TwoColorTimeline.A] - a) * percent;
                    r2 += (frames[frame + TwoColorTimeline.R2] - r2) * percent;
                    g2 += (frames[frame + TwoColorTimeline.G2] - g2) * percent;
                    b2 += (frames[frame + TwoColorTimeline.B2] - b2) * percent;
                  }

                  if (alpha == 1) {
                    slot.color.set(r, g, b, a);
                    slot.darkColor.set(r2, g2, b2, 1);
                  } else {
                    var light = slot.color,
                        dark = slot.darkColor;

                    if (blend == MixBlend.setup) {
                      light.setFromColor(slot.data.color);
                      dark.setFromColor(slot.data.darkColor);
                    }

                    light.add((r - light.r) * alpha, (g - light.g) * alpha, (b - light.b) * alpha, (a - light.a) * alpha);
                    dark.add((r2 - dark.r) * alpha, (g2 - dark.g) * alpha, (b2 - dark.b) * alpha, 0);
                  }
                };

                TwoColorTimeline.ENTRIES = 8;
                TwoColorTimeline.PREV_TIME = -8;
                TwoColorTimeline.PREV_R = -7;
                TwoColorTimeline.PREV_G = -6;
                TwoColorTimeline.PREV_B = -5;
                TwoColorTimeline.PREV_A = -4;
                TwoColorTimeline.PREV_R2 = -3;
                TwoColorTimeline.PREV_G2 = -2;
                TwoColorTimeline.PREV_B2 = -1;
                TwoColorTimeline.R = 1;
                TwoColorTimeline.G = 2;
                TwoColorTimeline.B = 3;
                TwoColorTimeline.A = 4;
                TwoColorTimeline.R2 = 5;
                TwoColorTimeline.G2 = 6;
                TwoColorTimeline.B2 = 7;
                return TwoColorTimeline;
              }(CurveTimeline);

              spine.TwoColorTimeline = TwoColorTimeline;

              var AttachmentTimeline = function () {
                function AttachmentTimeline(frameCount) {
                  this.frames = spine.Utils.newFloatArray(frameCount);
                  this.attachmentNames = new Array(frameCount);
                }

                AttachmentTimeline.prototype.getPropertyId = function () {
                  return (TimelineType.attachment << 24) + this.slotIndex;
                };

                AttachmentTimeline.prototype.getFrameCount = function () {
                  return this.frames.length;
                };

                AttachmentTimeline.prototype.setFrame = function (frameIndex, time, attachmentName) {
                  this.frames[frameIndex] = time;
                  this.attachmentNames[frameIndex] = attachmentName;
                };

                AttachmentTimeline.prototype.apply = function (skeleton, lastTime, time, events, alpha, blend, direction) {
                  var slot = skeleton.slots[this.slotIndex];
                  if (!slot.bone.active) return;

                  if (direction == MixDirection.mixOut && blend == MixBlend.setup) {
                    var attachmentName_1 = slot.data.attachmentName;
                    slot.setAttachment(attachmentName_1 == null ? null : skeleton.getAttachment(this.slotIndex, attachmentName_1));
                    return;
                  }

                  var frames = this.frames;

                  if (time < frames[0]) {
                    if (blend == MixBlend.setup || blend == MixBlend.first) {
                      var attachmentName_2 = slot.data.attachmentName;
                      slot.setAttachment(attachmentName_2 == null ? null : skeleton.getAttachment(this.slotIndex, attachmentName_2));
                    }

                    return;
                  }

                  var frameIndex = 0;
                  if (time >= frames[frames.length - 1]) frameIndex = frames.length - 1;else frameIndex = Animation.binarySearch(frames, time, 1) - 1;
                  var attachmentName = this.attachmentNames[frameIndex];
                  skeleton.slots[this.slotIndex].setAttachment(attachmentName == null ? null : skeleton.getAttachment(this.slotIndex, attachmentName));
                };

                return AttachmentTimeline;
              }();

              spine.AttachmentTimeline = AttachmentTimeline;
              var zeros = null;

              var DeformTimeline = function (_super) {
                __extends(DeformTimeline, _super);

                function DeformTimeline(frameCount) {
                  var _this = _super.call(this, frameCount) || this;

                  _this.frames = spine.Utils.newFloatArray(frameCount);
                  _this.frameVertices = new Array(frameCount);
                  if (zeros == null) zeros = spine.Utils.newFloatArray(64);
                  return _this;
                }

                DeformTimeline.prototype.getPropertyId = function () {
                  return (TimelineType.deform << 27) + +this.attachment.id + this.slotIndex;
                };

                DeformTimeline.prototype.setFrame = function (frameIndex, time, vertices) {
                  this.frames[frameIndex] = time;
                  this.frameVertices[frameIndex] = vertices;
                };

                DeformTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, blend, direction) {
                  var slot = skeleton.slots[this.slotIndex];
                  if (!slot.bone.active) return;
                  var slotAttachment = slot.getAttachment();
                  if (!(slotAttachment instanceof spine.VertexAttachment) || !(slotAttachment.deformAttachment == this.attachment)) return;
                  var deformArray = slot.deform;
                  if (deformArray.length == 0) blend = MixBlend.setup;
                  var frameVertices = this.frameVertices;
                  var vertexCount = frameVertices[0].length;
                  var frames = this.frames;

                  if (time < frames[0]) {
                    var vertexAttachment = slotAttachment;

                    switch (blend) {
                      case MixBlend.setup:
                        deformArray.length = 0;
                        return;

                      case MixBlend.first:
                        if (alpha == 1) {
                          deformArray.length = 0;
                          break;
                        }

                        var deform_1 = spine.Utils.setArraySize(deformArray, vertexCount);

                        if (vertexAttachment.bones == null) {
                          var setupVertices = vertexAttachment.vertices;

                          for (var i = 0; i < vertexCount; i++) {
                            deform_1[i] += (setupVertices[i] - deform_1[i]) * alpha;
                          }
                        } else {
                          alpha = 1 - alpha;

                          for (var i = 0; i < vertexCount; i++) {
                            deform_1[i] *= alpha;
                          }
                        }

                    }

                    return;
                  }

                  var deform = spine.Utils.setArraySize(deformArray, vertexCount);

                  if (time >= frames[frames.length - 1]) {
                    var lastVertices = frameVertices[frames.length - 1];

                    if (alpha == 1) {
                      if (blend == MixBlend.add) {
                        var vertexAttachment = slotAttachment;

                        if (vertexAttachment.bones == null) {
                          var setupVertices = vertexAttachment.vertices;

                          for (var i_1 = 0; i_1 < vertexCount; i_1++) {
                            deform[i_1] += lastVertices[i_1] - setupVertices[i_1];
                          }
                        } else {
                          for (var i_2 = 0; i_2 < vertexCount; i_2++) {
                            deform[i_2] += lastVertices[i_2];
                          }
                        }
                      } else {
                        spine.Utils.arrayCopy(lastVertices, 0, deform, 0, vertexCount);
                      }
                    } else {
                      switch (blend) {
                        case MixBlend.setup:
                          {
                            var vertexAttachment_1 = slotAttachment;

                            if (vertexAttachment_1.bones == null) {
                              var setupVertices = vertexAttachment_1.vertices;

                              for (var i_3 = 0; i_3 < vertexCount; i_3++) {
                                var setup = setupVertices[i_3];
                                deform[i_3] = setup + (lastVertices[i_3] - setup) * alpha;
                              }
                            } else {
                              for (var i_4 = 0; i_4 < vertexCount; i_4++) {
                                deform[i_4] = lastVertices[i_4] * alpha;
                              }
                            }

                            break;
                          }

                        case MixBlend.first:
                        case MixBlend.replace:
                          for (var i_5 = 0; i_5 < vertexCount; i_5++) {
                            deform[i_5] += (lastVertices[i_5] - deform[i_5]) * alpha;
                          }

                        case MixBlend.add:
                          var vertexAttachment = slotAttachment;

                          if (vertexAttachment.bones == null) {
                            var setupVertices = vertexAttachment.vertices;

                            for (var i_6 = 0; i_6 < vertexCount; i_6++) {
                              deform[i_6] += (lastVertices[i_6] - setupVertices[i_6]) * alpha;
                            }
                          } else {
                            for (var i_7 = 0; i_7 < vertexCount; i_7++) {
                              deform[i_7] += lastVertices[i_7] * alpha;
                            }
                          }

                      }
                    }

                    return;
                  }

                  var frame = Animation.binarySearch(frames, time);
                  var prevVertices = frameVertices[frame - 1];
                  var nextVertices = frameVertices[frame];
                  var frameTime = frames[frame];
                  var percent = this.getCurvePercent(frame - 1, 1 - (time - frameTime) / (frames[frame - 1] - frameTime));

                  if (alpha == 1) {
                    if (blend == MixBlend.add) {
                      var vertexAttachment = slotAttachment;

                      if (vertexAttachment.bones == null) {
                        var setupVertices = vertexAttachment.vertices;

                        for (var i_8 = 0; i_8 < vertexCount; i_8++) {
                          var prev = prevVertices[i_8];
                          deform[i_8] += prev + (nextVertices[i_8] - prev) * percent - setupVertices[i_8];
                        }
                      } else {
                        for (var i_9 = 0; i_9 < vertexCount; i_9++) {
                          var prev = prevVertices[i_9];
                          deform[i_9] += prev + (nextVertices[i_9] - prev) * percent;
                        }
                      }
                    } else {
                      for (var i_10 = 0; i_10 < vertexCount; i_10++) {
                        var prev = prevVertices[i_10];
                        deform[i_10] = prev + (nextVertices[i_10] - prev) * percent;
                      }
                    }
                  } else {
                    switch (blend) {
                      case MixBlend.setup:
                        {
                          var vertexAttachment_2 = slotAttachment;

                          if (vertexAttachment_2.bones == null) {
                            var setupVertices = vertexAttachment_2.vertices;

                            for (var i_11 = 0; i_11 < vertexCount; i_11++) {
                              var prev = prevVertices[i_11],
                                  setup = setupVertices[i_11];
                              deform[i_11] = setup + (prev + (nextVertices[i_11] - prev) * percent - setup) * alpha;
                            }
                          } else {
                            for (var i_12 = 0; i_12 < vertexCount; i_12++) {
                              var prev = prevVertices[i_12];
                              deform[i_12] = (prev + (nextVertices[i_12] - prev) * percent) * alpha;
                            }
                          }

                          break;
                        }

                      case MixBlend.first:
                      case MixBlend.replace:
                        for (var i_13 = 0; i_13 < vertexCount; i_13++) {
                          var prev = prevVertices[i_13];
                          deform[i_13] += (prev + (nextVertices[i_13] - prev) * percent - deform[i_13]) * alpha;
                        }

                        break;

                      case MixBlend.add:
                        var vertexAttachment = slotAttachment;

                        if (vertexAttachment.bones == null) {
                          var setupVertices = vertexAttachment.vertices;

                          for (var i_14 = 0; i_14 < vertexCount; i_14++) {
                            var prev = prevVertices[i_14];
                            deform[i_14] += (prev + (nextVertices[i_14] - prev) * percent - setupVertices[i_14]) * alpha;
                          }
                        } else {
                          for (var i_15 = 0; i_15 < vertexCount; i_15++) {
                            var prev = prevVertices[i_15];
                            deform[i_15] += (prev + (nextVertices[i_15] - prev) * percent) * alpha;
                          }
                        }

                    }
                  }
                };

                return DeformTimeline;
              }(CurveTimeline);

              spine.DeformTimeline = DeformTimeline;

              var EventTimeline = function () {
                function EventTimeline(frameCount) {
                  this.frames = spine.Utils.newFloatArray(frameCount);
                  this.events = new Array(frameCount);
                }

                EventTimeline.prototype.getPropertyId = function () {
                  return TimelineType.event << 24;
                };

                EventTimeline.prototype.getFrameCount = function () {
                  return this.frames.length;
                };

                EventTimeline.prototype.setFrame = function (frameIndex, event) {
                  this.frames[frameIndex] = event.time;
                  this.events[frameIndex] = event;
                };

                EventTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, blend, direction) {
                  if (firedEvents == null) return;
                  var frames = this.frames;
                  var frameCount = this.frames.length;

                  if (lastTime > time) {
                    this.apply(skeleton, lastTime, Number.MAX_VALUE, firedEvents, alpha, blend, direction);
                    lastTime = -1;
                  } else if (lastTime >= frames[frameCount - 1]) return;

                  if (time < frames[0]) return;
                  var frame = 0;
                  if (lastTime < frames[0]) frame = 0;else {
                    frame = Animation.binarySearch(frames, lastTime);
                    var frameTime = frames[frame];

                    while (frame > 0) {
                      if (frames[frame - 1] != frameTime) break;
                      frame--;
                    }
                  }

                  for (; frame < frameCount && time >= frames[frame]; frame++) {
                    firedEvents.push(this.events[frame]);
                  }
                };

                return EventTimeline;
              }();

              spine.EventTimeline = EventTimeline;

              var DrawOrderTimeline = function () {
                function DrawOrderTimeline(frameCount) {
                  this.frames = spine.Utils.newFloatArray(frameCount);
                  this.drawOrders = new Array(frameCount);
                }

                DrawOrderTimeline.prototype.getPropertyId = function () {
                  return TimelineType.drawOrder << 24;
                };

                DrawOrderTimeline.prototype.getFrameCount = function () {
                  return this.frames.length;
                };

                DrawOrderTimeline.prototype.setFrame = function (frameIndex, time, drawOrder) {
                  this.frames[frameIndex] = time;
                  this.drawOrders[frameIndex] = drawOrder;
                };

                DrawOrderTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, blend, direction) {
                  var drawOrder = skeleton.drawOrder;
                  var slots = skeleton.slots;

                  if (direction == MixDirection.mixOut && blend == MixBlend.setup) {
                    spine.Utils.arrayCopy(skeleton.slots, 0, skeleton.drawOrder, 0, skeleton.slots.length);
                    return;
                  }

                  var frames = this.frames;

                  if (time < frames[0]) {
                    if (blend == MixBlend.setup || blend == MixBlend.first) spine.Utils.arrayCopy(skeleton.slots, 0, skeleton.drawOrder, 0, skeleton.slots.length);
                    return;
                  }

                  var frame = 0;
                  if (time >= frames[frames.length - 1]) frame = frames.length - 1;else frame = Animation.binarySearch(frames, time) - 1;
                  var drawOrderToSetupIndex = this.drawOrders[frame];
                  if (drawOrderToSetupIndex == null) spine.Utils.arrayCopy(slots, 0, drawOrder, 0, slots.length);else {
                    for (var i = 0, n = drawOrderToSetupIndex.length; i < n; i++) {
                      drawOrder[i] = slots[drawOrderToSetupIndex[i]];
                    }
                  }
                };

                return DrawOrderTimeline;
              }();

              spine.DrawOrderTimeline = DrawOrderTimeline;

              var IkConstraintTimeline = function (_super) {
                __extends(IkConstraintTimeline, _super);

                function IkConstraintTimeline(frameCount) {
                  var _this = _super.call(this, frameCount) || this;

                  _this.frames = spine.Utils.newFloatArray(frameCount * IkConstraintTimeline.ENTRIES);
                  return _this;
                }

                IkConstraintTimeline.prototype.getPropertyId = function () {
                  return (TimelineType.ikConstraint << 24) + this.ikConstraintIndex;
                };

                IkConstraintTimeline.prototype.setFrame = function (frameIndex, time, mix, softness, bendDirection, compress, stretch) {
                  frameIndex *= IkConstraintTimeline.ENTRIES;
                  this.frames[frameIndex] = time;
                  this.frames[frameIndex + IkConstraintTimeline.MIX] = mix;
                  this.frames[frameIndex + IkConstraintTimeline.SOFTNESS] = softness;
                  this.frames[frameIndex + IkConstraintTimeline.BEND_DIRECTION] = bendDirection;
                  this.frames[frameIndex + IkConstraintTimeline.COMPRESS] = compress ? 1 : 0;
                  this.frames[frameIndex + IkConstraintTimeline.STRETCH] = stretch ? 1 : 0;
                };

                IkConstraintTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, blend, direction) {
                  var frames = this.frames;
                  var constraint = skeleton.ikConstraints[this.ikConstraintIndex];
                  if (!constraint.active) return;

                  if (time < frames[0]) {
                    switch (blend) {
                      case MixBlend.setup:
                        constraint.mix = constraint.data.mix;
                        constraint.softness = constraint.data.softness;
                        constraint.bendDirection = constraint.data.bendDirection;
                        constraint.compress = constraint.data.compress;
                        constraint.stretch = constraint.data.stretch;
                        return;

                      case MixBlend.first:
                        constraint.mix += (constraint.data.mix - constraint.mix) * alpha;
                        constraint.softness += (constraint.data.softness - constraint.softness) * alpha;
                        constraint.bendDirection = constraint.data.bendDirection;
                        constraint.compress = constraint.data.compress;
                        constraint.stretch = constraint.data.stretch;
                    }

                    return;
                  }

                  if (time >= frames[frames.length - IkConstraintTimeline.ENTRIES]) {
                    if (blend == MixBlend.setup) {
                      constraint.mix = constraint.data.mix + (frames[frames.length + IkConstraintTimeline.PREV_MIX] - constraint.data.mix) * alpha;
                      constraint.softness = constraint.data.softness + (frames[frames.length + IkConstraintTimeline.PREV_SOFTNESS] - constraint.data.softness) * alpha;

                      if (direction == MixDirection.mixOut) {
                        constraint.bendDirection = constraint.data.bendDirection;
                        constraint.compress = constraint.data.compress;
                        constraint.stretch = constraint.data.stretch;
                      } else {
                        constraint.bendDirection = frames[frames.length + IkConstraintTimeline.PREV_BEND_DIRECTION];
                        constraint.compress = frames[frames.length + IkConstraintTimeline.PREV_COMPRESS] != 0;
                        constraint.stretch = frames[frames.length + IkConstraintTimeline.PREV_STRETCH] != 0;
                      }
                    } else {
                      constraint.mix += (frames[frames.length + IkConstraintTimeline.PREV_MIX] - constraint.mix) * alpha;
                      constraint.softness += (frames[frames.length + IkConstraintTimeline.PREV_SOFTNESS] - constraint.softness) * alpha;

                      if (direction == MixDirection.mixIn) {
                        constraint.bendDirection = frames[frames.length + IkConstraintTimeline.PREV_BEND_DIRECTION];
                        constraint.compress = frames[frames.length + IkConstraintTimeline.PREV_COMPRESS] != 0;
                        constraint.stretch = frames[frames.length + IkConstraintTimeline.PREV_STRETCH] != 0;
                      }
                    }

                    return;
                  }

                  var frame = Animation.binarySearch(frames, time, IkConstraintTimeline.ENTRIES);
                  var mix = frames[frame + IkConstraintTimeline.PREV_MIX];
                  var softness = frames[frame + IkConstraintTimeline.PREV_SOFTNESS];
                  var frameTime = frames[frame];
                  var percent = this.getCurvePercent(frame / IkConstraintTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + IkConstraintTimeline.PREV_TIME] - frameTime));

                  if (blend == MixBlend.setup) {
                    constraint.mix = constraint.data.mix + (mix + (frames[frame + IkConstraintTimeline.MIX] - mix) * percent - constraint.data.mix) * alpha;
                    constraint.softness = constraint.data.softness + (softness + (frames[frame + IkConstraintTimeline.SOFTNESS] - softness) * percent - constraint.data.softness) * alpha;

                    if (direction == MixDirection.mixOut) {
                      constraint.bendDirection = constraint.data.bendDirection;
                      constraint.compress = constraint.data.compress;
                      constraint.stretch = constraint.data.stretch;
                    } else {
                      constraint.bendDirection = frames[frame + IkConstraintTimeline.PREV_BEND_DIRECTION];
                      constraint.compress = frames[frame + IkConstraintTimeline.PREV_COMPRESS] != 0;
                      constraint.stretch = frames[frame + IkConstraintTimeline.PREV_STRETCH] != 0;
                    }
                  } else {
                    constraint.mix += (mix + (frames[frame + IkConstraintTimeline.MIX] - mix) * percent - constraint.mix) * alpha;
                    constraint.softness += (softness + (frames[frame + IkConstraintTimeline.SOFTNESS] - softness) * percent - constraint.softness) * alpha;

                    if (direction == MixDirection.mixIn) {
                      constraint.bendDirection = frames[frame + IkConstraintTimeline.PREV_BEND_DIRECTION];
                      constraint.compress = frames[frame + IkConstraintTimeline.PREV_COMPRESS] != 0;
                      constraint.stretch = frames[frame + IkConstraintTimeline.PREV_STRETCH] != 0;
                    }
                  }
                };

                IkConstraintTimeline.ENTRIES = 6;
                IkConstraintTimeline.PREV_TIME = -6;
                IkConstraintTimeline.PREV_MIX = -5;
                IkConstraintTimeline.PREV_SOFTNESS = -4;
                IkConstraintTimeline.PREV_BEND_DIRECTION = -3;
                IkConstraintTimeline.PREV_COMPRESS = -2;
                IkConstraintTimeline.PREV_STRETCH = -1;
                IkConstraintTimeline.MIX = 1;
                IkConstraintTimeline.SOFTNESS = 2;
                IkConstraintTimeline.BEND_DIRECTION = 3;
                IkConstraintTimeline.COMPRESS = 4;
                IkConstraintTimeline.STRETCH = 5;
                return IkConstraintTimeline;
              }(CurveTimeline);

              spine.IkConstraintTimeline = IkConstraintTimeline;

              var TransformConstraintTimeline = function (_super) {
                __extends(TransformConstraintTimeline, _super);

                function TransformConstraintTimeline(frameCount) {
                  var _this = _super.call(this, frameCount) || this;

                  _this.frames = spine.Utils.newFloatArray(frameCount * TransformConstraintTimeline.ENTRIES);
                  return _this;
                }

                TransformConstraintTimeline.prototype.getPropertyId = function () {
                  return (TimelineType.transformConstraint << 24) + this.transformConstraintIndex;
                };

                TransformConstraintTimeline.prototype.setFrame = function (frameIndex, time, rotateMix, translateMix, scaleMix, shearMix) {
                  frameIndex *= TransformConstraintTimeline.ENTRIES;
                  this.frames[frameIndex] = time;
                  this.frames[frameIndex + TransformConstraintTimeline.ROTATE] = rotateMix;
                  this.frames[frameIndex + TransformConstraintTimeline.TRANSLATE] = translateMix;
                  this.frames[frameIndex + TransformConstraintTimeline.SCALE] = scaleMix;
                  this.frames[frameIndex + TransformConstraintTimeline.SHEAR] = shearMix;
                };

                TransformConstraintTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, blend, direction) {
                  var frames = this.frames;
                  var constraint = skeleton.transformConstraints[this.transformConstraintIndex];
                  if (!constraint.active) return;

                  if (time < frames[0]) {
                    var data = constraint.data;

                    switch (blend) {
                      case MixBlend.setup:
                        constraint.rotateMix = data.rotateMix;
                        constraint.translateMix = data.translateMix;
                        constraint.scaleMix = data.scaleMix;
                        constraint.shearMix = data.shearMix;
                        return;

                      case MixBlend.first:
                        constraint.rotateMix += (data.rotateMix - constraint.rotateMix) * alpha;
                        constraint.translateMix += (data.translateMix - constraint.translateMix) * alpha;
                        constraint.scaleMix += (data.scaleMix - constraint.scaleMix) * alpha;
                        constraint.shearMix += (data.shearMix - constraint.shearMix) * alpha;
                    }

                    return;
                  }

                  var rotate = 0,
                      translate = 0,
                      scale = 0,
                      shear = 0;

                  if (time >= frames[frames.length - TransformConstraintTimeline.ENTRIES]) {
                    var i = frames.length;
                    rotate = frames[i + TransformConstraintTimeline.PREV_ROTATE];
                    translate = frames[i + TransformConstraintTimeline.PREV_TRANSLATE];
                    scale = frames[i + TransformConstraintTimeline.PREV_SCALE];
                    shear = frames[i + TransformConstraintTimeline.PREV_SHEAR];
                  } else {
                    var frame = Animation.binarySearch(frames, time, TransformConstraintTimeline.ENTRIES);
                    rotate = frames[frame + TransformConstraintTimeline.PREV_ROTATE];
                    translate = frames[frame + TransformConstraintTimeline.PREV_TRANSLATE];
                    scale = frames[frame + TransformConstraintTimeline.PREV_SCALE];
                    shear = frames[frame + TransformConstraintTimeline.PREV_SHEAR];
                    var frameTime = frames[frame];
                    var percent = this.getCurvePercent(frame / TransformConstraintTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + TransformConstraintTimeline.PREV_TIME] - frameTime));
                    rotate += (frames[frame + TransformConstraintTimeline.ROTATE] - rotate) * percent;
                    translate += (frames[frame + TransformConstraintTimeline.TRANSLATE] - translate) * percent;
                    scale += (frames[frame + TransformConstraintTimeline.SCALE] - scale) * percent;
                    shear += (frames[frame + TransformConstraintTimeline.SHEAR] - shear) * percent;
                  }

                  if (blend == MixBlend.setup) {
                    var data = constraint.data;
                    constraint.rotateMix = data.rotateMix + (rotate - data.rotateMix) * alpha;
                    constraint.translateMix = data.translateMix + (translate - data.translateMix) * alpha;
                    constraint.scaleMix = data.scaleMix + (scale - data.scaleMix) * alpha;
                    constraint.shearMix = data.shearMix + (shear - data.shearMix) * alpha;
                  } else {
                    constraint.rotateMix += (rotate - constraint.rotateMix) * alpha;
                    constraint.translateMix += (translate - constraint.translateMix) * alpha;
                    constraint.scaleMix += (scale - constraint.scaleMix) * alpha;
                    constraint.shearMix += (shear - constraint.shearMix) * alpha;
                  }
                };

                TransformConstraintTimeline.ENTRIES = 5;
                TransformConstraintTimeline.PREV_TIME = -5;
                TransformConstraintTimeline.PREV_ROTATE = -4;
                TransformConstraintTimeline.PREV_TRANSLATE = -3;
                TransformConstraintTimeline.PREV_SCALE = -2;
                TransformConstraintTimeline.PREV_SHEAR = -1;
                TransformConstraintTimeline.ROTATE = 1;
                TransformConstraintTimeline.TRANSLATE = 2;
                TransformConstraintTimeline.SCALE = 3;
                TransformConstraintTimeline.SHEAR = 4;
                return TransformConstraintTimeline;
              }(CurveTimeline);

              spine.TransformConstraintTimeline = TransformConstraintTimeline;

              var PathConstraintPositionTimeline = function (_super) {
                __extends(PathConstraintPositionTimeline, _super);

                function PathConstraintPositionTimeline(frameCount) {
                  var _this = _super.call(this, frameCount) || this;

                  _this.frames = spine.Utils.newFloatArray(frameCount * PathConstraintPositionTimeline.ENTRIES);
                  return _this;
                }

                PathConstraintPositionTimeline.prototype.getPropertyId = function () {
                  return (TimelineType.pathConstraintPosition << 24) + this.pathConstraintIndex;
                };

                PathConstraintPositionTimeline.prototype.setFrame = function (frameIndex, time, value) {
                  frameIndex *= PathConstraintPositionTimeline.ENTRIES;
                  this.frames[frameIndex] = time;
                  this.frames[frameIndex + PathConstraintPositionTimeline.VALUE] = value;
                };

                PathConstraintPositionTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, blend, direction) {
                  var frames = this.frames;
                  var constraint = skeleton.pathConstraints[this.pathConstraintIndex];
                  if (!constraint.active) return;

                  if (time < frames[0]) {
                    switch (blend) {
                      case MixBlend.setup:
                        constraint.position = constraint.data.position;
                        return;

                      case MixBlend.first:
                        constraint.position += (constraint.data.position - constraint.position) * alpha;
                    }

                    return;
                  }

                  var position = 0;
                  if (time >= frames[frames.length - PathConstraintPositionTimeline.ENTRIES]) position = frames[frames.length + PathConstraintPositionTimeline.PREV_VALUE];else {
                    var frame = Animation.binarySearch(frames, time, PathConstraintPositionTimeline.ENTRIES);
                    position = frames[frame + PathConstraintPositionTimeline.PREV_VALUE];
                    var frameTime = frames[frame];
                    var percent = this.getCurvePercent(frame / PathConstraintPositionTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + PathConstraintPositionTimeline.PREV_TIME] - frameTime));
                    position += (frames[frame + PathConstraintPositionTimeline.VALUE] - position) * percent;
                  }
                  if (blend == MixBlend.setup) constraint.position = constraint.data.position + (position - constraint.data.position) * alpha;else constraint.position += (position - constraint.position) * alpha;
                };

                PathConstraintPositionTimeline.ENTRIES = 2;
                PathConstraintPositionTimeline.PREV_TIME = -2;
                PathConstraintPositionTimeline.PREV_VALUE = -1;
                PathConstraintPositionTimeline.VALUE = 1;
                return PathConstraintPositionTimeline;
              }(CurveTimeline);

              spine.PathConstraintPositionTimeline = PathConstraintPositionTimeline;

              var PathConstraintSpacingTimeline = function (_super) {
                __extends(PathConstraintSpacingTimeline, _super);

                function PathConstraintSpacingTimeline(frameCount) {
                  return _super.call(this, frameCount) || this;
                }

                PathConstraintSpacingTimeline.prototype.getPropertyId = function () {
                  return (TimelineType.pathConstraintSpacing << 24) + this.pathConstraintIndex;
                };

                PathConstraintSpacingTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, blend, direction) {
                  var frames = this.frames;
                  var constraint = skeleton.pathConstraints[this.pathConstraintIndex];
                  if (!constraint.active) return;

                  if (time < frames[0]) {
                    switch (blend) {
                      case MixBlend.setup:
                        constraint.spacing = constraint.data.spacing;
                        return;

                      case MixBlend.first:
                        constraint.spacing += (constraint.data.spacing - constraint.spacing) * alpha;
                    }

                    return;
                  }

                  var spacing = 0;
                  if (time >= frames[frames.length - PathConstraintSpacingTimeline.ENTRIES]) spacing = frames[frames.length + PathConstraintSpacingTimeline.PREV_VALUE];else {
                    var frame = Animation.binarySearch(frames, time, PathConstraintSpacingTimeline.ENTRIES);
                    spacing = frames[frame + PathConstraintSpacingTimeline.PREV_VALUE];
                    var frameTime = frames[frame];
                    var percent = this.getCurvePercent(frame / PathConstraintSpacingTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + PathConstraintSpacingTimeline.PREV_TIME] - frameTime));
                    spacing += (frames[frame + PathConstraintSpacingTimeline.VALUE] - spacing) * percent;
                  }
                  if (blend == MixBlend.setup) constraint.spacing = constraint.data.spacing + (spacing - constraint.data.spacing) * alpha;else constraint.spacing += (spacing - constraint.spacing) * alpha;
                };

                return PathConstraintSpacingTimeline;
              }(PathConstraintPositionTimeline);

              spine.PathConstraintSpacingTimeline = PathConstraintSpacingTimeline;

              var PathConstraintMixTimeline = function (_super) {
                __extends(PathConstraintMixTimeline, _super);

                function PathConstraintMixTimeline(frameCount) {
                  var _this = _super.call(this, frameCount) || this;

                  _this.frames = spine.Utils.newFloatArray(frameCount * PathConstraintMixTimeline.ENTRIES);
                  return _this;
                }

                PathConstraintMixTimeline.prototype.getPropertyId = function () {
                  return (TimelineType.pathConstraintMix << 24) + this.pathConstraintIndex;
                };

                PathConstraintMixTimeline.prototype.setFrame = function (frameIndex, time, rotateMix, translateMix) {
                  frameIndex *= PathConstraintMixTimeline.ENTRIES;
                  this.frames[frameIndex] = time;
                  this.frames[frameIndex + PathConstraintMixTimeline.ROTATE] = rotateMix;
                  this.frames[frameIndex + PathConstraintMixTimeline.TRANSLATE] = translateMix;
                };

                PathConstraintMixTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, blend, direction) {
                  var frames = this.frames;
                  var constraint = skeleton.pathConstraints[this.pathConstraintIndex];
                  if (!constraint.active) return;

                  if (time < frames[0]) {
                    switch (blend) {
                      case MixBlend.setup:
                        constraint.rotateMix = constraint.data.rotateMix;
                        constraint.translateMix = constraint.data.translateMix;
                        return;

                      case MixBlend.first:
                        constraint.rotateMix += (constraint.data.rotateMix - constraint.rotateMix) * alpha;
                        constraint.translateMix += (constraint.data.translateMix - constraint.translateMix) * alpha;
                    }

                    return;
                  }

                  var rotate = 0,
                      translate = 0;

                  if (time >= frames[frames.length - PathConstraintMixTimeline.ENTRIES]) {
                    rotate = frames[frames.length + PathConstraintMixTimeline.PREV_ROTATE];
                    translate = frames[frames.length + PathConstraintMixTimeline.PREV_TRANSLATE];
                  } else {
                    var frame = Animation.binarySearch(frames, time, PathConstraintMixTimeline.ENTRIES);
                    rotate = frames[frame + PathConstraintMixTimeline.PREV_ROTATE];
                    translate = frames[frame + PathConstraintMixTimeline.PREV_TRANSLATE];
                    var frameTime = frames[frame];
                    var percent = this.getCurvePercent(frame / PathConstraintMixTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + PathConstraintMixTimeline.PREV_TIME] - frameTime));
                    rotate += (frames[frame + PathConstraintMixTimeline.ROTATE] - rotate) * percent;
                    translate += (frames[frame + PathConstraintMixTimeline.TRANSLATE] - translate) * percent;
                  }

                  if (blend == MixBlend.setup) {
                    constraint.rotateMix = constraint.data.rotateMix + (rotate - constraint.data.rotateMix) * alpha;
                    constraint.translateMix = constraint.data.translateMix + (translate - constraint.data.translateMix) * alpha;
                  } else {
                    constraint.rotateMix += (rotate - constraint.rotateMix) * alpha;
                    constraint.translateMix += (translate - constraint.translateMix) * alpha;
                  }
                };

                PathConstraintMixTimeline.ENTRIES = 3;
                PathConstraintMixTimeline.PREV_TIME = -3;
                PathConstraintMixTimeline.PREV_ROTATE = -2;
                PathConstraintMixTimeline.PREV_TRANSLATE = -1;
                PathConstraintMixTimeline.ROTATE = 1;
                PathConstraintMixTimeline.TRANSLATE = 2;
                return PathConstraintMixTimeline;
              }(CurveTimeline);

              spine.PathConstraintMixTimeline = PathConstraintMixTimeline;
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var AnimationState = function () {
                function AnimationState(data) {
                  this.tracks = new Array();
                  this.timeScale = 1;
                  this.events = new Array();
                  this.listeners = new Array();
                  this.queue = new EventQueue(this);
                  this.propertyIDs = new spine.IntSet();
                  this.animationsChanged = false;
                  this.trackEntryPool = new spine.Pool(function () {
                    return new TrackEntry();
                  });
                  this.data = data;
                }

                AnimationState.prototype.update = function (delta) {
                  delta *= this.timeScale;
                  var tracks = this.tracks;

                  for (var i = 0, n = tracks.length; i < n; i++) {
                    var current = tracks[i];
                    if (current == null) continue;
                    current.animationLast = current.nextAnimationLast;
                    current.trackLast = current.nextTrackLast;
                    var currentDelta = delta * current.timeScale;

                    if (current.delay > 0) {
                      current.delay -= currentDelta;
                      if (current.delay > 0) continue;
                      currentDelta = -current.delay;
                      current.delay = 0;
                    }

                    var next = current.next;

                    if (next != null) {
                      var nextTime = current.trackLast - next.delay;

                      if (nextTime >= 0) {
                        next.delay = 0;
                        next.trackTime += current.timeScale == 0 ? 0 : (nextTime / current.timeScale + delta) * next.timeScale;
                        current.trackTime += currentDelta;
                        this.setCurrent(i, next, true);

                        while (next.mixingFrom != null) {
                          next.mixTime += delta;
                          next = next.mixingFrom;
                        }

                        continue;
                      }
                    } else if (current.trackLast >= current.trackEnd && current.mixingFrom == null) {
                      tracks[i] = null;
                      this.queue.end(current);
                      this.disposeNext(current);
                      continue;
                    }

                    if (current.mixingFrom != null && this.updateMixingFrom(current, delta)) {
                      var from = current.mixingFrom;
                      current.mixingFrom = null;
                      if (from != null) from.mixingTo = null;

                      while (from != null) {
                        this.queue.end(from);
                        from = from.mixingFrom;
                      }
                    }

                    current.trackTime += currentDelta;
                  }

                  this.queue.drain();
                };

                AnimationState.prototype.updateMixingFrom = function (to, delta) {
                  var from = to.mixingFrom;
                  if (from == null) return true;
                  var finished = this.updateMixingFrom(from, delta);
                  from.animationLast = from.nextAnimationLast;
                  from.trackLast = from.nextTrackLast;

                  if (to.mixTime > 0 && to.mixTime >= to.mixDuration) {
                    if (from.totalAlpha == 0 || to.mixDuration == 0) {
                      to.mixingFrom = from.mixingFrom;
                      if (from.mixingFrom != null) from.mixingFrom.mixingTo = to;
                      to.interruptAlpha = from.interruptAlpha;
                      this.queue.end(from);
                    }

                    return finished;
                  }

                  from.trackTime += delta * from.timeScale;
                  to.mixTime += delta;
                  return false;
                };

                AnimationState.prototype.apply = function (skeleton) {
                  if (skeleton == null) throw new Error("skeleton cannot be null.");
                  if (this.animationsChanged) this._animationsChanged();
                  var events = this.events;
                  var tracks = this.tracks;
                  var applied = false;

                  for (var i = 0, n = tracks.length; i < n; i++) {
                    var current = tracks[i];
                    if (current == null || current.delay > 0) continue;
                    applied = true;
                    var blend = i == 0 ? spine.MixBlend.first : current.mixBlend;
                    var mix = current.alpha;
                    if (current.mixingFrom != null) mix *= this.applyMixingFrom(current, skeleton, blend);else if (current.trackTime >= current.trackEnd && current.next == null) mix = 0;
                    var animationLast = current.animationLast,
                        animationTime = current.getAnimationTime();
                    var timelineCount = current.animation.timelines.length;
                    var timelines = current.animation.timelines;

                    if (i == 0 && mix == 1 || blend == spine.MixBlend.add) {
                      for (var ii = 0; ii < timelineCount; ii++) {
                        spine.Utils.webkit602BugfixHelper(mix, blend);
                        timelines[ii].apply(skeleton, animationLast, animationTime, events, mix, blend, spine.MixDirection.mixIn);
                      }
                    } else {
                      var timelineMode = current.timelineMode;
                      var firstFrame = current.timelinesRotation.length == 0;
                      if (firstFrame) spine.Utils.setArraySize(current.timelinesRotation, timelineCount << 1, null);
                      var timelinesRotation = current.timelinesRotation;

                      for (var ii = 0; ii < timelineCount; ii++) {
                        var timeline = timelines[ii];
                        var timelineBlend = (timelineMode[ii] & AnimationState.NOT_LAST - 1) == AnimationState.SUBSEQUENT ? blend : spine.MixBlend.setup;

                        if (timeline instanceof spine.RotateTimeline) {
                          this.applyRotateTimeline(timeline, skeleton, animationTime, mix, timelineBlend, timelinesRotation, ii << 1, firstFrame);
                        } else {
                          spine.Utils.webkit602BugfixHelper(mix, blend);
                          timeline.apply(skeleton, animationLast, animationTime, events, mix, timelineBlend, spine.MixDirection.mixIn);
                        }
                      }
                    }

                    this.queueEvents(current, animationTime);
                    events.length = 0;
                    current.nextAnimationLast = animationTime;
                    current.nextTrackLast = current.trackTime;
                  }

                  this.queue.drain();
                  return applied;
                };

                AnimationState.prototype.applyMixingFrom = function (to, skeleton, blend) {
                  var from = to.mixingFrom;
                  if (from.mixingFrom != null) this.applyMixingFrom(from, skeleton, blend);
                  var mix = 0;

                  if (to.mixDuration == 0) {
                    mix = 1;
                    if (blend == spine.MixBlend.first) blend = spine.MixBlend.setup;
                  } else {
                    mix = to.mixTime / to.mixDuration;
                    if (mix > 1) mix = 1;
                    if (blend != spine.MixBlend.first) blend = from.mixBlend;
                  }

                  var events = mix < from.eventThreshold ? this.events : null;
                  var attachments = mix < from.attachmentThreshold,
                      drawOrder = mix < from.drawOrderThreshold;
                  var animationLast = from.animationLast,
                      animationTime = from.getAnimationTime();
                  var timelineCount = from.animation.timelines.length;
                  var timelines = from.animation.timelines;
                  var alphaHold = from.alpha * to.interruptAlpha,
                      alphaMix = alphaHold * (1 - mix);

                  if (blend == spine.MixBlend.add) {
                    for (var i = 0; i < timelineCount; i++) {
                      timelines[i].apply(skeleton, animationLast, animationTime, events, alphaMix, blend, spine.MixDirection.mixOut);
                    }
                  } else {
                    var timelineMode = from.timelineMode;
                    var timelineHoldMix = from.timelineHoldMix;
                    var firstFrame = from.timelinesRotation.length == 0;
                    if (firstFrame) spine.Utils.setArraySize(from.timelinesRotation, timelineCount << 1, null);
                    var timelinesRotation = from.timelinesRotation;
                    from.totalAlpha = 0;

                    for (var i = 0; i < timelineCount; i++) {
                      var timeline = timelines[i];
                      var direction = spine.MixDirection.mixOut;
                      var timelineBlend = void 0;
                      var alpha = 0;

                      switch (timelineMode[i] & AnimationState.NOT_LAST - 1) {
                        case AnimationState.SUBSEQUENT:
                          timelineBlend = blend;

                          if (!attachments && timeline instanceof spine.AttachmentTimeline) {
                            if ((timelineMode[i] & AnimationState.NOT_LAST) == AnimationState.NOT_LAST) continue;
                            timelineBlend = spine.MixBlend.setup;
                          }

                          if (!drawOrder && timeline instanceof spine.DrawOrderTimeline) continue;
                          alpha = alphaMix;
                          break;

                        case AnimationState.FIRST:
                          timelineBlend = spine.MixBlend.setup;
                          alpha = alphaMix;
                          break;

                        case AnimationState.HOLD:
                          timelineBlend = spine.MixBlend.setup;
                          alpha = alphaHold;
                          break;

                        default:
                          timelineBlend = spine.MixBlend.setup;
                          var holdMix = timelineHoldMix[i];
                          alpha = alphaHold * Math.max(0, 1 - holdMix.mixTime / holdMix.mixDuration);
                          break;
                      }

                      from.totalAlpha += alpha;
                      if (timeline instanceof spine.RotateTimeline) this.applyRotateTimeline(timeline, skeleton, animationTime, alpha, timelineBlend, timelinesRotation, i << 1, firstFrame);else {
                        spine.Utils.webkit602BugfixHelper(alpha, blend);

                        if (timelineBlend == spine.MixBlend.setup) {
                          if (timeline instanceof spine.AttachmentTimeline) {
                            if (attachments || (timelineMode[i] & AnimationState.NOT_LAST) == AnimationState.NOT_LAST) direction = spine.MixDirection.mixIn;
                          } else if (timeline instanceof spine.DrawOrderTimeline) {
                            if (drawOrder) direction = spine.MixDirection.mixIn;
                          }
                        }

                        timeline.apply(skeleton, animationLast, animationTime, events, alpha, timelineBlend, direction);
                      }
                    }
                  }

                  if (to.mixDuration > 0) this.queueEvents(from, animationTime);
                  this.events.length = 0;
                  from.nextAnimationLast = animationTime;
                  from.nextTrackLast = from.trackTime;
                  return mix;
                };

                AnimationState.prototype.applyRotateTimeline = function (timeline, skeleton, time, alpha, blend, timelinesRotation, i, firstFrame) {
                  if (firstFrame) timelinesRotation[i] = 0;

                  if (alpha == 1) {
                    timeline.apply(skeleton, 0, time, null, 1, blend, spine.MixDirection.mixIn);
                    return;
                  }

                  var rotateTimeline = timeline;
                  var frames = rotateTimeline.frames;
                  var bone = skeleton.bones[rotateTimeline.boneIndex];
                  if (!bone.active) return;
                  var r1 = 0,
                      r2 = 0;

                  if (time < frames[0]) {
                    switch (blend) {
                      case spine.MixBlend.setup:
                        bone.rotation = bone.data.rotation;

                      default:
                        return;

                      case spine.MixBlend.first:
                        r1 = bone.rotation;
                        r2 = bone.data.rotation;
                    }
                  } else {
                    r1 = blend == spine.MixBlend.setup ? bone.data.rotation : bone.rotation;
                    if (time >= frames[frames.length - spine.RotateTimeline.ENTRIES]) r2 = bone.data.rotation + frames[frames.length + spine.RotateTimeline.PREV_ROTATION];else {
                      var frame = spine.Animation.binarySearch(frames, time, spine.RotateTimeline.ENTRIES);
                      var prevRotation = frames[frame + spine.RotateTimeline.PREV_ROTATION];
                      var frameTime = frames[frame];
                      var percent = rotateTimeline.getCurvePercent((frame >> 1) - 1, 1 - (time - frameTime) / (frames[frame + spine.RotateTimeline.PREV_TIME] - frameTime));
                      r2 = frames[frame + spine.RotateTimeline.ROTATION] - prevRotation;
                      r2 -= (16384 - (16384.499999999996 - r2 / 360 | 0)) * 360;
                      r2 = prevRotation + r2 * percent + bone.data.rotation;
                      r2 -= (16384 - (16384.499999999996 - r2 / 360 | 0)) * 360;
                    }
                  }

                  var total = 0,
                      diff = r2 - r1;
                  diff -= (16384 - (16384.499999999996 - diff / 360 | 0)) * 360;

                  if (diff == 0) {
                    total = timelinesRotation[i];
                  } else {
                    var lastTotal = 0,
                        lastDiff = 0;

                    if (firstFrame) {
                      lastTotal = 0;
                      lastDiff = diff;
                    } else {
                      lastTotal = timelinesRotation[i];
                      lastDiff = timelinesRotation[i + 1];
                    }

                    var current = diff > 0,
                        dir = lastTotal >= 0;

                    if (spine.MathUtils.signum(lastDiff) != spine.MathUtils.signum(diff) && Math.abs(lastDiff) <= 90) {
                      if (Math.abs(lastTotal) > 180) lastTotal += 360 * spine.MathUtils.signum(lastTotal);
                      dir = current;
                    }

                    total = diff + lastTotal - lastTotal % 360;
                    if (dir != current) total += 360 * spine.MathUtils.signum(lastTotal);
                    timelinesRotation[i] = total;
                  }

                  timelinesRotation[i + 1] = diff;
                  r1 += total * alpha;
                  bone.rotation = r1 - (16384 - (16384.499999999996 - r1 / 360 | 0)) * 360;
                };

                AnimationState.prototype.queueEvents = function (entry, animationTime) {
                  var animationStart = entry.animationStart,
                      animationEnd = entry.animationEnd;
                  var duration = animationEnd - animationStart;
                  var trackLastWrapped = entry.trackLast % duration;
                  var events = this.events;
                  var i = 0,
                      n = events.length;

                  for (; i < n; i++) {
                    var event_1 = events[i];
                    if (event_1.time < trackLastWrapped) break;
                    if (event_1.time > animationEnd) continue;
                    this.queue.event(entry, event_1);
                  }

                  var complete = false;
                  if (entry.loop) complete = duration == 0 || trackLastWrapped > entry.trackTime % duration;else complete = animationTime >= animationEnd && entry.animationLast < animationEnd;
                  if (complete) this.queue.complete(entry);

                  for (; i < n; i++) {
                    var event_2 = events[i];
                    if (event_2.time < animationStart) continue;
                    this.queue.event(entry, events[i]);
                  }
                };

                AnimationState.prototype.clearTracks = function () {
                  var oldDrainDisabled = this.queue.drainDisabled;
                  this.queue.drainDisabled = true;

                  for (var i = 0, n = this.tracks.length; i < n; i++) {
                    this.clearTrack(i);
                  }

                  this.tracks.length = 0;
                  this.queue.drainDisabled = oldDrainDisabled;
                  this.queue.drain();
                };

                AnimationState.prototype.clearTrack = function (trackIndex) {
                  if (trackIndex >= this.tracks.length) return;
                  var current = this.tracks[trackIndex];
                  if (current == null) return;
                  this.queue.end(current);
                  this.disposeNext(current);
                  var entry = current;

                  while (true) {
                    var from = entry.mixingFrom;
                    if (from == null) break;
                    this.queue.end(from);
                    entry.mixingFrom = null;
                    entry.mixingTo = null;
                    entry = from;
                  }

                  this.tracks[current.trackIndex] = null;
                  this.queue.drain();
                };

                AnimationState.prototype.setCurrent = function (index, current, interrupt) {
                  var from = this.expandToIndex(index);
                  this.tracks[index] = current;

                  if (from != null) {
                    if (interrupt) this.queue.interrupt(from);
                    current.mixingFrom = from;
                    from.mixingTo = current;
                    current.mixTime = 0;
                    if (from.mixingFrom != null && from.mixDuration > 0) current.interruptAlpha *= Math.min(1, from.mixTime / from.mixDuration);
                    from.timelinesRotation.length = 0;
                  }

                  this.queue.start(current);
                };

                AnimationState.prototype.setAnimation = function (trackIndex, animationName, loop) {
                  var animation = this.data.skeletonData.findAnimation(animationName);
                  if (animation == null) throw new Error("Animation not found: " + animationName);
                  return this.setAnimationWith(trackIndex, animation, loop);
                };

                AnimationState.prototype.setAnimationWith = function (trackIndex, animation, loop) {
                  if (animation == null) throw new Error("animation cannot be null.");
                  var interrupt = true;
                  var current = this.expandToIndex(trackIndex);

                  if (current != null) {
                    if (current.nextTrackLast == -1) {
                      this.tracks[trackIndex] = current.mixingFrom;
                      this.queue.interrupt(current);
                      this.queue.end(current);
                      this.disposeNext(current);
                      current = current.mixingFrom;
                      interrupt = false;
                    } else this.disposeNext(current);
                  }

                  var entry = this.trackEntry(trackIndex, animation, loop, current);
                  this.setCurrent(trackIndex, entry, interrupt);
                  this.queue.drain();
                  return entry;
                };

                AnimationState.prototype.addAnimation = function (trackIndex, animationName, loop, delay) {
                  var animation = this.data.skeletonData.findAnimation(animationName);
                  if (animation == null) throw new Error("Animation not found: " + animationName);
                  return this.addAnimationWith(trackIndex, animation, loop, delay);
                };

                AnimationState.prototype.addAnimationWith = function (trackIndex, animation, loop, delay) {
                  if (animation == null) throw new Error("animation cannot be null.");
                  var last = this.expandToIndex(trackIndex);

                  if (last != null) {
                    while (last.next != null) {
                      last = last.next;
                    }
                  }

                  var entry = this.trackEntry(trackIndex, animation, loop, last);

                  if (last == null) {
                    this.setCurrent(trackIndex, entry, true);
                    this.queue.drain();
                  } else {
                    last.next = entry;

                    if (delay <= 0) {
                      var duration = last.animationEnd - last.animationStart;

                      if (duration != 0) {
                        if (last.loop) delay += duration * (1 + (last.trackTime / duration | 0));else delay += Math.max(duration, last.trackTime);
                        delay -= this.data.getMix(last.animation, animation);
                      } else delay = last.trackTime;
                    }
                  }

                  entry.delay = delay;
                  return entry;
                };

                AnimationState.prototype.setEmptyAnimation = function (trackIndex, mixDuration) {
                  var entry = this.setAnimationWith(trackIndex, AnimationState.emptyAnimation, false);
                  entry.mixDuration = mixDuration;
                  entry.trackEnd = mixDuration;
                  return entry;
                };

                AnimationState.prototype.addEmptyAnimation = function (trackIndex, mixDuration, delay) {
                  if (delay <= 0) delay -= mixDuration;
                  var entry = this.addAnimationWith(trackIndex, AnimationState.emptyAnimation, false, delay);
                  entry.mixDuration = mixDuration;
                  entry.trackEnd = mixDuration;
                  return entry;
                };

                AnimationState.prototype.setEmptyAnimations = function (mixDuration) {
                  var oldDrainDisabled = this.queue.drainDisabled;
                  this.queue.drainDisabled = true;

                  for (var i = 0, n = this.tracks.length; i < n; i++) {
                    var current = this.tracks[i];
                    if (current != null) this.setEmptyAnimation(current.trackIndex, mixDuration);
                  }

                  this.queue.drainDisabled = oldDrainDisabled;
                  this.queue.drain();
                };

                AnimationState.prototype.expandToIndex = function (index) {
                  if (index < this.tracks.length) return this.tracks[index];
                  spine.Utils.ensureArrayCapacity(this.tracks, index + 1, null);
                  this.tracks.length = index + 1;
                  return null;
                };

                AnimationState.prototype.trackEntry = function (trackIndex, animation, loop, last) {
                  var entry = this.trackEntryPool.obtain();
                  entry.trackIndex = trackIndex;
                  entry.animation = animation;
                  entry.loop = loop;
                  entry.holdPrevious = false;
                  entry.eventThreshold = 0;
                  entry.attachmentThreshold = 0;
                  entry.drawOrderThreshold = 0;
                  entry.animationStart = 0;
                  entry.animationEnd = animation.duration;
                  entry.animationLast = -1;
                  entry.nextAnimationLast = -1;
                  entry.delay = 0;
                  entry.trackTime = 0;
                  entry.trackLast = -1;
                  entry.nextTrackLast = -1;
                  entry.trackEnd = Number.MAX_VALUE;
                  entry.timeScale = 1;
                  entry.alpha = 1;
                  entry.interruptAlpha = 1;
                  entry.mixTime = 0;
                  entry.mixDuration = last == null ? 0 : this.data.getMix(last.animation, animation);
                  return entry;
                };

                AnimationState.prototype.disposeNext = function (entry) {
                  var next = entry.next;

                  while (next != null) {
                    this.queue.dispose(next);
                    next = next.next;
                  }

                  entry.next = null;
                };

                AnimationState.prototype._animationsChanged = function () {
                  this.animationsChanged = false;
                  this.propertyIDs.clear();

                  for (var i = 0, n = this.tracks.length; i < n; i++) {
                    var entry = this.tracks[i];
                    if (entry == null) continue;

                    while (entry.mixingFrom != null) {
                      entry = entry.mixingFrom;
                    }

                    do {
                      if (entry.mixingFrom == null || entry.mixBlend != spine.MixBlend.add) this.computeHold(entry);
                      entry = entry.mixingTo;
                    } while (entry != null);
                  }

                  this.propertyIDs.clear();

                  for (var i = this.tracks.length - 1; i >= 0; i--) {
                    var entry = this.tracks[i];

                    while (entry != null) {
                      this.computeNotLast(entry);
                      entry = entry.mixingFrom;
                    }
                  }
                };

                AnimationState.prototype.computeHold = function (entry) {
                  var to = entry.mixingTo;
                  var timelines = entry.animation.timelines;
                  var timelinesCount = entry.animation.timelines.length;
                  var timelineMode = spine.Utils.setArraySize(entry.timelineMode, timelinesCount);
                  entry.timelineHoldMix.length = 0;
                  var timelineDipMix = spine.Utils.setArraySize(entry.timelineHoldMix, timelinesCount);
                  var propertyIDs = this.propertyIDs;

                  if (to != null && to.holdPrevious) {
                    for (var i = 0; i < timelinesCount; i++) {
                      propertyIDs.add(timelines[i].getPropertyId());
                      timelineMode[i] = AnimationState.HOLD;
                    }

                    return;
                  }

                  outer: for (var i = 0; i < timelinesCount; i++) {
                    var timeline = timelines[i];
                    var id = timeline.getPropertyId();
                    if (!propertyIDs.add(id)) timelineMode[i] = AnimationState.SUBSEQUENT;else if (to == null || timeline instanceof spine.AttachmentTimeline || timeline instanceof spine.DrawOrderTimeline || timeline instanceof spine.EventTimeline || !to.animation.hasTimeline(id)) {
                      timelineMode[i] = AnimationState.FIRST;
                    } else {
                      for (var next = to.mixingTo; next != null; next = next.mixingTo) {
                        if (next.animation.hasTimeline(id)) continue;

                        if (entry.mixDuration > 0) {
                          timelineMode[i] = AnimationState.HOLD_MIX;
                          timelineDipMix[i] = next;
                          continue outer;
                        }

                        break;
                      }

                      timelineMode[i] = AnimationState.HOLD;
                    }
                  }
                };

                AnimationState.prototype.computeNotLast = function (entry) {
                  var timelines = entry.animation.timelines;
                  var timelinesCount = entry.animation.timelines.length;
                  var timelineMode = entry.timelineMode;
                  var propertyIDs = this.propertyIDs;

                  for (var i = 0; i < timelinesCount; i++) {
                    if (timelines[i] instanceof spine.AttachmentTimeline) {
                      var timeline = timelines[i];
                      if (!propertyIDs.add(timeline.slotIndex)) timelineMode[i] |= AnimationState.NOT_LAST;
                    }
                  }
                };

                AnimationState.prototype.getCurrent = function (trackIndex) {
                  if (trackIndex >= this.tracks.length) return null;
                  return this.tracks[trackIndex];
                };

                AnimationState.prototype.addListener = function (listener) {
                  if (listener == null) throw new Error("listener cannot be null.");
                  this.listeners.push(listener);
                };

                AnimationState.prototype.removeListener = function (listener) {
                  var index = this.listeners.indexOf(listener);
                  if (index >= 0) this.listeners.splice(index, 1);
                };

                AnimationState.prototype.clearListeners = function () {
                  this.listeners.length = 0;
                };

                AnimationState.prototype.clearListenerNotifications = function () {
                  this.queue.clear();
                };

                AnimationState.emptyAnimation = new spine.Animation("<empty>", [], 0);
                AnimationState.SUBSEQUENT = 0;
                AnimationState.FIRST = 1;
                AnimationState.HOLD = 2;
                AnimationState.HOLD_MIX = 3;
                AnimationState.NOT_LAST = 4;
                return AnimationState;
              }();

              spine.AnimationState = AnimationState;

              var TrackEntry = function () {
                function TrackEntry() {
                  this.mixBlend = spine.MixBlend.replace;
                  this.timelineMode = new Array();
                  this.timelineHoldMix = new Array();
                  this.timelinesRotation = new Array();
                }

                TrackEntry.prototype.reset = function () {
                  this.next = null;
                  this.mixingFrom = null;
                  this.mixingTo = null;
                  this.animation = null;
                  this.listener = null;
                  this.timelineMode.length = 0;
                  this.timelineHoldMix.length = 0;
                  this.timelinesRotation.length = 0;
                };

                TrackEntry.prototype.getAnimationTime = function () {
                  if (this.loop) {
                    var duration = this.animationEnd - this.animationStart;
                    if (duration == 0) return this.animationStart;
                    return this.trackTime % duration + this.animationStart;
                  }

                  return Math.min(this.trackTime + this.animationStart, this.animationEnd);
                };

                TrackEntry.prototype.setAnimationLast = function (animationLast) {
                  this.animationLast = animationLast;
                  this.nextAnimationLast = animationLast;
                };

                TrackEntry.prototype.isComplete = function () {
                  return this.trackTime >= this.animationEnd - this.animationStart;
                };

                TrackEntry.prototype.resetRotationDirections = function () {
                  this.timelinesRotation.length = 0;
                };

                return TrackEntry;
              }();

              spine.TrackEntry = TrackEntry;

              var EventQueue = function () {
                function EventQueue(animState) {
                  this.objects = [];
                  this.drainDisabled = false;
                  this.animState = animState;
                }

                EventQueue.prototype.start = function (entry) {
                  this.objects.push(EventType.start);
                  this.objects.push(entry);
                  this.animState.animationsChanged = true;
                };

                EventQueue.prototype.interrupt = function (entry) {
                  this.objects.push(EventType.interrupt);
                  this.objects.push(entry);
                };

                EventQueue.prototype.end = function (entry) {
                  this.objects.push(EventType.end);
                  this.objects.push(entry);
                  this.animState.animationsChanged = true;
                };

                EventQueue.prototype.dispose = function (entry) {
                  this.objects.push(EventType.dispose);
                  this.objects.push(entry);
                };

                EventQueue.prototype.complete = function (entry) {
                  this.objects.push(EventType.complete);
                  this.objects.push(entry);
                };

                EventQueue.prototype.event = function (entry, event) {
                  this.objects.push(EventType.event);
                  this.objects.push(entry);
                  this.objects.push(event);
                };

                EventQueue.prototype.drain = function () {
                  if (this.drainDisabled) return;
                  this.drainDisabled = true;
                  var objects = this.objects;
                  var listeners = this.animState.listeners;

                  for (var i = 0; i < objects.length; i += 2) {
                    var type = objects[i];
                    var entry = objects[i + 1];

                    switch (type) {
                      case EventType.start:
                        if (entry.listener != null && entry.listener.start) entry.listener.start(entry);

                        for (var ii = 0; ii < listeners.length; ii++) {
                          if (listeners[ii].start) listeners[ii].start(entry);
                        }

                        break;

                      case EventType.interrupt:
                        if (entry.listener != null && entry.listener.interrupt) entry.listener.interrupt(entry);

                        for (var ii = 0; ii < listeners.length; ii++) {
                          if (listeners[ii].interrupt) listeners[ii].interrupt(entry);
                        }

                        break;

                      case EventType.end:
                        if (entry.listener != null && entry.listener.end) entry.listener.end(entry);

                        for (var ii = 0; ii < listeners.length; ii++) {
                          if (listeners[ii].end) listeners[ii].end(entry);
                        }

                      case EventType.dispose:
                        if (entry.listener != null && entry.listener.dispose) entry.listener.dispose(entry);

                        for (var ii = 0; ii < listeners.length; ii++) {
                          if (listeners[ii].dispose) listeners[ii].dispose(entry);
                        }

                        this.animState.trackEntryPool.free(entry);
                        break;

                      case EventType.complete:
                        if (entry.listener != null && entry.listener.complete) entry.listener.complete(entry);

                        for (var ii = 0; ii < listeners.length; ii++) {
                          if (listeners[ii].complete) listeners[ii].complete(entry);
                        }

                        break;

                      case EventType.event:
                        var event_3 = objects[i++ + 2];
                        if (entry.listener != null && entry.listener.event) entry.listener.event(entry, event_3);

                        for (var ii = 0; ii < listeners.length; ii++) {
                          if (listeners[ii].event) listeners[ii].event(entry, event_3);
                        }

                        break;
                    }
                  }

                  this.clear();
                  this.drainDisabled = false;
                };

                EventQueue.prototype.clear = function () {
                  this.objects.length = 0;
                };

                return EventQueue;
              }();

              spine.EventQueue = EventQueue;
              var EventType;

              (function (EventType) {
                EventType[EventType["start"] = 0] = "start";
                EventType[EventType["interrupt"] = 1] = "interrupt";
                EventType[EventType["end"] = 2] = "end";
                EventType[EventType["dispose"] = 3] = "dispose";
                EventType[EventType["complete"] = 4] = "complete";
                EventType[EventType["event"] = 5] = "event";
              })(EventType = spine.EventType || (spine.EventType = {}));

              var AnimationStateAdapter = function () {
                function AnimationStateAdapter() {}

                AnimationStateAdapter.prototype.start = function (entry) {};

                AnimationStateAdapter.prototype.interrupt = function (entry) {};

                AnimationStateAdapter.prototype.end = function (entry) {};

                AnimationStateAdapter.prototype.dispose = function (entry) {};

                AnimationStateAdapter.prototype.complete = function (entry) {};

                AnimationStateAdapter.prototype.event = function (entry, event) {};

                return AnimationStateAdapter;
              }();

              spine.AnimationStateAdapter = AnimationStateAdapter;
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var AnimationStateData = function () {
                function AnimationStateData(skeletonData) {
                  this.animationToMixTime = {};
                  this.defaultMix = 0;
                  if (skeletonData == null) throw new Error("skeletonData cannot be null.");
                  this.skeletonData = skeletonData;
                }

                AnimationStateData.prototype.setMix = function (fromName, toName, duration) {
                  var from = this.skeletonData.findAnimation(fromName);
                  if (from == null) throw new Error("Animation not found: " + fromName);
                  var to = this.skeletonData.findAnimation(toName);
                  if (to == null) throw new Error("Animation not found: " + toName);
                  this.setMixWith(from, to, duration);
                };

                AnimationStateData.prototype.setMixWith = function (from, to, duration) {
                  if (from == null) throw new Error("from cannot be null.");
                  if (to == null) throw new Error("to cannot be null.");
                  var key = from.name + "." + to.name;
                  this.animationToMixTime[key] = duration;
                };

                AnimationStateData.prototype.getMix = function (from, to) {
                  var key = from.name + "." + to.name;
                  var value = this.animationToMixTime[key];
                  return value === undefined ? this.defaultMix : value;
                };

                return AnimationStateData;
              }();

              spine.AnimationStateData = AnimationStateData;
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var AssetManager = function () {
                function AssetManager(textureLoader, pathPrefix) {
                  if (pathPrefix === void 0) {
                    pathPrefix = "";
                  }

                  this.assets = {};
                  this.errors = {};
                  this.toLoad = 0;
                  this.loaded = 0;
                  this.textureLoader = textureLoader;
                  this.pathPrefix = pathPrefix;
                }

                AssetManager.downloadText = function (url, success, error) {
                  var request = new XMLHttpRequest();
                  request.open("GET", url, true);

                  request.onload = function () {
                    if (request.status == 200) {
                      success(request.responseText);
                    } else {
                      error(request.status, request.responseText);
                    }
                  };

                  request.onerror = function () {
                    error(request.status, request.responseText);
                  };

                  request.send();
                };

                AssetManager.downloadBinary = function (url, success, error) {
                  var request = new XMLHttpRequest();
                  request.open("GET", url, true);
                  request.responseType = "arraybuffer";

                  request.onload = function () {
                    if (request.status == 200) {
                      success(new Uint8Array(request.response));
                    } else {
                      error(request.status, request.responseText);
                    }
                  };

                  request.onerror = function () {
                    error(request.status, request.responseText);
                  };

                  request.send();
                };

                AssetManager.prototype.loadBinary = function (path, success, error) {
                  var _this = this;

                  if (success === void 0) {
                    success = null;
                  }

                  if (error === void 0) {
                    error = null;
                  }

                  path = this.pathPrefix + path;
                  this.toLoad++;
                  AssetManager.downloadBinary(path, function (data) {
                    _this.assets[path] = data;
                    if (success) success(path, data);
                    _this.toLoad--;
                    _this.loaded++;
                  }, function (state, responseText) {
                    _this.errors[path] = "Couldn't load binary " + path + ": status " + status + ", " + responseText;
                    if (error) error(path, "Couldn't load binary " + path + ": status " + status + ", " + responseText);
                    _this.toLoad--;
                    _this.loaded++;
                  });
                };

                AssetManager.prototype.loadText = function (path, success, error) {
                  var _this = this;

                  if (success === void 0) {
                    success = null;
                  }

                  if (error === void 0) {
                    error = null;
                  }

                  path = this.pathPrefix + path;
                  this.toLoad++;
                  AssetManager.downloadText(path, function (data) {
                    _this.assets[path] = data;
                    if (success) success(path, data);
                    _this.toLoad--;
                    _this.loaded++;
                  }, function (state, responseText) {
                    _this.errors[path] = "Couldn't load text " + path + ": status " + status + ", " + responseText;
                    if (error) error(path, "Couldn't load text " + path + ": status " + status + ", " + responseText);
                    _this.toLoad--;
                    _this.loaded++;
                  });
                };

                AssetManager.prototype.loadTexture = function (path, success, error) {
                  var _this = this;

                  if (success === void 0) {
                    success = null;
                  }

                  if (error === void 0) {
                    error = null;
                  }

                  path = this.pathPrefix + path;
                  this.toLoad++;
                  var img = new Image();
                  img.crossOrigin = "anonymous";

                  img.onload = function (ev) {
                    var texture = _this.textureLoader(img);

                    _this.assets[path] = texture;
                    _this.toLoad--;
                    _this.loaded++;
                    if (success) success(path, img);
                  };

                  img.onerror = function (ev) {
                    _this.errors[path] = "Couldn't load image " + path;
                    _this.toLoad--;
                    _this.loaded++;
                    if (error) error(path, "Couldn't load image " + path);
                  };

                  img.src = path;
                };

                AssetManager.prototype.loadTextureData = function (path, data, success, error) {
                  var _this = this;

                  if (success === void 0) {
                    success = null;
                  }

                  if (error === void 0) {
                    error = null;
                  }

                  path = this.pathPrefix + path;
                  this.toLoad++;
                  var img = new Image();

                  img.onload = function (ev) {
                    var texture = _this.textureLoader(img);

                    _this.assets[path] = texture;
                    _this.toLoad--;
                    _this.loaded++;
                    if (success) success(path, img);
                  };

                  img.onerror = function (ev) {
                    _this.errors[path] = "Couldn't load image " + path;
                    _this.toLoad--;
                    _this.loaded++;
                    if (error) error(path, "Couldn't load image " + path);
                  };

                  img.src = data;
                };

                AssetManager.prototype.loadTextureAtlas = function (path, success, error) {
                  var _this = this;

                  if (success === void 0) {
                    success = null;
                  }

                  if (error === void 0) {
                    error = null;
                  }

                  var parent = path.lastIndexOf("/") >= 0 ? path.substring(0, path.lastIndexOf("/")) : "";
                  path = this.pathPrefix + path;
                  this.toLoad++;
                  AssetManager.downloadText(path, function (atlasData) {
                    var pagesLoaded = {
                      count: 0
                    };
                    var atlasPages = new Array();

                    try {
                      var atlas = new spine.TextureAtlas(atlasData, function (path) {
                        atlasPages.push(parent + "/" + path);
                        var image = document.createElement("img");
                        image.width = 16;
                        image.height = 16;
                        return new spine.FakeTexture(image);
                      });
                    } catch (e) {
                      var ex = e;
                      _this.errors[path] = "Couldn't load texture atlas " + path + ": " + ex.message;
                      if (error) error(path, "Couldn't load texture atlas " + path + ": " + ex.message);
                      _this.toLoad--;
                      _this.loaded++;
                      return;
                    }

                    var _loop_1 = function _loop_1(atlasPage) {
                      var pageLoadError = false;

                      _this.loadTexture(atlasPage, function (imagePath, image) {
                        pagesLoaded.count++;

                        if (pagesLoaded.count == atlasPages.length) {
                          if (!pageLoadError) {
                            try {
                              var atlas = new spine.TextureAtlas(atlasData, function (path) {
                                return _this.get(parent + "/" + path);
                              });
                              _this.assets[path] = atlas;
                              if (success) success(path, atlas);
                              _this.toLoad--;
                              _this.loaded++;
                            } catch (e) {
                              var ex = e;
                              _this.errors[path] = "Couldn't load texture atlas " + path + ": " + ex.message;
                              if (error) error(path, "Couldn't load texture atlas " + path + ": " + ex.message);
                              _this.toLoad--;
                              _this.loaded++;
                            }
                          } else {
                            _this.errors[path] = "Couldn't load texture atlas page " + imagePath + "} of atlas " + path;
                            if (error) error(path, "Couldn't load texture atlas page " + imagePath + " of atlas " + path);
                            _this.toLoad--;
                            _this.loaded++;
                          }
                        }
                      }, function (imagePath, errorMessage) {
                        pageLoadError = true;
                        pagesLoaded.count++;

                        if (pagesLoaded.count == atlasPages.length) {
                          _this.errors[path] = "Couldn't load texture atlas page " + imagePath + "} of atlas " + path;
                          if (error) error(path, "Couldn't load texture atlas page " + imagePath + " of atlas " + path);
                          _this.toLoad--;
                          _this.loaded++;
                        }
                      });
                    };

                    for (var _i = 0, atlasPages_1 = atlasPages; _i < atlasPages_1.length; _i++) {
                      var atlasPage = atlasPages_1[_i];

                      _loop_1(atlasPage);
                    }
                  }, function (state, responseText) {
                    _this.errors[path] = "Couldn't load texture atlas " + path + ": status " + status + ", " + responseText;
                    if (error) error(path, "Couldn't load texture atlas " + path + ": status " + status + ", " + responseText);
                    _this.toLoad--;
                    _this.loaded++;
                  });
                };

                AssetManager.prototype.get = function (path) {
                  path = this.pathPrefix + path;
                  return this.assets[path];
                };

                AssetManager.prototype.remove = function (path) {
                  path = this.pathPrefix + path;
                  var asset = this.assets[path];
                  if (asset.dispose) asset.dispose();
                  this.assets[path] = null;
                };

                AssetManager.prototype.removeAll = function () {
                  for (var key in this.assets) {
                    var asset = this.assets[key];
                    if (asset.dispose) asset.dispose();
                  }

                  this.assets = {};
                };

                AssetManager.prototype.isLoadingComplete = function () {
                  return this.toLoad == 0;
                };

                AssetManager.prototype.getToLoad = function () {
                  return this.toLoad;
                };

                AssetManager.prototype.getLoaded = function () {
                  return this.loaded;
                };

                AssetManager.prototype.dispose = function () {
                  this.removeAll();
                };

                AssetManager.prototype.hasErrors = function () {
                  return Object.keys(this.errors).length > 0;
                };

                AssetManager.prototype.getErrors = function () {
                  return this.errors;
                };

                return AssetManager;
              }();

              spine.AssetManager = AssetManager;
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var AtlasAttachmentLoader = function () {
                function AtlasAttachmentLoader(atlas) {
                  this.atlas = atlas;
                }

                AtlasAttachmentLoader.prototype.newRegionAttachment = function (skin, name, path) {
                  var region = this.atlas.findRegion(path);

                  if (region == null) {
                    return null;
                  }

                  region.renderObject = region;
                  var attachment = new spine.RegionAttachment(name);
                  attachment.setRegion(region);
                  return attachment;
                };

                AtlasAttachmentLoader.prototype.newMeshAttachment = function (skin, name, path) {
                  var region = this.atlas.findRegion(path);

                  if (region == null) {
                    return null;
                  }

                  region.renderObject = region;
                  var attachment = new spine.MeshAttachment(name);
                  attachment.region = region;
                  return attachment;
                };

                AtlasAttachmentLoader.prototype.newBoundingBoxAttachment = function (skin, name) {
                  return new spine.BoundingBoxAttachment(name);
                };

                AtlasAttachmentLoader.prototype.newPathAttachment = function (skin, name) {
                  return new spine.PathAttachment(name);
                };

                AtlasAttachmentLoader.prototype.newPointAttachment = function (skin, name) {
                  return new spine.PointAttachment(name);
                };

                AtlasAttachmentLoader.prototype.newClippingAttachment = function (skin, name) {
                  return new spine.ClippingAttachment(name);
                };

                return AtlasAttachmentLoader;
              }();

              spine.AtlasAttachmentLoader = AtlasAttachmentLoader;
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var BlendMode;

              (function (BlendMode) {
                BlendMode[BlendMode["Normal"] = 0] = "Normal";
                BlendMode[BlendMode["Additive"] = 1] = "Additive";
                BlendMode[BlendMode["Multiply"] = 2] = "Multiply";
                BlendMode[BlendMode["Screen"] = 3] = "Screen";
              })(BlendMode = spine.BlendMode || (spine.BlendMode = {}));
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var Bone = function () {
                function Bone(data, skeleton, parent) {
                  this.children = new Array();
                  this.x = 0;
                  this.y = 0;
                  this.rotation = 0;
                  this.scaleX = 0;
                  this.scaleY = 0;
                  this.shearX = 0;
                  this.shearY = 0;
                  this.ax = 0;
                  this.ay = 0;
                  this.arotation = 0;
                  this.ascaleX = 0;
                  this.ascaleY = 0;
                  this.ashearX = 0;
                  this.ashearY = 0;
                  this.appliedValid = false;
                  this.a = 0;
                  this.b = 0;
                  this.c = 0;
                  this.d = 0;
                  this.worldY = 0;
                  this.worldX = 0;
                  this.sorted = false;
                  this.active = false;
                  if (data == null) throw new Error("data cannot be null.");
                  if (skeleton == null) throw new Error("skeleton cannot be null.");
                  this.data = data;
                  this.skeleton = skeleton;
                  this.parent = parent;
                  this.setToSetupPose();
                }

                Bone.prototype.isActive = function () {
                  return this.active;
                };

                Bone.prototype.update = function () {
                  this.updateWorldTransformWith(this.x, this.y, this.rotation, this.scaleX, this.scaleY, this.shearX, this.shearY);
                };

                Bone.prototype.updateWorldTransform = function () {
                  this.updateWorldTransformWith(this.x, this.y, this.rotation, this.scaleX, this.scaleY, this.shearX, this.shearY);
                };

                Bone.prototype.updateWorldTransformWith = function (x, y, rotation, scaleX, scaleY, shearX, shearY) {
                  this.ax = x;
                  this.ay = y;
                  this.arotation = rotation;
                  this.ascaleX = scaleX;
                  this.ascaleY = scaleY;
                  this.ashearX = shearX;
                  this.ashearY = shearY;
                  this.appliedValid = true;
                  var parent = this.parent;

                  if (parent == null) {
                    var skeleton = this.skeleton;
                    var rotationY = rotation + 90 + shearY;
                    var sx = skeleton.scaleX;
                    var sy = skeleton.scaleY;
                    this.a = spine.MathUtils.cosDeg(rotation + shearX) * scaleX * sx;
                    this.b = spine.MathUtils.cosDeg(rotationY) * scaleY * sx;
                    this.c = spine.MathUtils.sinDeg(rotation + shearX) * scaleX * sy;
                    this.d = spine.MathUtils.sinDeg(rotationY) * scaleY * sy;
                    this.worldX = x * sx + skeleton.x;
                    this.worldY = y * sy + skeleton.y;
                    return;
                  }

                  var pa = parent.a,
                      pb = parent.b,
                      pc = parent.c,
                      pd = parent.d;
                  this.worldX = pa * x + pb * y + parent.worldX;
                  this.worldY = pc * x + pd * y + parent.worldY;

                  switch (this.data.transformMode) {
                    case spine.TransformMode.Normal:
                      {
                        var rotationY = rotation + 90 + shearY;
                        var la = spine.MathUtils.cosDeg(rotation + shearX) * scaleX;
                        var lb = spine.MathUtils.cosDeg(rotationY) * scaleY;
                        var lc = spine.MathUtils.sinDeg(rotation + shearX) * scaleX;
                        var ld = spine.MathUtils.sinDeg(rotationY) * scaleY;
                        this.a = pa * la + pb * lc;
                        this.b = pa * lb + pb * ld;
                        this.c = pc * la + pd * lc;
                        this.d = pc * lb + pd * ld;
                        return;
                      }

                    case spine.TransformMode.OnlyTranslation:
                      {
                        var rotationY = rotation + 90 + shearY;
                        this.a = spine.MathUtils.cosDeg(rotation + shearX) * scaleX;
                        this.b = spine.MathUtils.cosDeg(rotationY) * scaleY;
                        this.c = spine.MathUtils.sinDeg(rotation + shearX) * scaleX;
                        this.d = spine.MathUtils.sinDeg(rotationY) * scaleY;
                        break;
                      }

                    case spine.TransformMode.NoRotationOrReflection:
                      {
                        var s = pa * pa + pc * pc;
                        var prx = 0;

                        if (s > 0.0001) {
                          s = Math.abs(pa * pd - pb * pc) / s;
                          pb = pc * s;
                          pd = pa * s;
                          prx = Math.atan2(pc, pa) * spine.MathUtils.radDeg;
                        } else {
                          pa = 0;
                          pc = 0;
                          prx = 90 - Math.atan2(pd, pb) * spine.MathUtils.radDeg;
                        }

                        var rx = rotation + shearX - prx;
                        var ry = rotation + shearY - prx + 90;
                        var la = spine.MathUtils.cosDeg(rx) * scaleX;
                        var lb = spine.MathUtils.cosDeg(ry) * scaleY;
                        var lc = spine.MathUtils.sinDeg(rx) * scaleX;
                        var ld = spine.MathUtils.sinDeg(ry) * scaleY;
                        this.a = pa * la - pb * lc;
                        this.b = pa * lb - pb * ld;
                        this.c = pc * la + pd * lc;
                        this.d = pc * lb + pd * ld;
                        break;
                      }

                    case spine.TransformMode.NoScale:
                    case spine.TransformMode.NoScaleOrReflection:
                      {
                        var cos = spine.MathUtils.cosDeg(rotation);
                        var sin = spine.MathUtils.sinDeg(rotation);
                        var za = (pa * cos + pb * sin) / this.skeleton.scaleX;
                        var zc = (pc * cos + pd * sin) / this.skeleton.scaleY;
                        var s = Math.sqrt(za * za + zc * zc);
                        if (s > 0.00001) s = 1 / s;
                        za *= s;
                        zc *= s;
                        s = Math.sqrt(za * za + zc * zc);
                        if (this.data.transformMode == spine.TransformMode.NoScale && pa * pd - pb * pc < 0 != (this.skeleton.scaleX < 0 != this.skeleton.scaleY < 0)) s = -s;
                        var r = Math.PI / 2 + Math.atan2(zc, za);
                        var zb = Math.cos(r) * s;
                        var zd = Math.sin(r) * s;
                        var la = spine.MathUtils.cosDeg(shearX) * scaleX;
                        var lb = spine.MathUtils.cosDeg(90 + shearY) * scaleY;
                        var lc = spine.MathUtils.sinDeg(shearX) * scaleX;
                        var ld = spine.MathUtils.sinDeg(90 + shearY) * scaleY;
                        this.a = za * la + zb * lc;
                        this.b = za * lb + zb * ld;
                        this.c = zc * la + zd * lc;
                        this.d = zc * lb + zd * ld;
                        break;
                      }
                  }

                  this.a *= this.skeleton.scaleX;
                  this.b *= this.skeleton.scaleX;
                  this.c *= this.skeleton.scaleY;
                  this.d *= this.skeleton.scaleY;
                };

                Bone.prototype.setToSetupPose = function () {
                  var data = this.data;
                  this.x = data.x;
                  this.y = data.y;
                  this.rotation = data.rotation;
                  this.scaleX = data.scaleX;
                  this.scaleY = data.scaleY;
                  this.shearX = data.shearX;
                  this.shearY = data.shearY;
                };

                Bone.prototype.getWorldRotationX = function () {
                  return Math.atan2(this.c, this.a) * spine.MathUtils.radDeg;
                };

                Bone.prototype.getWorldRotationY = function () {
                  return Math.atan2(this.d, this.b) * spine.MathUtils.radDeg;
                };

                Bone.prototype.getWorldScaleX = function () {
                  return Math.sqrt(this.a * this.a + this.c * this.c);
                };

                Bone.prototype.getWorldScaleY = function () {
                  return Math.sqrt(this.b * this.b + this.d * this.d);
                };

                Bone.prototype.updateAppliedTransform = function () {
                  this.appliedValid = true;
                  var parent = this.parent;

                  if (parent == null) {
                    this.ax = this.worldX;
                    this.ay = this.worldY;
                    this.arotation = Math.atan2(this.c, this.a) * spine.MathUtils.radDeg;
                    this.ascaleX = Math.sqrt(this.a * this.a + this.c * this.c);
                    this.ascaleY = Math.sqrt(this.b * this.b + this.d * this.d);
                    this.ashearX = 0;
                    this.ashearY = Math.atan2(this.a * this.b + this.c * this.d, this.a * this.d - this.b * this.c) * spine.MathUtils.radDeg;
                    return;
                  }

                  var pa = parent.a,
                      pb = parent.b,
                      pc = parent.c,
                      pd = parent.d;
                  var pid = 1 / (pa * pd - pb * pc);
                  var dx = this.worldX - parent.worldX,
                      dy = this.worldY - parent.worldY;
                  this.ax = dx * pd * pid - dy * pb * pid;
                  this.ay = dy * pa * pid - dx * pc * pid;
                  var ia = pid * pd;
                  var id = pid * pa;
                  var ib = pid * pb;
                  var ic = pid * pc;
                  var ra = ia * this.a - ib * this.c;
                  var rb = ia * this.b - ib * this.d;
                  var rc = id * this.c - ic * this.a;
                  var rd = id * this.d - ic * this.b;
                  this.ashearX = 0;
                  this.ascaleX = Math.sqrt(ra * ra + rc * rc);

                  if (this.ascaleX > 0.0001) {
                    var det = ra * rd - rb * rc;
                    this.ascaleY = det / this.ascaleX;
                    this.ashearY = Math.atan2(ra * rb + rc * rd, det) * spine.MathUtils.radDeg;
                    this.arotation = Math.atan2(rc, ra) * spine.MathUtils.radDeg;
                  } else {
                    this.ascaleX = 0;
                    this.ascaleY = Math.sqrt(rb * rb + rd * rd);
                    this.ashearY = 0;
                    this.arotation = 90 - Math.atan2(rd, rb) * spine.MathUtils.radDeg;
                  }
                };

                Bone.prototype.worldToLocal = function (world) {
                  var a = this.a,
                      b = this.b,
                      c = this.c,
                      d = this.d;
                  var invDet = 1 / (a * d - b * c);
                  var x = world.x - this.worldX,
                      y = world.y - this.worldY;
                  world.x = x * d * invDet - y * b * invDet;
                  world.y = y * a * invDet - x * c * invDet;
                  return world;
                };

                Bone.prototype.localToWorld = function (local) {
                  var x = local.x,
                      y = local.y;
                  local.x = x * this.a + y * this.b + this.worldX;
                  local.y = x * this.c + y * this.d + this.worldY;
                  return local;
                };

                Bone.prototype.worldToLocalRotation = function (worldRotation) {
                  var sin = spine.MathUtils.sinDeg(worldRotation),
                      cos = spine.MathUtils.cosDeg(worldRotation);
                  return Math.atan2(this.a * sin - this.c * cos, this.d * cos - this.b * sin) * spine.MathUtils.radDeg + this.rotation - this.shearX;
                };

                Bone.prototype.localToWorldRotation = function (localRotation) {
                  localRotation -= this.rotation - this.shearX;
                  var sin = spine.MathUtils.sinDeg(localRotation),
                      cos = spine.MathUtils.cosDeg(localRotation);
                  return Math.atan2(cos * this.c + sin * this.d, cos * this.a + sin * this.b) * spine.MathUtils.radDeg;
                };

                Bone.prototype.rotateWorld = function (degrees) {
                  var a = this.a,
                      b = this.b,
                      c = this.c,
                      d = this.d;
                  var cos = spine.MathUtils.cosDeg(degrees),
                      sin = spine.MathUtils.sinDeg(degrees);
                  this.a = cos * a - sin * c;
                  this.b = cos * b - sin * d;
                  this.c = sin * a + cos * c;
                  this.d = sin * b + cos * d;
                  this.appliedValid = false;
                };

                return Bone;
              }();

              spine.Bone = Bone;
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var BoneData = function () {
                function BoneData(index, name, parent) {
                  this.x = 0;
                  this.y = 0;
                  this.rotation = 0;
                  this.scaleX = 1;
                  this.scaleY = 1;
                  this.shearX = 0;
                  this.shearY = 0;
                  this.transformMode = TransformMode.Normal;
                  this.skinRequired = false;
                  this.color = new spine.Color();
                  if (index < 0) throw new Error("index must be >= 0.");
                  if (name == null) throw new Error("name cannot be null.");
                  this.index = index;
                  this.name = name;
                  this.parent = parent;
                }

                return BoneData;
              }();

              spine.BoneData = BoneData;
              var TransformMode;

              (function (TransformMode) {
                TransformMode[TransformMode["Normal"] = 0] = "Normal";
                TransformMode[TransformMode["OnlyTranslation"] = 1] = "OnlyTranslation";
                TransformMode[TransformMode["NoRotationOrReflection"] = 2] = "NoRotationOrReflection";
                TransformMode[TransformMode["NoScale"] = 3] = "NoScale";
                TransformMode[TransformMode["NoScaleOrReflection"] = 4] = "NoScaleOrReflection";
              })(TransformMode = spine.TransformMode || (spine.TransformMode = {}));
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var ConstraintData = function () {
                function ConstraintData(name, order, skinRequired) {
                  this.name = name;
                  this.order = order;
                  this.skinRequired = skinRequired;
                }

                return ConstraintData;
              }();

              spine.ConstraintData = ConstraintData;
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var Event = function () {
                function Event(time, data) {
                  if (data == null) throw new Error("data cannot be null.");
                  this.time = time;
                  this.data = data;
                }

                return Event;
              }();

              spine.Event = Event;
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var EventData = function () {
                function EventData(name) {
                  this.name = name;
                }

                return EventData;
              }();

              spine.EventData = EventData;
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var IkConstraint = function () {
                function IkConstraint(data, skeleton) {
                  this.bendDirection = 0;
                  this.compress = false;
                  this.stretch = false;
                  this.mix = 1;
                  this.softness = 0;
                  this.active = false;
                  if (data == null) throw new Error("data cannot be null.");
                  if (skeleton == null) throw new Error("skeleton cannot be null.");
                  this.data = data;
                  this.mix = data.mix;
                  this.softness = data.softness;
                  this.bendDirection = data.bendDirection;
                  this.compress = data.compress;
                  this.stretch = data.stretch;
                  this.bones = new Array();

                  for (var i = 0; i < data.bones.length; i++) {
                    this.bones.push(skeleton.findBone(data.bones[i].name));
                  }

                  this.target = skeleton.findBone(data.target.name);
                }

                IkConstraint.prototype.isActive = function () {
                  return this.active;
                };

                IkConstraint.prototype.apply = function () {
                  this.update();
                };

                IkConstraint.prototype.update = function () {
                  var target = this.target;
                  var bones = this.bones;

                  switch (bones.length) {
                    case 1:
                      this.apply1(bones[0], target.worldX, target.worldY, this.compress, this.stretch, this.data.uniform, this.mix);
                      break;

                    case 2:
                      this.apply2(bones[0], bones[1], target.worldX, target.worldY, this.bendDirection, this.stretch, this.softness, this.mix);
                      break;
                  }
                };

                IkConstraint.prototype.apply1 = function (bone, targetX, targetY, compress, stretch, uniform, alpha) {
                  if (!bone.appliedValid) bone.updateAppliedTransform();
                  var p = bone.parent;
                  var id = 1 / (p.a * p.d - p.b * p.c);
                  var x = targetX - p.worldX,
                      y = targetY - p.worldY;
                  var tx = (x * p.d - y * p.b) * id - bone.ax,
                      ty = (y * p.a - x * p.c) * id - bone.ay;
                  var rotationIK = Math.atan2(ty, tx) * spine.MathUtils.radDeg - bone.ashearX - bone.arotation;
                  if (bone.ascaleX < 0) rotationIK += 180;
                  if (rotationIK > 180) rotationIK -= 360;else if (rotationIK < -180) rotationIK += 360;
                  var sx = bone.ascaleX,
                      sy = bone.ascaleY;

                  if (compress || stretch) {
                    var b = bone.data.length * sx,
                        dd = Math.sqrt(tx * tx + ty * ty);

                    if (compress && dd < b || stretch && dd > b && b > 0.0001) {
                      var s = (dd / b - 1) * alpha + 1;
                      sx *= s;
                      if (uniform) sy *= s;
                    }
                  }

                  bone.updateWorldTransformWith(bone.ax, bone.ay, bone.arotation + rotationIK * alpha, sx, sy, bone.ashearX, bone.ashearY);
                };

                IkConstraint.prototype.apply2 = function (parent, child, targetX, targetY, bendDir, stretch, softness, alpha) {
                  if (alpha == 0) {
                    child.updateWorldTransform();
                    return;
                  }

                  if (!parent.appliedValid) parent.updateAppliedTransform();
                  if (!child.appliedValid) child.updateAppliedTransform();
                  var px = parent.ax,
                      py = parent.ay,
                      psx = parent.ascaleX,
                      sx = psx,
                      psy = parent.ascaleY,
                      csx = child.ascaleX;
                  var os1 = 0,
                      os2 = 0,
                      s2 = 0;

                  if (psx < 0) {
                    psx = -psx;
                    os1 = 180;
                    s2 = -1;
                  } else {
                    os1 = 0;
                    s2 = 1;
                  }

                  if (psy < 0) {
                    psy = -psy;
                    s2 = -s2;
                  }

                  if (csx < 0) {
                    csx = -csx;
                    os2 = 180;
                  } else os2 = 0;

                  var cx = child.ax,
                      cy = 0,
                      cwx = 0,
                      cwy = 0,
                      a = parent.a,
                      b = parent.b,
                      c = parent.c,
                      d = parent.d;
                  var u = Math.abs(psx - psy) <= 0.0001;

                  if (!u) {
                    cy = 0;
                    cwx = a * cx + parent.worldX;
                    cwy = c * cx + parent.worldY;
                  } else {
                    cy = child.ay;
                    cwx = a * cx + b * cy + parent.worldX;
                    cwy = c * cx + d * cy + parent.worldY;
                  }

                  var pp = parent.parent;
                  a = pp.a;
                  b = pp.b;
                  c = pp.c;
                  d = pp.d;
                  var id = 1 / (a * d - b * c),
                      x = cwx - pp.worldX,
                      y = cwy - pp.worldY;
                  var dx = (x * d - y * b) * id - px,
                      dy = (y * a - x * c) * id - py;
                  var l1 = Math.sqrt(dx * dx + dy * dy),
                      l2 = child.data.length * csx,
                      a1,
                      a2;

                  if (l1 < 0.0001) {
                    this.apply1(parent, targetX, targetY, false, stretch, false, alpha);
                    child.updateWorldTransformWith(cx, cy, 0, child.ascaleX, child.ascaleY, child.ashearX, child.ashearY);
                    return;
                  }

                  x = targetX - pp.worldX;
                  y = targetY - pp.worldY;
                  var tx = (x * d - y * b) * id - px,
                      ty = (y * a - x * c) * id - py;
                  var dd = tx * tx + ty * ty;

                  if (softness != 0) {
                    softness *= psx * (csx + 1) / 2;
                    var td = Math.sqrt(dd),
                        sd = td - l1 - l2 * psx + softness;

                    if (sd > 0) {
                      var p = Math.min(1, sd / (softness * 2)) - 1;
                      p = (sd - softness * (1 - p * p)) / td;
                      tx -= p * tx;
                      ty -= p * ty;
                      dd = tx * tx + ty * ty;
                    }
                  }

                  outer: if (u) {
                    l2 *= psx;
                    var cos = (dd - l1 * l1 - l2 * l2) / (2 * l1 * l2);
                    if (cos < -1) cos = -1;else if (cos > 1) {
                      cos = 1;
                      if (stretch) sx *= (Math.sqrt(dd) / (l1 + l2) - 1) * alpha + 1;
                    }
                    a2 = Math.acos(cos) * bendDir;
                    a = l1 + l2 * cos;
                    b = l2 * Math.sin(a2);
                    a1 = Math.atan2(ty * a - tx * b, tx * a + ty * b);
                  } else {
                    a = psx * l2;
                    b = psy * l2;
                    var aa = a * a,
                        bb = b * b,
                        ta = Math.atan2(ty, tx);
                    c = bb * l1 * l1 + aa * dd - aa * bb;
                    var c1 = -2 * bb * l1,
                        c2 = bb - aa;
                    d = c1 * c1 - 4 * c2 * c;

                    if (d >= 0) {
                      var q = Math.sqrt(d);
                      if (c1 < 0) q = -q;
                      q = -(c1 + q) / 2;
                      var r0 = q / c2,
                          r1 = c / q;
                      var r = Math.abs(r0) < Math.abs(r1) ? r0 : r1;

                      if (r * r <= dd) {
                        y = Math.sqrt(dd - r * r) * bendDir;
                        a1 = ta - Math.atan2(y, r);
                        a2 = Math.atan2(y / psy, (r - l1) / psx);
                        break outer;
                      }
                    }

                    var minAngle = spine.MathUtils.PI,
                        minX = l1 - a,
                        minDist = minX * minX,
                        minY = 0;
                    var maxAngle = 0,
                        maxX = l1 + a,
                        maxDist = maxX * maxX,
                        maxY = 0;
                    c = -a * l1 / (aa - bb);

                    if (c >= -1 && c <= 1) {
                      c = Math.acos(c);
                      x = a * Math.cos(c) + l1;
                      y = b * Math.sin(c);
                      d = x * x + y * y;

                      if (d < minDist) {
                        minAngle = c;
                        minDist = d;
                        minX = x;
                        minY = y;
                      }

                      if (d > maxDist) {
                        maxAngle = c;
                        maxDist = d;
                        maxX = x;
                        maxY = y;
                      }
                    }

                    if (dd <= (minDist + maxDist) / 2) {
                      a1 = ta - Math.atan2(minY * bendDir, minX);
                      a2 = minAngle * bendDir;
                    } else {
                      a1 = ta - Math.atan2(maxY * bendDir, maxX);
                      a2 = maxAngle * bendDir;
                    }
                  }

                  var os = Math.atan2(cy, cx) * s2;
                  var rotation = parent.arotation;
                  a1 = (a1 - os) * spine.MathUtils.radDeg + os1 - rotation;
                  if (a1 > 180) a1 -= 360;else if (a1 < -180) a1 += 360;
                  parent.updateWorldTransformWith(px, py, rotation + a1 * alpha, sx, parent.ascaleY, 0, 0);
                  rotation = child.arotation;
                  a2 = ((a2 + os) * spine.MathUtils.radDeg - child.ashearX) * s2 + os2 - rotation;
                  if (a2 > 180) a2 -= 360;else if (a2 < -180) a2 += 360;
                  child.updateWorldTransformWith(cx, cy, rotation + a2 * alpha, child.ascaleX, child.ascaleY, child.ashearX, child.ashearY);
                };

                return IkConstraint;
              }();

              spine.IkConstraint = IkConstraint;
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var IkConstraintData = function (_super) {
                __extends(IkConstraintData, _super);

                function IkConstraintData(name) {
                  var _this = _super.call(this, name, 0, false) || this;

                  _this.bones = new Array();
                  _this.bendDirection = 1;
                  _this.compress = false;
                  _this.stretch = false;
                  _this.uniform = false;
                  _this.mix = 1;
                  _this.softness = 0;
                  return _this;
                }

                return IkConstraintData;
              }(spine.ConstraintData);

              spine.IkConstraintData = IkConstraintData;
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var PathConstraint = function () {
                function PathConstraint(data, skeleton) {
                  this.position = 0;
                  this.spacing = 0;
                  this.rotateMix = 0;
                  this.translateMix = 0;
                  this.spaces = new Array();
                  this.positions = new Array();
                  this.world = new Array();
                  this.curves = new Array();
                  this.lengths = new Array();
                  this.segments = new Array();
                  this.active = false;
                  if (data == null) throw new Error("data cannot be null.");
                  if (skeleton == null) throw new Error("skeleton cannot be null.");
                  this.data = data;
                  this.bones = new Array();

                  for (var i = 0, n = data.bones.length; i < n; i++) {
                    this.bones.push(skeleton.findBone(data.bones[i].name));
                  }

                  this.target = skeleton.findSlot(data.target.name);
                  this.position = data.position;
                  this.spacing = data.spacing;
                  this.rotateMix = data.rotateMix;
                  this.translateMix = data.translateMix;
                }

                PathConstraint.prototype.isActive = function () {
                  return this.active;
                };

                PathConstraint.prototype.apply = function () {
                  this.update();
                };

                PathConstraint.prototype.update = function () {
                  var attachment = this.target.getAttachment();
                  if (!(attachment instanceof spine.PathAttachment)) return;
                  var rotateMix = this.rotateMix,
                      translateMix = this.translateMix;
                  var translate = translateMix > 0,
                      rotate = rotateMix > 0;
                  if (!translate && !rotate) return;
                  var data = this.data;
                  var percentSpacing = data.spacingMode == spine.SpacingMode.Percent;
                  var rotateMode = data.rotateMode;
                  var tangents = rotateMode == spine.RotateMode.Tangent,
                      scale = rotateMode == spine.RotateMode.ChainScale;
                  var boneCount = this.bones.length,
                      spacesCount = tangents ? boneCount : boneCount + 1;
                  var bones = this.bones;
                  var spaces = spine.Utils.setArraySize(this.spaces, spacesCount),
                      lengths = null;
                  var spacing = this.spacing;

                  if (scale || !percentSpacing) {
                    if (scale) lengths = spine.Utils.setArraySize(this.lengths, boneCount);
                    var lengthSpacing = data.spacingMode == spine.SpacingMode.Length;

                    for (var i = 0, n = spacesCount - 1; i < n;) {
                      var bone = bones[i];
                      var setupLength = bone.data.length;

                      if (setupLength < PathConstraint.epsilon) {
                        if (scale) lengths[i] = 0;
                        spaces[++i] = 0;
                      } else if (percentSpacing) {
                        if (scale) {
                          var x = setupLength * bone.a,
                              y = setupLength * bone.c;
                          var length_1 = Math.sqrt(x * x + y * y);
                          lengths[i] = length_1;
                        }

                        spaces[++i] = spacing;
                      } else {
                        var x = setupLength * bone.a,
                            y = setupLength * bone.c;
                        var length_2 = Math.sqrt(x * x + y * y);
                        if (scale) lengths[i] = length_2;
                        spaces[++i] = (lengthSpacing ? setupLength + spacing : spacing) * length_2 / setupLength;
                      }
                    }
                  } else {
                    for (var i = 1; i < spacesCount; i++) {
                      spaces[i] = spacing;
                    }
                  }

                  var positions = this.computeWorldPositions(attachment, spacesCount, tangents, data.positionMode == spine.PositionMode.Percent, percentSpacing);
                  var boneX = positions[0],
                      boneY = positions[1],
                      offsetRotation = data.offsetRotation;
                  var tip = false;
                  if (offsetRotation == 0) tip = rotateMode == spine.RotateMode.Chain;else {
                    tip = false;
                    var p = this.target.bone;
                    offsetRotation *= p.a * p.d - p.b * p.c > 0 ? spine.MathUtils.degRad : -spine.MathUtils.degRad;
                  }

                  for (var i = 0, p = 3; i < boneCount; i++, p += 3) {
                    var bone = bones[i];
                    bone.worldX += (boneX - bone.worldX) * translateMix;
                    bone.worldY += (boneY - bone.worldY) * translateMix;
                    var x = positions[p],
                        y = positions[p + 1],
                        dx = x - boneX,
                        dy = y - boneY;

                    if (scale) {
                      var length_3 = lengths[i];

                      if (length_3 != 0) {
                        var s = (Math.sqrt(dx * dx + dy * dy) / length_3 - 1) * rotateMix + 1;
                        bone.a *= s;
                        bone.c *= s;
                      }
                    }

                    boneX = x;
                    boneY = y;

                    if (rotate) {
                      var a = bone.a,
                          b = bone.b,
                          c = bone.c,
                          d = bone.d,
                          r = 0,
                          cos = 0,
                          sin = 0;
                      if (tangents) r = positions[p - 1];else if (spaces[i + 1] == 0) r = positions[p + 2];else r = Math.atan2(dy, dx);
                      r -= Math.atan2(c, a);

                      if (tip) {
                        cos = Math.cos(r);
                        sin = Math.sin(r);
                        var length_4 = bone.data.length;
                        boneX += (length_4 * (cos * a - sin * c) - dx) * rotateMix;
                        boneY += (length_4 * (sin * a + cos * c) - dy) * rotateMix;
                      } else {
                        r += offsetRotation;
                      }

                      if (r > spine.MathUtils.PI) r -= spine.MathUtils.PI2;else if (r < -spine.MathUtils.PI) r += spine.MathUtils.PI2;
                      r *= rotateMix;
                      cos = Math.cos(r);
                      sin = Math.sin(r);
                      bone.a = cos * a - sin * c;
                      bone.b = cos * b - sin * d;
                      bone.c = sin * a + cos * c;
                      bone.d = sin * b + cos * d;
                    }

                    bone.appliedValid = false;
                  }
                };

                PathConstraint.prototype.computeWorldPositions = function (path, spacesCount, tangents, percentPosition, percentSpacing) {
                  var target = this.target;
                  var position = this.position;
                  var spaces = this.spaces,
                      out = spine.Utils.setArraySize(this.positions, spacesCount * 3 + 2),
                      world = null;
                  var closed = path.closed;
                  var verticesLength = path.worldVerticesLength,
                      curveCount = verticesLength / 6,
                      prevCurve = PathConstraint.NONE;

                  if (!path.constantSpeed) {
                    var lengths = path.lengths;
                    curveCount -= closed ? 1 : 2;
                    var pathLength_1 = lengths[curveCount];
                    if (percentPosition) position *= pathLength_1;

                    if (percentSpacing) {
                      for (var i = 1; i < spacesCount; i++) {
                        spaces[i] *= pathLength_1;
                      }
                    }

                    world = spine.Utils.setArraySize(this.world, 8);

                    for (var i = 0, o = 0, curve = 0; i < spacesCount; i++, o += 3) {
                      var space = spaces[i];
                      position += space;
                      var p = position;

                      if (closed) {
                        p %= pathLength_1;
                        if (p < 0) p += pathLength_1;
                        curve = 0;
                      } else if (p < 0) {
                        if (prevCurve != PathConstraint.BEFORE) {
                          prevCurve = PathConstraint.BEFORE;
                          path.computeWorldVertices(target, 2, 4, world, 0, 2);
                        }

                        this.addBeforePosition(p, world, 0, out, o);
                        continue;
                      } else if (p > pathLength_1) {
                        if (prevCurve != PathConstraint.AFTER) {
                          prevCurve = PathConstraint.AFTER;
                          path.computeWorldVertices(target, verticesLength - 6, 4, world, 0, 2);
                        }

                        this.addAfterPosition(p - pathLength_1, world, 0, out, o);
                        continue;
                      }

                      for (;; curve++) {
                        var length_5 = lengths[curve];
                        if (p > length_5) continue;
                        if (curve == 0) p /= length_5;else {
                          var prev = lengths[curve - 1];
                          p = (p - prev) / (length_5 - prev);
                        }
                        break;
                      }

                      if (curve != prevCurve) {
                        prevCurve = curve;

                        if (closed && curve == curveCount) {
                          path.computeWorldVertices(target, verticesLength - 4, 4, world, 0, 2);
                          path.computeWorldVertices(target, 0, 4, world, 4, 2);
                        } else path.computeWorldVertices(target, curve * 6 + 2, 8, world, 0, 2);
                      }

                      this.addCurvePosition(p, world[0], world[1], world[2], world[3], world[4], world[5], world[6], world[7], out, o, tangents || i > 0 && space == 0);
                    }

                    return out;
                  }

                  if (closed) {
                    verticesLength += 2;
                    world = spine.Utils.setArraySize(this.world, verticesLength);
                    path.computeWorldVertices(target, 2, verticesLength - 4, world, 0, 2);
                    path.computeWorldVertices(target, 0, 2, world, verticesLength - 4, 2);
                    world[verticesLength - 2] = world[0];
                    world[verticesLength - 1] = world[1];
                  } else {
                    curveCount--;
                    verticesLength -= 4;
                    world = spine.Utils.setArraySize(this.world, verticesLength);
                    path.computeWorldVertices(target, 2, verticesLength, world, 0, 2);
                  }

                  var curves = spine.Utils.setArraySize(this.curves, curveCount);
                  var pathLength = 0;
                  var x1 = world[0],
                      y1 = world[1],
                      cx1 = 0,
                      cy1 = 0,
                      cx2 = 0,
                      cy2 = 0,
                      x2 = 0,
                      y2 = 0;
                  var tmpx = 0,
                      tmpy = 0,
                      dddfx = 0,
                      dddfy = 0,
                      ddfx = 0,
                      ddfy = 0,
                      dfx = 0,
                      dfy = 0;

                  for (var i = 0, w = 2; i < curveCount; i++, w += 6) {
                    cx1 = world[w];
                    cy1 = world[w + 1];
                    cx2 = world[w + 2];
                    cy2 = world[w + 3];
                    x2 = world[w + 4];
                    y2 = world[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;else position *= pathLength / path.lengths[curveCount - 1];

                  if (percentSpacing) {
                    for (var i = 1; i < spacesCount; i++) {
                      spaces[i] *= pathLength;
                    }
                  }

                  var segments = this.segments;
                  var curveLength = 0;

                  for (var i = 0, o = 0, curve = 0, segment = 0; i < spacesCount; i++, o += 3) {
                    var space = spaces[i];
                    position += space;
                    var p = position;

                    if (closed) {
                      p %= pathLength;
                      if (p < 0) p += pathLength;
                      curve = 0;
                    } else if (p < 0) {
                      this.addBeforePosition(p, world, 0, out, o);
                      continue;
                    } else if (p > pathLength) {
                      this.addAfterPosition(p - pathLength, world, verticesLength - 4, out, o);
                      continue;
                    }

                    for (;; curve++) {
                      var length_6 = curves[curve];
                      if (p > length_6) continue;
                      if (curve == 0) p /= length_6;else {
                        var prev = curves[curve - 1];
                        p = (p - prev) / (length_6 - prev);
                      }
                      break;
                    }

                    if (curve != prevCurve) {
                      prevCurve = curve;
                      var ii = curve * 6;
                      x1 = world[ii];
                      y1 = world[ii + 1];
                      cx1 = world[ii + 2];
                      cy1 = world[ii + 3];
                      cx2 = world[ii + 4];
                      cy2 = world[ii + 5];
                      x2 = world[ii + 6];
                      y2 = world[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_7 = segments[segment];
                      if (p > length_7) continue;
                      if (segment == 0) p /= length_7;else {
                        var prev = segments[segment - 1];
                        p = segment + (p - prev) / (length_7 - prev);
                      }
                      break;
                    }

                    this.addCurvePosition(p * 0.1, x1, y1, cx1, cy1, cx2, cy2, x2, y2, out, o, tangents || i > 0 && space == 0);
                  }

                  return out;
                };

                PathConstraint.prototype.addBeforePosition = function (p, temp, i, out, o) {
                  var x1 = temp[i],
                      y1 = temp[i + 1],
                      dx = temp[i + 2] - x1,
                      dy = temp[i + 3] - y1,
                      r = Math.atan2(dy, dx);
                  out[o] = x1 + p * Math.cos(r);
                  out[o + 1] = y1 + p * Math.sin(r);
                  out[o + 2] = r;
                };

                PathConstraint.prototype.addAfterPosition = function (p, temp, i, out, o) {
                  var x1 = temp[i + 2],
                      y1 = temp[i + 3],
                      dx = x1 - temp[i],
                      dy = y1 - temp[i + 1],
                      r = Math.atan2(dy, dx);
                  out[o] = x1 + p * Math.cos(r);
                  out[o + 1] = y1 + p * Math.sin(r);
                  out[o + 2] = r;
                };

                PathConstraint.prototype.addCurvePosition = function (p, x1, y1, cx1, cy1, cx2, cy2, x2, y2, out, o, tangents) {
                  if (p == 0 || isNaN(p)) {
                    out[o] = x1;
                    out[o + 1] = y1;
                    out[o + 2] = Math.atan2(cy1 - y1, cx1 - x1);
                    return;
                  }

                  var tt = p * p,
                      ttt = tt * p,
                      u = 1 - p,
                      uu = u * u,
                      uuu = uu * u;
                  var ut = u * p,
                      ut3 = ut * 3,
                      uut3 = u * ut3,
                      utt3 = ut3 * p;
                  var x = x1 * uuu + cx1 * uut3 + cx2 * utt3 + x2 * ttt,
                      y = y1 * uuu + cy1 * uut3 + cy2 * utt3 + y2 * ttt;
                  out[o] = x;
                  out[o + 1] = y;

                  if (tangents) {
                    if (p < 0.001) out[o + 2] = Math.atan2(cy1 - y1, cx1 - x1);else out[o + 2] = Math.atan2(y - (y1 * uu + cy1 * ut * 2 + cy2 * tt), x - (x1 * uu + cx1 * ut * 2 + cx2 * tt));
                  }
                };

                PathConstraint.NONE = -1;
                PathConstraint.BEFORE = -2;
                PathConstraint.AFTER = -3;
                PathConstraint.epsilon = 0.00001;
                return PathConstraint;
              }();

              spine.PathConstraint = PathConstraint;
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var PathConstraintData = function (_super) {
                __extends(PathConstraintData, _super);

                function PathConstraintData(name) {
                  var _this = _super.call(this, name, 0, false) || this;

                  _this.bones = new Array();
                  return _this;
                }

                return PathConstraintData;
              }(spine.ConstraintData);

              spine.PathConstraintData = PathConstraintData;
              var PositionMode;

              (function (PositionMode) {
                PositionMode[PositionMode["Fixed"] = 0] = "Fixed";
                PositionMode[PositionMode["Percent"] = 1] = "Percent";
              })(PositionMode = spine.PositionMode || (spine.PositionMode = {}));

              var SpacingMode;

              (function (SpacingMode) {
                SpacingMode[SpacingMode["Length"] = 0] = "Length";
                SpacingMode[SpacingMode["Fixed"] = 1] = "Fixed";
                SpacingMode[SpacingMode["Percent"] = 2] = "Percent";
              })(SpacingMode = spine.SpacingMode || (spine.SpacingMode = {}));

              var RotateMode;

              (function (RotateMode) {
                RotateMode[RotateMode["Tangent"] = 0] = "Tangent";
                RotateMode[RotateMode["Chain"] = 1] = "Chain";
                RotateMode[RotateMode["ChainScale"] = 2] = "ChainScale";
              })(RotateMode = spine.RotateMode || (spine.RotateMode = {}));
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var Assets = function () {
                function Assets(clientId) {
                  this.toLoad = new Array();
                  this.assets = {};
                  this.clientId = clientId;
                }

                Assets.prototype.loaded = function () {
                  var i = 0;

                  for (var v in this.assets) {
                    i++;
                  }

                  return i;
                };

                return Assets;
              }();

              var SharedAssetManager = function () {
                function SharedAssetManager(pathPrefix) {
                  if (pathPrefix === void 0) {
                    pathPrefix = "";
                  }

                  this.clientAssets = {};
                  this.queuedAssets = {};
                  this.rawAssets = {};
                  this.errors = {};
                  this.pathPrefix = pathPrefix;
                }

                SharedAssetManager.prototype.queueAsset = function (clientId, textureLoader, path) {
                  var clientAssets = this.clientAssets[clientId];

                  if (clientAssets === null || clientAssets === undefined) {
                    clientAssets = new Assets(clientId);
                    this.clientAssets[clientId] = clientAssets;
                  }

                  if (textureLoader !== null) clientAssets.textureLoader = textureLoader;
                  clientAssets.toLoad.push(path);

                  if (this.queuedAssets[path] === path) {
                    return false;
                  } else {
                    this.queuedAssets[path] = path;
                    return true;
                  }
                };

                SharedAssetManager.prototype.loadText = function (clientId, path) {
                  var _this = this;

                  path = this.pathPrefix + path;
                  if (!this.queueAsset(clientId, null, path)) return;
                  var request = new XMLHttpRequest();

                  request.onreadystatechange = function () {
                    if (request.readyState == XMLHttpRequest.DONE) {
                      if (request.status >= 200 && request.status < 300) {
                        _this.rawAssets[path] = request.responseText;
                      } else {
                        _this.errors[path] = "Couldn't load text " + path + ": status " + request.status + ", " + request.responseText;
                      }
                    }
                  };

                  request.open("GET", path, true);
                  request.send();
                };

                SharedAssetManager.prototype.loadJson = function (clientId, path) {
                  var _this = this;

                  path = this.pathPrefix + path;
                  if (!this.queueAsset(clientId, null, path)) return;
                  var request = new XMLHttpRequest();

                  request.onreadystatechange = function () {
                    if (request.readyState == XMLHttpRequest.DONE) {
                      if (request.status >= 200 && request.status < 300) {
                        _this.rawAssets[path] = JSON.parse(request.responseText);
                      } else {
                        _this.errors[path] = "Couldn't load text " + path + ": status " + request.status + ", " + request.responseText;
                      }
                    }
                  };

                  request.open("GET", path, true);
                  request.send();
                };

                SharedAssetManager.prototype.loadTexture = function (clientId, textureLoader, path) {
                  var _this = this;

                  path = this.pathPrefix + path;
                  if (!this.queueAsset(clientId, textureLoader, path)) return;
                  var img = new Image();
                  img.src = path;
                  img.crossOrigin = "anonymous";

                  img.onload = function (ev) {
                    _this.rawAssets[path] = img;
                  };

                  img.onerror = function (ev) {
                    _this.errors[path] = "Couldn't load image " + path;
                  };
                };

                SharedAssetManager.prototype.get = function (clientId, path) {
                  path = this.pathPrefix + path;
                  var clientAssets = this.clientAssets[clientId];
                  if (clientAssets === null || clientAssets === undefined) return true;
                  return clientAssets.assets[path];
                };

                SharedAssetManager.prototype.updateClientAssets = function (clientAssets) {
                  for (var i = 0; i < clientAssets.toLoad.length; i++) {
                    var path = clientAssets.toLoad[i];
                    var asset = clientAssets.assets[path];

                    if (asset === null || asset === undefined) {
                      var rawAsset = this.rawAssets[path];
                      if (rawAsset === null || rawAsset === undefined) continue;

                      if (rawAsset instanceof HTMLImageElement) {
                        clientAssets.assets[path] = clientAssets.textureLoader(rawAsset);
                      } else {
                        clientAssets.assets[path] = rawAsset;
                      }
                    }
                  }
                };

                SharedAssetManager.prototype.isLoadingComplete = function (clientId) {
                  var clientAssets = this.clientAssets[clientId];
                  if (clientAssets === null || clientAssets === undefined) return true;
                  this.updateClientAssets(clientAssets);
                  return clientAssets.toLoad.length == clientAssets.loaded();
                };

                SharedAssetManager.prototype.dispose = function () {};

                SharedAssetManager.prototype.hasErrors = function () {
                  return Object.keys(this.errors).length > 0;
                };

                SharedAssetManager.prototype.getErrors = function () {
                  return this.errors;
                };

                return SharedAssetManager;
              }();

              spine.SharedAssetManager = SharedAssetManager;
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var Skeleton = function () {
                function Skeleton(data) {
                  this._updateCache = new Array();
                  this.updateCacheReset = new Array();
                  this.time = 0;
                  this.scaleX = 1;
                  this.scaleY = 1;
                  this.x = 0;
                  this.y = 0;
                  if (data == null) throw new Error("data cannot be null.");
                  this.data = data;
                  this.bones = new Array();

                  for (var i = 0; i < data.bones.length; i++) {
                    var boneData = data.bones[i];
                    var bone = void 0;
                    if (boneData.parent == null) bone = new spine.Bone(boneData, this, null);else {
                      var parent_1 = this.bones[boneData.parent.index];
                      bone = new spine.Bone(boneData, this, parent_1);
                      parent_1.children.push(bone);
                    }
                    this.bones.push(bone);
                  }

                  this.slots = new Array();
                  this.drawOrder = new Array();

                  for (var i = 0; i < data.slots.length; i++) {
                    var slotData = data.slots[i];
                    var bone = this.bones[slotData.boneData.index];
                    var slot = new spine.Slot(slotData, bone);
                    this.slots.push(slot);
                    this.drawOrder.push(slot);
                  }

                  this.ikConstraints = new Array();

                  for (var i = 0; i < data.ikConstraints.length; i++) {
                    var ikConstraintData = data.ikConstraints[i];
                    this.ikConstraints.push(new spine.IkConstraint(ikConstraintData, this));
                  }

                  this.transformConstraints = new Array();

                  for (var i = 0; i < data.transformConstraints.length; i++) {
                    var transformConstraintData = data.transformConstraints[i];
                    this.transformConstraints.push(new spine.TransformConstraint(transformConstraintData, this));
                  }

                  this.pathConstraints = new Array();

                  for (var i = 0; i < data.pathConstraints.length; i++) {
                    var pathConstraintData = data.pathConstraints[i];
                    this.pathConstraints.push(new spine.PathConstraint(pathConstraintData, this));
                  }

                  this.color = new spine.Color(1, 1, 1, 1);
                  this.updateCache();
                }

                Skeleton.prototype.updateCache = function () {
                  var updateCache = this._updateCache;
                  updateCache.length = 0;
                  this.updateCacheReset.length = 0;
                  var bones = this.bones;

                  for (var i = 0, n = bones.length; i < n; i++) {
                    var bone = bones[i];
                    bone.sorted = bone.data.skinRequired;
                    bone.active = !bone.sorted;
                  }

                  if (this.skin != null) {
                    var skinBones = this.skin.bones;

                    for (var i = 0, n = this.skin.bones.length; i < n; i++) {
                      var bone = this.bones[skinBones[i].index];

                      do {
                        bone.sorted = false;
                        bone.active = true;
                        bone = bone.parent;
                      } while (bone != null);
                    }
                  }

                  var ikConstraints = this.ikConstraints;
                  var transformConstraints = this.transformConstraints;
                  var pathConstraints = this.pathConstraints;
                  var ikCount = ikConstraints.length,
                      transformCount = transformConstraints.length,
                      pathCount = pathConstraints.length;
                  var constraintCount = ikCount + transformCount + pathCount;

                  outer: for (var i = 0; i < constraintCount; i++) {
                    for (var ii = 0; ii < ikCount; ii++) {
                      var constraint = ikConstraints[ii];

                      if (constraint.data.order == i) {
                        this.sortIkConstraint(constraint);
                        continue outer;
                      }
                    }

                    for (var ii = 0; ii < transformCount; ii++) {
                      var constraint = transformConstraints[ii];

                      if (constraint.data.order == i) {
                        this.sortTransformConstraint(constraint);
                        continue outer;
                      }
                    }

                    for (var ii = 0; ii < pathCount; ii++) {
                      var constraint = pathConstraints[ii];

                      if (constraint.data.order == i) {
                        this.sortPathConstraint(constraint);
                        continue outer;
                      }
                    }
                  }

                  for (var i = 0, n = bones.length; i < n; i++) {
                    this.sortBone(bones[i]);
                  }
                };

                Skeleton.prototype.sortIkConstraint = function (constraint) {
                  constraint.active = constraint.target.isActive() && (!constraint.data.skinRequired || this.skin != null && spine.Utils.contains(this.skin.constraints, constraint.data, true));
                  if (!constraint.active) return;
                  var target = constraint.target;
                  this.sortBone(target);
                  var constrained = constraint.bones;
                  var parent = constrained[0];
                  this.sortBone(parent);

                  if (constrained.length > 1) {
                    var child = constrained[constrained.length - 1];
                    if (!(this._updateCache.indexOf(child) > -1)) this.updateCacheReset.push(child);
                  }

                  this._updateCache.push(constraint);

                  this.sortReset(parent.children);
                  constrained[constrained.length - 1].sorted = true;
                };

                Skeleton.prototype.sortPathConstraint = function (constraint) {
                  constraint.active = constraint.target.bone.isActive() && (!constraint.data.skinRequired || this.skin != null && spine.Utils.contains(this.skin.constraints, constraint.data, true));
                  if (!constraint.active) return;
                  var slot = constraint.target;
                  var slotIndex = slot.data.index;
                  var slotBone = slot.bone;
                  if (this.skin != null) this.sortPathConstraintAttachment(this.skin, slotIndex, slotBone);
                  if (this.data.defaultSkin != null && this.data.defaultSkin != this.skin) this.sortPathConstraintAttachment(this.data.defaultSkin, slotIndex, slotBone);

                  for (var i = 0, n = this.data.skins.length; i < n; i++) {
                    this.sortPathConstraintAttachment(this.data.skins[i], slotIndex, slotBone);
                  }

                  var attachment = slot.getAttachment();
                  if (attachment instanceof spine.PathAttachment) this.sortPathConstraintAttachmentWith(attachment, slotBone);
                  var constrained = constraint.bones;
                  var boneCount = constrained.length;

                  for (var i = 0; i < boneCount; i++) {
                    this.sortBone(constrained[i]);
                  }

                  this._updateCache.push(constraint);

                  for (var i = 0; i < boneCount; i++) {
                    this.sortReset(constrained[i].children);
                  }

                  for (var i = 0; i < boneCount; i++) {
                    constrained[i].sorted = true;
                  }
                };

                Skeleton.prototype.sortTransformConstraint = function (constraint) {
                  constraint.active = constraint.target.isActive() && (!constraint.data.skinRequired || this.skin != null && spine.Utils.contains(this.skin.constraints, constraint.data, true));
                  if (!constraint.active) return;
                  this.sortBone(constraint.target);
                  var constrained = constraint.bones;
                  var boneCount = constrained.length;

                  if (constraint.data.local) {
                    for (var i = 0; i < boneCount; i++) {
                      var child = constrained[i];
                      this.sortBone(child.parent);
                      if (!(this._updateCache.indexOf(child) > -1)) this.updateCacheReset.push(child);
                    }
                  } else {
                    for (var i = 0; i < boneCount; i++) {
                      this.sortBone(constrained[i]);
                    }
                  }

                  this._updateCache.push(constraint);

                  for (var ii = 0; ii < boneCount; ii++) {
                    this.sortReset(constrained[ii].children);
                  }

                  for (var ii = 0; ii < boneCount; ii++) {
                    constrained[ii].sorted = true;
                  }
                };

                Skeleton.prototype.sortPathConstraintAttachment = function (skin, slotIndex, slotBone) {
                  var attachments = skin.attachments[slotIndex];
                  if (!attachments) return;

                  for (var key in attachments) {
                    this.sortPathConstraintAttachmentWith(attachments[key], slotBone);
                  }
                };

                Skeleton.prototype.sortPathConstraintAttachmentWith = function (attachment, slotBone) {
                  if (!(attachment instanceof spine.PathAttachment)) return;
                  var pathBones = attachment.bones;
                  if (pathBones == null) this.sortBone(slotBone);else {
                    var bones = this.bones;
                    var i = 0;

                    while (i < pathBones.length) {
                      var boneCount = pathBones[i++];

                      for (var n = i + boneCount; i < n; i++) {
                        var boneIndex = pathBones[i];
                        this.sortBone(bones[boneIndex]);
                      }
                    }
                  }
                };

                Skeleton.prototype.sortBone = function (bone) {
                  if (bone.sorted) return;
                  var parent = bone.parent;
                  if (parent != null) this.sortBone(parent);
                  bone.sorted = true;

                  this._updateCache.push(bone);
                };

                Skeleton.prototype.sortReset = function (bones) {
                  for (var i = 0, n = bones.length; i < n; i++) {
                    var bone = bones[i];
                    if (!bone.active) continue;
                    if (bone.sorted) this.sortReset(bone.children);
                    bone.sorted = false;
                  }
                };

                Skeleton.prototype.updateWorldTransform = function () {
                  var updateCacheReset = this.updateCacheReset;

                  for (var i = 0, n = updateCacheReset.length; i < n; i++) {
                    var bone = updateCacheReset[i];
                    bone.ax = bone.x;
                    bone.ay = bone.y;
                    bone.arotation = bone.rotation;
                    bone.ascaleX = bone.scaleX;
                    bone.ascaleY = bone.scaleY;
                    bone.ashearX = bone.shearX;
                    bone.ashearY = bone.shearY;
                    bone.appliedValid = true;
                  }

                  var updateCache = this._updateCache;

                  for (var i = 0, n = updateCache.length; i < n; i++) {
                    updateCache[i].update();
                  }
                };

                Skeleton.prototype.setToSetupPose = function () {
                  this.setBonesToSetupPose();
                  this.setSlotsToSetupPose();
                };

                Skeleton.prototype.setBonesToSetupPose = function () {
                  var bones = this.bones;

                  for (var i = 0, n = bones.length; i < n; i++) {
                    bones[i].setToSetupPose();
                  }

                  var ikConstraints = this.ikConstraints;

                  for (var i = 0, n = ikConstraints.length; i < n; i++) {
                    var constraint = ikConstraints[i];
                    constraint.mix = constraint.data.mix;
                    constraint.softness = constraint.data.softness;
                    constraint.bendDirection = constraint.data.bendDirection;
                    constraint.compress = constraint.data.compress;
                    constraint.stretch = constraint.data.stretch;
                  }

                  var transformConstraints = this.transformConstraints;

                  for (var i = 0, n = transformConstraints.length; i < n; i++) {
                    var constraint = transformConstraints[i];
                    var data = constraint.data;
                    constraint.rotateMix = data.rotateMix;
                    constraint.translateMix = data.translateMix;
                    constraint.scaleMix = data.scaleMix;
                    constraint.shearMix = data.shearMix;
                  }

                  var pathConstraints = this.pathConstraints;

                  for (var i = 0, n = pathConstraints.length; i < n; i++) {
                    var constraint = pathConstraints[i];
                    var data = constraint.data;
                    constraint.position = data.position;
                    constraint.spacing = data.spacing;
                    constraint.rotateMix = data.rotateMix;
                    constraint.translateMix = data.translateMix;
                  }
                };

                Skeleton.prototype.setSlotsToSetupPose = function () {
                  var slots = this.slots;
                  spine.Utils.arrayCopy(slots, 0, this.drawOrder, 0, slots.length);

                  for (var i = 0, n = slots.length; i < n; i++) {
                    slots[i].setToSetupPose();
                  }
                };

                Skeleton.prototype.getRootBone = function () {
                  if (this.bones.length == 0) return null;
                  return this.bones[0];
                };

                Skeleton.prototype.findBone = function (boneName) {
                  if (boneName == null) throw new Error("boneName cannot be null.");
                  var bones = this.bones;

                  for (var i = 0, n = bones.length; i < n; i++) {
                    var bone = bones[i];
                    if (bone.data.name == boneName) return bone;
                  }

                  return null;
                };

                Skeleton.prototype.findBoneIndex = function (boneName) {
                  if (boneName == null) throw new Error("boneName cannot be null.");
                  var bones = this.bones;

                  for (var i = 0, n = bones.length; i < n; i++) {
                    if (bones[i].data.name == boneName) return i;
                  }

                  return -1;
                };

                Skeleton.prototype.findSlot = function (slotName) {
                  if (slotName == null) throw new Error("slotName cannot be null.");
                  var slots = this.slots;

                  for (var i = 0, n = slots.length; i < n; i++) {
                    var slot = slots[i];
                    if (slot.data.name == slotName) return slot;
                  }

                  return null;
                };

                Skeleton.prototype.findSlotIndex = function (slotName) {
                  if (slotName == null) throw new Error("slotName cannot be null.");
                  var slots = this.slots;

                  for (var i = 0, n = slots.length; i < n; i++) {
                    if (slots[i].data.name == slotName) return i;
                  }

                  return -1;
                };

                Skeleton.prototype.setSkinByName = function (skinName) {
                  var skin = this.data.findSkin(skinName);
                  if (skin == null) throw new Error("Skin not found: " + skinName);
                  this.setSkin(skin);
                };

                Skeleton.prototype.setSkin = function (newSkin) {
                  if (newSkin == this.skin) return;

                  if (newSkin != null) {
                    if (this.skin != null) newSkin.attachAll(this, this.skin);else {
                      var slots = this.slots;

                      for (var i = 0, n = slots.length; i < n; i++) {
                        var slot = slots[i];
                        var name_1 = slot.data.attachmentName;

                        if (name_1 != null) {
                          var attachment = newSkin.getAttachment(i, name_1);
                          if (attachment != null) slot.setAttachment(attachment);
                        }
                      }
                    }
                  }

                  this.skin = newSkin;
                  this.updateCache();
                };

                Skeleton.prototype.getAttachmentByName = function (slotName, attachmentName) {
                  return this.getAttachment(this.data.findSlotIndex(slotName), attachmentName);
                };

                Skeleton.prototype.getAttachment = function (slotIndex, attachmentName) {
                  if (attachmentName == null) throw new Error("attachmentName cannot be null.");

                  if (this.skin != null) {
                    var attachment = this.skin.getAttachment(slotIndex, attachmentName);
                    if (attachment != null) return attachment;
                  }

                  if (this.data.defaultSkin != null) return this.data.defaultSkin.getAttachment(slotIndex, attachmentName);
                  return null;
                };

                Skeleton.prototype.setAttachment = function (slotName, attachmentName) {
                  if (slotName == null) throw new Error("slotName cannot be null.");
                  var slots = this.slots;

                  for (var i = 0, n = slots.length; i < n; i++) {
                    var slot = slots[i];

                    if (slot.data.name == slotName) {
                      var attachment = null;

                      if (attachmentName != null) {
                        attachment = this.getAttachment(i, attachmentName);
                        if (attachment == null) throw new Error("Attachment not found: " + attachmentName + ", for slot: " + slotName);
                      }

                      slot.setAttachment(attachment);
                      return;
                    }
                  }

                  throw new Error("Slot not found: " + slotName);
                };

                Skeleton.prototype.findIkConstraint = function (constraintName) {
                  if (constraintName == null) throw new Error("constraintName cannot be null.");
                  var ikConstraints = this.ikConstraints;

                  for (var i = 0, n = ikConstraints.length; i < n; i++) {
                    var ikConstraint = ikConstraints[i];
                    if (ikConstraint.data.name == constraintName) return ikConstraint;
                  }

                  return null;
                };

                Skeleton.prototype.findTransformConstraint = function (constraintName) {
                  if (constraintName == null) throw new Error("constraintName cannot be null.");
                  var transformConstraints = this.transformConstraints;

                  for (var i = 0, n = transformConstraints.length; i < n; i++) {
                    var constraint = transformConstraints[i];
                    if (constraint.data.name == constraintName) return constraint;
                  }

                  return null;
                };

                Skeleton.prototype.findPathConstraint = function (constraintName) {
                  if (constraintName == null) throw new Error("constraintName cannot be null.");
                  var pathConstraints = this.pathConstraints;

                  for (var i = 0, n = pathConstraints.length; i < n; i++) {
                    var constraint = pathConstraints[i];
                    if (constraint.data.name == constraintName) return constraint;
                  }

                  return null;
                };

                Skeleton.prototype.getBounds = function (offset, size, temp) {
                  if (temp === void 0) {
                    temp = new Array(2);
                  }

                  if (offset == null) throw new Error("offset cannot be null.");
                  if (size == null) throw new Error("size cannot be null.");
                  var drawOrder = this.drawOrder;
                  var minX = Number.POSITIVE_INFINITY,
                      minY = Number.POSITIVE_INFINITY,
                      maxX = Number.NEGATIVE_INFINITY,
                      maxY = Number.NEGATIVE_INFINITY;

                  for (var i = 0, n = drawOrder.length; i < n; i++) {
                    var slot = drawOrder[i];
                    if (!slot.bone.active) continue;
                    var verticesLength = 0;
                    var vertices = null;
                    var attachment = slot.getAttachment();

                    if (attachment instanceof spine.RegionAttachment) {
                      verticesLength = 8;
                      vertices = spine.Utils.setArraySize(temp, verticesLength, 0);
                      attachment.computeWorldVertices(slot.bone, vertices, 0, 2);
                    } else if (attachment instanceof spine.MeshAttachment) {
                      var mesh = attachment;
                      verticesLength = mesh.worldVerticesLength;
                      vertices = spine.Utils.setArraySize(temp, verticesLength, 0);
                      mesh.computeWorldVertices(slot, 0, verticesLength, vertices, 0, 2);
                    }

                    if (vertices != null) {
                      for (var ii = 0, nn = vertices.length; ii < nn; ii += 2) {
                        var x = vertices[ii],
                            y = vertices[ii + 1];
                        minX = Math.min(minX, x);
                        minY = Math.min(minY, y);
                        maxX = Math.max(maxX, x);
                        maxY = Math.max(maxY, y);
                      }
                    }
                  }

                  offset.set(minX, minY);
                  size.set(maxX - minX, maxY - minY);
                };

                Skeleton.prototype.update = function (delta) {
                  this.time += delta;
                };

                return Skeleton;
              }();

              spine.Skeleton = Skeleton;
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var SkeletonBinary = function () {
                function SkeletonBinary(attachmentLoader) {
                  this.scale = 1;
                  this.linkedMeshes = new Array();
                  this.attachmentLoader = attachmentLoader;
                }

                SkeletonBinary.prototype.readSkeletonData = function (binary) {
                  var scale = this.scale;
                  var skeletonData = new spine.SkeletonData();
                  skeletonData.name = "";
                  var input = new BinaryInput(binary);
                  skeletonData.hash = input.readString();
                  skeletonData.version = input.readString();
                  skeletonData.x = input.readFloat();
                  skeletonData.y = input.readFloat();
                  skeletonData.width = input.readFloat();
                  skeletonData.height = input.readFloat();
                  var nonessential = input.readBoolean();

                  if (nonessential) {
                    skeletonData.fps = input.readFloat();
                    skeletonData.imagesPath = input.readString();
                    skeletonData.audioPath = input.readString();
                  }

                  var n = 0;
                  n = input.readInt(true);

                  for (var i = 0; i < n; i++) {
                    input.strings.push(input.readString());
                  }

                  n = input.readInt(true);

                  for (var i = 0; i < n; i++) {
                    var name_2 = input.readString();
                    var parent_2 = i == 0 ? null : skeletonData.bones[input.readInt(true)];
                    var data = new spine.BoneData(i, name_2, parent_2);
                    data.rotation = input.readFloat();
                    data.x = input.readFloat() * scale;
                    data.y = input.readFloat() * scale;
                    data.scaleX = input.readFloat();
                    data.scaleY = input.readFloat();
                    data.shearX = input.readFloat();
                    data.shearY = input.readFloat();
                    data.length = input.readFloat() * scale;
                    data.transformMode = SkeletonBinary.TransformModeValues[input.readInt(true)];
                    data.skinRequired = input.readBoolean();
                    if (nonessential) spine.Color.rgba8888ToColor(data.color, input.readInt32());
                    skeletonData.bones.push(data);
                  }

                  n = input.readInt(true);

                  for (var i = 0; i < n; i++) {
                    var slotName = input.readString();
                    var boneData = skeletonData.bones[input.readInt(true)];
                    var data = new spine.SlotData(i, slotName, boneData);
                    spine.Color.rgba8888ToColor(data.color, input.readInt32());
                    var darkColor = input.readInt32();
                    if (darkColor != -1) spine.Color.rgb888ToColor(data.darkColor = new spine.Color(), darkColor);
                    data.attachmentName = input.readStringRef();
                    data.blendMode = SkeletonBinary.BlendModeValues[input.readInt(true)];
                    skeletonData.slots.push(data);
                  }

                  n = input.readInt(true);

                  for (var i = 0, nn = void 0; i < n; i++) {
                    var data = new spine.IkConstraintData(input.readString());
                    data.order = input.readInt(true);
                    data.skinRequired = input.readBoolean();
                    nn = input.readInt(true);

                    for (var ii = 0; ii < nn; ii++) {
                      data.bones.push(skeletonData.bones[input.readInt(true)]);
                    }

                    data.target = skeletonData.bones[input.readInt(true)];
                    data.mix = input.readFloat();
                    data.softness = input.readFloat() * scale;
                    data.bendDirection = input.readByte();
                    data.compress = input.readBoolean();
                    data.stretch = input.readBoolean();
                    data.uniform = input.readBoolean();
                    skeletonData.ikConstraints.push(data);
                  }

                  n = input.readInt(true);

                  for (var i = 0, nn = void 0; i < n; i++) {
                    var data = new spine.TransformConstraintData(input.readString());
                    data.order = input.readInt(true);
                    data.skinRequired = input.readBoolean();
                    nn = input.readInt(true);

                    for (var ii = 0; ii < nn; ii++) {
                      data.bones.push(skeletonData.bones[input.readInt(true)]);
                    }

                    data.target = skeletonData.bones[input.readInt(true)];
                    data.local = input.readBoolean();
                    data.relative = input.readBoolean();
                    data.offsetRotation = input.readFloat();
                    data.offsetX = input.readFloat() * scale;
                    data.offsetY = input.readFloat() * scale;
                    data.offsetScaleX = input.readFloat();
                    data.offsetScaleY = input.readFloat();
                    data.offsetShearY = input.readFloat();
                    data.rotateMix = input.readFloat();
                    data.translateMix = input.readFloat();
                    data.scaleMix = input.readFloat();
                    data.shearMix = input.readFloat();
                    skeletonData.transformConstraints.push(data);
                  }

                  n = input.readInt(true);

                  for (var i = 0, nn = void 0; i < n; i++) {
                    var data = new spine.PathConstraintData(input.readString());
                    data.order = input.readInt(true);
                    data.skinRequired = input.readBoolean();
                    nn = input.readInt(true);

                    for (var ii = 0; ii < nn; ii++) {
                      data.bones.push(skeletonData.bones[input.readInt(true)]);
                    }

                    data.target = skeletonData.slots[input.readInt(true)];
                    data.positionMode = SkeletonBinary.PositionModeValues[input.readInt(true)];
                    data.spacingMode = SkeletonBinary.SpacingModeValues[input.readInt(true)];
                    data.rotateMode = SkeletonBinary.RotateModeValues[input.readInt(true)];
                    data.offsetRotation = input.readFloat();
                    data.position = input.readFloat();
                    if (data.positionMode == spine.PositionMode.Fixed) data.position *= scale;
                    data.spacing = input.readFloat();
                    if (data.spacingMode == spine.SpacingMode.Length || data.spacingMode == spine.SpacingMode.Fixed) data.spacing *= scale;
                    data.rotateMix = input.readFloat();
                    data.translateMix = input.readFloat();
                    skeletonData.pathConstraints.push(data);
                  }

                  var defaultSkin = this.readSkin(input, skeletonData, true, nonessential);

                  if (defaultSkin != null) {
                    skeletonData.defaultSkin = defaultSkin;
                    skeletonData.skins.push(defaultSkin);
                  }

                  {
                    var i = skeletonData.skins.length;
                    spine.Utils.setArraySize(skeletonData.skins, n = i + input.readInt(true));

                    for (; i < n; i++) {
                      skeletonData.skins[i] = this.readSkin(input, skeletonData, false, nonessential);
                    }
                  }
                  n = this.linkedMeshes.length;

                  for (var i = 0; i < n; i++) {
                    var linkedMesh = this.linkedMeshes[i];
                    var skin = linkedMesh.skin == null ? skeletonData.defaultSkin : skeletonData.findSkin(linkedMesh.skin);
                    if (skin == null) throw new Error("Skin not found: " + linkedMesh.skin);
                    var parent_3 = skin.getAttachment(linkedMesh.slotIndex, linkedMesh.parent);
                    if (parent_3 == null) throw new Error("Parent mesh not found: " + linkedMesh.parent);
                    linkedMesh.mesh.deformAttachment = linkedMesh.inheritDeform ? parent_3 : linkedMesh.mesh;
                    linkedMesh.mesh.setParentMesh(parent_3);
                    linkedMesh.mesh.updateUVs();
                  }

                  this.linkedMeshes.length = 0;
                  n = input.readInt(true);

                  for (var i = 0; i < n; i++) {
                    var data = new spine.EventData(input.readStringRef());
                    data.intValue = input.readInt(false);
                    data.floatValue = input.readFloat();
                    data.stringValue = input.readString();
                    data.audioPath = input.readString();

                    if (data.audioPath != null) {
                      data.volume = input.readFloat();
                      data.balance = input.readFloat();
                    }

                    skeletonData.events.push(data);
                  }

                  n = input.readInt(true);

                  for (var i = 0; i < n; i++) {
                    skeletonData.animations.push(this.readAnimation(input, input.readString(), skeletonData));
                  }

                  return skeletonData;
                };

                SkeletonBinary.prototype.readSkin = function (input, skeletonData, defaultSkin, nonessential) {
                  var skin = null;
                  var slotCount = 0;

                  if (defaultSkin) {
                    slotCount = input.readInt(true);
                    if (slotCount == 0) return null;
                    skin = new spine.Skin("default");
                  } else {
                    skin = new spine.Skin(input.readStringRef());
                    skin.bones.length = input.readInt(true);

                    for (var i = 0, n = skin.bones.length; i < n; i++) {
                      skin.bones[i] = skeletonData.bones[input.readInt(true)];
                    }

                    for (var i = 0, n = input.readInt(true); i < n; i++) {
                      skin.constraints.push(skeletonData.ikConstraints[input.readInt(true)]);
                    }

                    for (var i = 0, n = input.readInt(true); i < n; i++) {
                      skin.constraints.push(skeletonData.transformConstraints[input.readInt(true)]);
                    }

                    for (var i = 0, n = input.readInt(true); i < n; i++) {
                      skin.constraints.push(skeletonData.pathConstraints[input.readInt(true)]);
                    }

                    slotCount = input.readInt(true);
                  }

                  for (var i = 0; i < slotCount; i++) {
                    var slotIndex = input.readInt(true);

                    for (var ii = 0, nn = input.readInt(true); ii < nn; ii++) {
                      var name_3 = input.readStringRef();
                      var attachment = this.readAttachment(input, skeletonData, skin, slotIndex, name_3, nonessential);
                      if (attachment != null) skin.setAttachment(slotIndex, name_3, attachment);
                    }
                  }

                  return skin;
                };

                SkeletonBinary.prototype.readAttachment = function (input, skeletonData, skin, slotIndex, attachmentName, nonessential) {
                  var scale = this.scale;
                  var name = input.readStringRef();
                  if (name == null) name = attachmentName;
                  var typeIndex = input.readByte();
                  var type = SkeletonBinary.AttachmentTypeValues[typeIndex];

                  switch (type) {
                    case spine.AttachmentType.Region:
                      {
                        var path = input.readStringRef();
                        var rotation = input.readFloat();
                        var x = input.readFloat();
                        var y = input.readFloat();
                        var scaleX = input.readFloat();
                        var scaleY = input.readFloat();
                        var width = input.readFloat();
                        var height = input.readFloat();
                        var color = input.readInt32();
                        if (path == null) path = name;
                        var region = this.attachmentLoader.newRegionAttachment(skin, name, path);
                        if (region == null) return null;
                        region.path = path;
                        region.x = x * scale;
                        region.y = y * scale;
                        region.scaleX = scaleX;
                        region.scaleY = scaleY;
                        region.rotation = rotation;
                        region.width = width * scale;
                        region.height = height * scale;
                        spine.Color.rgba8888ToColor(region.color, color);
                        region.updateOffset();
                        return region;
                      }

                    case spine.AttachmentType.BoundingBox:
                      {
                        var vertexCount = input.readInt(true);
                        var vertices = this.readVertices(input, vertexCount);
                        var color = nonessential ? input.readInt32() : 0;
                        var box = this.attachmentLoader.newBoundingBoxAttachment(skin, name);
                        if (box == null) return null;
                        box.worldVerticesLength = vertexCount << 1;
                        box.vertices = vertices.vertices;
                        box.bones = vertices.bones;
                        if (nonessential) spine.Color.rgba8888ToColor(box.color, color);
                        return box;
                      }

                    case spine.AttachmentType.Mesh:
                      {
                        var path = input.readStringRef();
                        var color = input.readInt32();
                        var vertexCount = input.readInt(true);
                        var uvs = this.readFloatArray(input, vertexCount << 1, 1);
                        var triangles = this.readShortArray(input);
                        var vertices = this.readVertices(input, vertexCount);
                        var hullLength = input.readInt(true);
                        var edges = null;
                        var width = 0,
                            height = 0;

                        if (nonessential) {
                          edges = this.readShortArray(input);
                          width = input.readFloat();
                          height = input.readFloat();
                        }

                        if (path == null) path = name;
                        var mesh = this.attachmentLoader.newMeshAttachment(skin, name, path);
                        if (mesh == null) return null;
                        mesh.path = path;
                        spine.Color.rgba8888ToColor(mesh.color, color);
                        mesh.bones = vertices.bones;
                        mesh.vertices = vertices.vertices;
                        mesh.worldVerticesLength = vertexCount << 1;
                        mesh.triangles = triangles;
                        mesh.regionUVs = uvs;
                        mesh.updateUVs();
                        mesh.hullLength = hullLength << 1;

                        if (nonessential) {
                          mesh.edges = edges;
                          mesh.width = width * scale;
                          mesh.height = height * scale;
                        }

                        return mesh;
                      }

                    case spine.AttachmentType.LinkedMesh:
                      {
                        var path = input.readStringRef();
                        var color = input.readInt32();
                        var skinName = input.readStringRef();
                        var parent_4 = input.readStringRef();
                        var inheritDeform = input.readBoolean();
                        var width = 0,
                            height = 0;

                        if (nonessential) {
                          width = input.readFloat();
                          height = input.readFloat();
                        }

                        if (path == null) path = name;
                        var mesh = this.attachmentLoader.newMeshAttachment(skin, name, path);
                        if (mesh == null) return null;
                        mesh.path = path;
                        spine.Color.rgba8888ToColor(mesh.color, color);

                        if (nonessential) {
                          mesh.width = width * scale;
                          mesh.height = height * scale;
                        }

                        this.linkedMeshes.push(new LinkedMesh(mesh, skinName, slotIndex, parent_4, inheritDeform));
                        return mesh;
                      }

                    case spine.AttachmentType.Path:
                      {
                        var closed_1 = input.readBoolean();
                        var constantSpeed = input.readBoolean();
                        var vertexCount = input.readInt(true);
                        var vertices = this.readVertices(input, vertexCount);
                        var lengths = spine.Utils.newArray(vertexCount / 3, 0);

                        for (var i = 0, n = lengths.length; i < n; i++) {
                          lengths[i] = input.readFloat() * scale;
                        }

                        var color = nonessential ? input.readInt32() : 0;
                        var path = this.attachmentLoader.newPathAttachment(skin, name);
                        if (path == null) return null;
                        path.closed = closed_1;
                        path.constantSpeed = constantSpeed;
                        path.worldVerticesLength = vertexCount << 1;
                        path.vertices = vertices.vertices;
                        path.bones = vertices.bones;
                        path.lengths = lengths;
                        if (nonessential) spine.Color.rgba8888ToColor(path.color, color);
                        return path;
                      }

                    case spine.AttachmentType.Point:
                      {
                        var rotation = input.readFloat();
                        var x = input.readFloat();
                        var y = input.readFloat();
                        var color = nonessential ? input.readInt32() : 0;
                        var point = this.attachmentLoader.newPointAttachment(skin, name);
                        if (point == null) return null;
                        point.x = x * scale;
                        point.y = y * scale;
                        point.rotation = rotation;
                        if (nonessential) spine.Color.rgba8888ToColor(point.color, color);
                        return point;
                      }

                    case spine.AttachmentType.Clipping:
                      {
                        var endSlotIndex = input.readInt(true);
                        var vertexCount = input.readInt(true);
                        var vertices = this.readVertices(input, vertexCount);
                        var color = nonessential ? input.readInt32() : 0;
                        var clip = this.attachmentLoader.newClippingAttachment(skin, name);
                        if (clip == null) return null;
                        clip.endSlot = skeletonData.slots[endSlotIndex];
                        clip.worldVerticesLength = vertexCount << 1;
                        clip.vertices = vertices.vertices;
                        clip.bones = vertices.bones;
                        if (nonessential) spine.Color.rgba8888ToColor(clip.color, color);
                        return clip;
                      }
                  }

                  return null;
                };

                SkeletonBinary.prototype.readVertices = function (input, vertexCount) {
                  var verticesLength = vertexCount << 1;
                  var vertices = new Vertices();
                  var scale = this.scale;

                  if (!input.readBoolean()) {
                    vertices.vertices = this.readFloatArray(input, verticesLength, scale);
                    return vertices;
                  }

                  var weights = new Array();
                  var bonesArray = new Array();

                  for (var i = 0; i < vertexCount; i++) {
                    var boneCount = input.readInt(true);
                    bonesArray.push(boneCount);

                    for (var ii = 0; ii < boneCount; ii++) {
                      bonesArray.push(input.readInt(true));
                      weights.push(input.readFloat() * scale);
                      weights.push(input.readFloat() * scale);
                      weights.push(input.readFloat());
                    }
                  }

                  vertices.vertices = spine.Utils.toFloatArray(weights);
                  vertices.bones = bonesArray;
                  return vertices;
                };

                SkeletonBinary.prototype.readFloatArray = function (input, n, scale) {
                  var array = new Array(n);

                  if (scale == 1) {
                    for (var i = 0; i < n; i++) {
                      array[i] = input.readFloat();
                    }
                  } else {
                    for (var i = 0; i < n; i++) {
                      array[i] = input.readFloat() * scale;
                    }
                  }

                  return array;
                };

                SkeletonBinary.prototype.readShortArray = function (input) {
                  var n = input.readInt(true);
                  var array = new Array(n);

                  for (var i = 0; i < n; i++) {
                    array[i] = input.readShort();
                  }

                  return array;
                };

                SkeletonBinary.prototype.readAnimation = function (input, name, skeletonData) {
                  var timelines = new Array();
                  var scale = this.scale;
                  var duration = 0;
                  var tempColor1 = new spine.Color();
                  var tempColor2 = new spine.Color();

                  for (var i = 0, n = input.readInt(true); i < n; i++) {
                    var slotIndex = input.readInt(true);

                    for (var ii = 0, nn = input.readInt(true); ii < nn; ii++) {
                      var timelineType = input.readByte();
                      var frameCount = input.readInt(true);

                      switch (timelineType) {
                        case SkeletonBinary.SLOT_ATTACHMENT:
                          {
                            var timeline = new spine.AttachmentTimeline(frameCount);
                            timeline.slotIndex = slotIndex;

                            for (var frameIndex = 0; frameIndex < frameCount; frameIndex++) {
                              timeline.setFrame(frameIndex, input.readFloat(), input.readStringRef());
                            }

                            timelines.push(timeline);
                            duration = Math.max(duration, timeline.frames[frameCount - 1]);
                            break;
                          }

                        case SkeletonBinary.SLOT_COLOR:
                          {
                            var timeline = new spine.ColorTimeline(frameCount);
                            timeline.slotIndex = slotIndex;

                            for (var frameIndex = 0; frameIndex < frameCount; frameIndex++) {
                              var time = input.readFloat();
                              spine.Color.rgba8888ToColor(tempColor1, input.readInt32());
                              timeline.setFrame(frameIndex, time, tempColor1.r, tempColor1.g, tempColor1.b, tempColor1.a);
                              if (frameIndex < frameCount - 1) this.readCurve(input, frameIndex, timeline);
                            }

                            timelines.push(timeline);
                            duration = Math.max(duration, timeline.frames[(frameCount - 1) * spine.ColorTimeline.ENTRIES]);
                            break;
                          }

                        case SkeletonBinary.SLOT_TWO_COLOR:
                          {
                            var timeline = new spine.TwoColorTimeline(frameCount);
                            timeline.slotIndex = slotIndex;

                            for (var frameIndex = 0; frameIndex < frameCount; frameIndex++) {
                              var time = input.readFloat();
                              spine.Color.rgba8888ToColor(tempColor1, input.readInt32());
                              spine.Color.rgb888ToColor(tempColor2, input.readInt32());
                              timeline.setFrame(frameIndex, time, tempColor1.r, tempColor1.g, tempColor1.b, tempColor1.a, tempColor2.r, tempColor2.g, tempColor2.b);
                              if (frameIndex < frameCount - 1) this.readCurve(input, frameIndex, timeline);
                            }

                            timelines.push(timeline);
                            duration = Math.max(duration, timeline.frames[(frameCount - 1) * spine.TwoColorTimeline.ENTRIES]);
                            break;
                          }
                      }
                    }
                  }

                  for (var i = 0, n = input.readInt(true); i < n; i++) {
                    var boneIndex = input.readInt(true);

                    for (var ii = 0, nn = input.readInt(true); ii < nn; ii++) {
                      var timelineType = input.readByte();
                      var frameCount = input.readInt(true);

                      switch (timelineType) {
                        case SkeletonBinary.BONE_ROTATE:
                          {
                            var timeline = new spine.RotateTimeline(frameCount);
                            timeline.boneIndex = boneIndex;

                            for (var frameIndex = 0; frameIndex < frameCount; frameIndex++) {
                              timeline.setFrame(frameIndex, input.readFloat(), input.readFloat());
                              if (frameIndex < frameCount - 1) this.readCurve(input, frameIndex, timeline);
                            }

                            timelines.push(timeline);
                            duration = Math.max(duration, timeline.frames[(frameCount - 1) * spine.RotateTimeline.ENTRIES]);
                            break;
                          }

                        case SkeletonBinary.BONE_TRANSLATE:
                        case SkeletonBinary.BONE_SCALE:
                        case SkeletonBinary.BONE_SHEAR:
                          {
                            var timeline = void 0;
                            var timelineScale = 1;
                            if (timelineType == SkeletonBinary.BONE_SCALE) timeline = new spine.ScaleTimeline(frameCount);else if (timelineType == SkeletonBinary.BONE_SHEAR) timeline = new spine.ShearTimeline(frameCount);else {
                              timeline = new spine.TranslateTimeline(frameCount);
                              timelineScale = scale;
                            }
                            timeline.boneIndex = boneIndex;

                            for (var frameIndex = 0; frameIndex < frameCount; frameIndex++) {
                              timeline.setFrame(frameIndex, input.readFloat(), input.readFloat() * timelineScale, input.readFloat() * timelineScale);
                              if (frameIndex < frameCount - 1) this.readCurve(input, frameIndex, timeline);
                            }

                            timelines.push(timeline);
                            duration = Math.max(duration, timeline.frames[(frameCount - 1) * spine.TranslateTimeline.ENTRIES]);
                            break;
                          }
                      }
                    }
                  }

                  for (var i = 0, n = input.readInt(true); i < n; i++) {
                    var index = input.readInt(true);
                    var frameCount = input.readInt(true);
                    var timeline = new spine.IkConstraintTimeline(frameCount);
                    timeline.ikConstraintIndex = index;

                    for (var frameIndex = 0; frameIndex < frameCount; frameIndex++) {
                      timeline.setFrame(frameIndex, input.readFloat(), input.readFloat(), input.readFloat() * scale, input.readByte(), input.readBoolean(), input.readBoolean());
                      if (frameIndex < frameCount - 1) this.readCurve(input, frameIndex, timeline);
                    }

                    timelines.push(timeline);
                    duration = Math.max(duration, timeline.frames[(frameCount - 1) * spine.IkConstraintTimeline.ENTRIES]);
                  }

                  for (var i = 0, n = input.readInt(true); i < n; i++) {
                    var index = input.readInt(true);
                    var frameCount = input.readInt(true);
                    var timeline = new spine.TransformConstraintTimeline(frameCount);
                    timeline.transformConstraintIndex = index;

                    for (var frameIndex = 0; frameIndex < frameCount; frameIndex++) {
                      timeline.setFrame(frameIndex, input.readFloat(), input.readFloat(), input.readFloat(), input.readFloat(), input.readFloat());
                      if (frameIndex < frameCount - 1) this.readCurve(input, frameIndex, timeline);
                    }

                    timelines.push(timeline);
                    duration = Math.max(duration, timeline.frames[(frameCount - 1) * spine.TransformConstraintTimeline.ENTRIES]);
                  }

                  for (var i = 0, n = input.readInt(true); i < n; i++) {
                    var index = input.readInt(true);
                    var data = skeletonData.pathConstraints[index];

                    for (var ii = 0, nn = input.readInt(true); ii < nn; ii++) {
                      var timelineType = input.readByte();
                      var frameCount = input.readInt(true);

                      switch (timelineType) {
                        case SkeletonBinary.PATH_POSITION:
                        case SkeletonBinary.PATH_SPACING:
                          {
                            var timeline = void 0;
                            var timelineScale = 1;

                            if (timelineType == SkeletonBinary.PATH_SPACING) {
                              timeline = new spine.PathConstraintSpacingTimeline(frameCount);
                              if (data.spacingMode == spine.SpacingMode.Length || data.spacingMode == spine.SpacingMode.Fixed) timelineScale = scale;
                            } else {
                              timeline = new spine.PathConstraintPositionTimeline(frameCount);
                              if (data.positionMode == spine.PositionMode.Fixed) timelineScale = scale;
                            }

                            timeline.pathConstraintIndex = index;

                            for (var frameIndex = 0; frameIndex < frameCount; frameIndex++) {
                              timeline.setFrame(frameIndex, input.readFloat(), input.readFloat() * timelineScale);
                              if (frameIndex < frameCount - 1) this.readCurve(input, frameIndex, timeline);
                            }

                            timelines.push(timeline);
                            duration = Math.max(duration, timeline.frames[(frameCount - 1) * spine.PathConstraintPositionTimeline.ENTRIES]);
                            break;
                          }

                        case SkeletonBinary.PATH_MIX:
                          {
                            var timeline = new spine.PathConstraintMixTimeline(frameCount);
                            timeline.pathConstraintIndex = index;

                            for (var frameIndex = 0; frameIndex < frameCount; frameIndex++) {
                              timeline.setFrame(frameIndex, input.readFloat(), input.readFloat(), input.readFloat());
                              if (frameIndex < frameCount - 1) this.readCurve(input, frameIndex, timeline);
                            }

                            timelines.push(timeline);
                            duration = Math.max(duration, timeline.frames[(frameCount - 1) * spine.PathConstraintMixTimeline.ENTRIES]);
                            break;
                          }
                      }
                    }
                  }

                  for (var i = 0, n = input.readInt(true); i < n; i++) {
                    var skin = skeletonData.skins[input.readInt(true)];

                    for (var ii = 0, nn = input.readInt(true); ii < nn; ii++) {
                      var slotIndex = input.readInt(true);

                      for (var iii = 0, nnn = input.readInt(true); iii < nnn; iii++) {
                        var attachment = skin.getAttachment(slotIndex, input.readStringRef());
                        var weighted = attachment.bones != null;
                        var vertices = attachment.vertices;
                        var deformLength = weighted ? vertices.length / 3 * 2 : vertices.length;
                        var frameCount = input.readInt(true);
                        var timeline = new spine.DeformTimeline(frameCount);
                        timeline.slotIndex = slotIndex;
                        timeline.attachment = attachment;

                        for (var frameIndex = 0; frameIndex < frameCount; frameIndex++) {
                          var time = input.readFloat();
                          var deform = void 0;
                          var end = input.readInt(true);
                          if (end == 0) deform = weighted ? spine.Utils.newFloatArray(deformLength) : vertices;else {
                            deform = spine.Utils.newFloatArray(deformLength);
                            var start = input.readInt(true);
                            end += start;

                            if (scale == 1) {
                              for (var v = start; v < end; v++) {
                                deform[v] = input.readFloat();
                              }
                            } else {
                              for (var v = start; v < end; v++) {
                                deform[v] = input.readFloat() * scale;
                              }
                            }

                            if (!weighted) {
                              for (var v = 0, vn = deform.length; v < vn; v++) {
                                deform[v] += vertices[v];
                              }
                            }
                          }
                          timeline.setFrame(frameIndex, time, deform);
                          if (frameIndex < frameCount - 1) this.readCurve(input, frameIndex, timeline);
                        }

                        timelines.push(timeline);
                        duration = Math.max(duration, timeline.frames[frameCount - 1]);
                      }
                    }
                  }

                  var drawOrderCount = input.readInt(true);

                  if (drawOrderCount > 0) {
                    var timeline = new spine.DrawOrderTimeline(drawOrderCount);
                    var slotCount = skeletonData.slots.length;

                    for (var i = 0; i < drawOrderCount; i++) {
                      var time = input.readFloat();
                      var offsetCount = input.readInt(true);
                      var drawOrder = spine.Utils.newArray(slotCount, 0);

                      for (var ii = slotCount - 1; ii >= 0; ii--) {
                        drawOrder[ii] = -1;
                      }

                      var unchanged = spine.Utils.newArray(slotCount - offsetCount, 0);
                      var originalIndex = 0,
                          unchangedIndex = 0;

                      for (var ii = 0; ii < offsetCount; ii++) {
                        var slotIndex = input.readInt(true);

                        while (originalIndex != slotIndex) {
                          unchanged[unchangedIndex++] = originalIndex++;
                        }

                        drawOrder[originalIndex + input.readInt(true)] = originalIndex++;
                      }

                      while (originalIndex < slotCount) {
                        unchanged[unchangedIndex++] = originalIndex++;
                      }

                      for (var ii = slotCount - 1; ii >= 0; ii--) {
                        if (drawOrder[ii] == -1) drawOrder[ii] = unchanged[--unchangedIndex];
                      }

                      timeline.setFrame(i, time, drawOrder);
                    }

                    timelines.push(timeline);
                    duration = Math.max(duration, timeline.frames[drawOrderCount - 1]);
                  }

                  var eventCount = input.readInt(true);

                  if (eventCount > 0) {
                    var timeline = new spine.EventTimeline(eventCount);

                    for (var i = 0; i < eventCount; i++) {
                      var time = input.readFloat();
                      var eventData = skeletonData.events[input.readInt(true)];
                      var event_4 = new spine.Event(time, eventData);
                      event_4.intValue = input.readInt(false);
                      event_4.floatValue = input.readFloat();
                      event_4.stringValue = input.readBoolean() ? input.readString() : eventData.stringValue;

                      if (event_4.data.audioPath != null) {
                        event_4.volume = input.readFloat();
                        event_4.balance = input.readFloat();
                      }

                      timeline.setFrame(i, event_4);
                    }

                    timelines.push(timeline);
                    duration = Math.max(duration, timeline.frames[eventCount - 1]);
                  }

                  return new spine.Animation(name, timelines, duration);
                };

                SkeletonBinary.prototype.readCurve = function (input, frameIndex, timeline) {
                  switch (input.readByte()) {
                    case SkeletonBinary.CURVE_STEPPED:
                      timeline.setStepped(frameIndex);
                      break;

                    case SkeletonBinary.CURVE_BEZIER:
                      this.setCurve(timeline, frameIndex, input.readFloat(), input.readFloat(), input.readFloat(), input.readFloat());
                      break;
                  }
                };

                SkeletonBinary.prototype.setCurve = function (timeline, frameIndex, cx1, cy1, cx2, cy2) {
                  timeline.setCurve(frameIndex, cx1, cy1, cx2, cy2);
                };

                SkeletonBinary.AttachmentTypeValues = [0, 1, 2, 3, 4, 5, 6];
                SkeletonBinary.TransformModeValues = [spine.TransformMode.Normal, spine.TransformMode.OnlyTranslation, spine.TransformMode.NoRotationOrReflection, spine.TransformMode.NoScale, spine.TransformMode.NoScaleOrReflection];
                SkeletonBinary.PositionModeValues = [spine.PositionMode.Fixed, spine.PositionMode.Percent];
                SkeletonBinary.SpacingModeValues = [spine.SpacingMode.Length, spine.SpacingMode.Fixed, spine.SpacingMode.Percent];
                SkeletonBinary.RotateModeValues = [spine.RotateMode.Tangent, spine.RotateMode.Chain, spine.RotateMode.ChainScale];
                SkeletonBinary.BlendModeValues = [spine.BlendMode.Normal, spine.BlendMode.Additive, spine.BlendMode.Multiply, spine.BlendMode.Screen];
                SkeletonBinary.BONE_ROTATE = 0;
                SkeletonBinary.BONE_TRANSLATE = 1;
                SkeletonBinary.BONE_SCALE = 2;
                SkeletonBinary.BONE_SHEAR = 3;
                SkeletonBinary.SLOT_ATTACHMENT = 0;
                SkeletonBinary.SLOT_COLOR = 1;
                SkeletonBinary.SLOT_TWO_COLOR = 2;
                SkeletonBinary.PATH_POSITION = 0;
                SkeletonBinary.PATH_SPACING = 1;
                SkeletonBinary.PATH_MIX = 2;
                SkeletonBinary.CURVE_LINEAR = 0;
                SkeletonBinary.CURVE_STEPPED = 1;
                SkeletonBinary.CURVE_BEZIER = 2;
                return SkeletonBinary;
              }();

              spine.SkeletonBinary = SkeletonBinary;

              var BinaryInput = function () {
                function BinaryInput(data, strings, index, buffer) {
                  if (strings === void 0) {
                    strings = new Array();
                  }

                  if (index === void 0) {
                    index = 0;
                  }

                  if (buffer === void 0) {
                    buffer = new DataView(data.buffer);
                  }

                  this.strings = strings;
                  this.index = index;
                  this.buffer = buffer;
                }

                BinaryInput.prototype.readByte = function () {
                  return this.buffer.getInt8(this.index++);
                };

                BinaryInput.prototype.readShort = function () {
                  var value = this.buffer.getInt16(this.index);
                  this.index += 2;
                  return value;
                };

                BinaryInput.prototype.readInt32 = function () {
                  var value = this.buffer.getInt32(this.index);
                  this.index += 4;
                  return value;
                };

                BinaryInput.prototype.readInt = function (optimizePositive) {
                  var b = this.readByte();
                  var result = b & 0x7F;

                  if ((b & 0x80) != 0) {
                    b = this.readByte();
                    result |= (b & 0x7F) << 7;

                    if ((b & 0x80) != 0) {
                      b = this.readByte();
                      result |= (b & 0x7F) << 14;

                      if ((b & 0x80) != 0) {
                        b = this.readByte();
                        result |= (b & 0x7F) << 21;

                        if ((b & 0x80) != 0) {
                          b = this.readByte();
                          result |= (b & 0x7F) << 28;
                        }
                      }
                    }
                  }

                  return optimizePositive ? result : result >>> 1 ^ -(result & 1);
                };

                BinaryInput.prototype.readStringRef = function () {
                  var index = this.readInt(true);
                  return index == 0 ? null : this.strings[index - 1];
                };

                BinaryInput.prototype.readString = function () {
                  var byteCount = this.readInt(true);

                  switch (byteCount) {
                    case 0:
                      return null;

                    case 1:
                      return "";
                  }

                  byteCount--;
                  var chars = "";

                  for (var i = 0; i < byteCount;) {
                    var b = this.readByte();

                    switch (b >> 4) {
                      case 12:
                      case 13:
                        chars += String.fromCharCode((b & 0x1F) << 6 | this.readByte() & 0x3F);
                        i += 2;
                        break;

                      case 14:
                        chars += String.fromCharCode((b & 0x0F) << 12 | (this.readByte() & 0x3F) << 6 | this.readByte() & 0x3F);
                        i += 3;
                        break;

                      default:
                        chars += String.fromCharCode(b);
                        i++;
                    }
                  }

                  return chars;
                };

                BinaryInput.prototype.readFloat = function () {
                  var value = this.buffer.getFloat32(this.index);
                  this.index += 4;
                  return value;
                };

                BinaryInput.prototype.readBoolean = function () {
                  return this.readByte() != 0;
                };

                return BinaryInput;
              }();

              var LinkedMesh = function () {
                function LinkedMesh(mesh, skin, slotIndex, parent, inheritDeform) {
                  this.mesh = mesh;
                  this.skin = skin;
                  this.slotIndex = slotIndex;
                  this.parent = parent;
                  this.inheritDeform = inheritDeform;
                }

                return LinkedMesh;
              }();

              var Vertices = function () {
                function Vertices(bones, vertices) {
                  if (bones === void 0) {
                    bones = null;
                  }

                  if (vertices === void 0) {
                    vertices = null;
                  }

                  this.bones = bones;
                  this.vertices = vertices;
                }

                return Vertices;
              }();
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var SkeletonBounds = function () {
                function SkeletonBounds() {
                  this.minX = 0;
                  this.minY = 0;
                  this.maxX = 0;
                  this.maxY = 0;
                  this.boundingBoxes = new Array();
                  this.polygons = new Array();
                  this.polygonPool = new spine.Pool(function () {
                    return spine.Utils.newFloatArray(16);
                  });
                }

                SkeletonBounds.prototype.update = function (skeleton, updateAabb) {
                  if (skeleton == null) throw new Error("skeleton cannot be null.");
                  var boundingBoxes = this.boundingBoxes;
                  var polygons = this.polygons;
                  var polygonPool = this.polygonPool;
                  var slots = skeleton.slots;
                  var slotCount = slots.length;
                  boundingBoxes.length = 0;
                  polygonPool.freeAll(polygons);
                  polygons.length = 0;

                  for (var i = 0; i < slotCount; i++) {
                    var slot = slots[i];
                    if (!slot.bone.active) continue;
                    var attachment = slot.getAttachment();

                    if (attachment instanceof spine.BoundingBoxAttachment) {
                      var boundingBox = attachment;
                      boundingBoxes.push(boundingBox);
                      var polygon = polygonPool.obtain();

                      if (polygon.length != boundingBox.worldVerticesLength) {
                        polygon = spine.Utils.newFloatArray(boundingBox.worldVerticesLength);
                      }

                      polygons.push(polygon);
                      boundingBox.computeWorldVertices(slot, 0, boundingBox.worldVerticesLength, polygon, 0, 2);
                    }
                  }

                  if (updateAabb) {
                    this.aabbCompute();
                  } else {
                    this.minX = Number.POSITIVE_INFINITY;
                    this.minY = Number.POSITIVE_INFINITY;
                    this.maxX = Number.NEGATIVE_INFINITY;
                    this.maxY = Number.NEGATIVE_INFINITY;
                  }
                };

                SkeletonBounds.prototype.aabbCompute = function () {
                  var minX = Number.POSITIVE_INFINITY,
                      minY = Number.POSITIVE_INFINITY,
                      maxX = Number.NEGATIVE_INFINITY,
                      maxY = Number.NEGATIVE_INFINITY;
                  var polygons = this.polygons;

                  for (var i = 0, n = polygons.length; i < n; i++) {
                    var polygon = polygons[i];
                    var vertices = polygon;

                    for (var ii = 0, nn = polygon.length; ii < nn; ii += 2) {
                      var x = vertices[ii];
                      var y = vertices[ii + 1];
                      minX = Math.min(minX, x);
                      minY = Math.min(minY, y);
                      maxX = Math.max(maxX, x);
                      maxY = Math.max(maxY, y);
                    }
                  }

                  this.minX = minX;
                  this.minY = minY;
                  this.maxX = maxX;
                  this.maxY = maxY;
                };

                SkeletonBounds.prototype.aabbContainsPoint = function (x, y) {
                  return x >= this.minX && x <= this.maxX && y >= this.minY && y <= this.maxY;
                };

                SkeletonBounds.prototype.aabbIntersectsSegment = function (x1, y1, x2, y2) {
                  var minX = this.minX;
                  var minY = this.minY;
                  var maxX = this.maxX;
                  var maxY = this.maxY;
                  if (x1 <= minX && x2 <= minX || y1 <= minY && y2 <= minY || x1 >= maxX && x2 >= maxX || y1 >= maxY && y2 >= maxY) return false;
                  var m = (y2 - y1) / (x2 - x1);
                  var y = m * (minX - x1) + y1;
                  if (y > minY && y < maxY) return true;
                  y = m * (maxX - x1) + y1;
                  if (y > minY && y < maxY) return true;
                  var x = (minY - y1) / m + x1;
                  if (x > minX && x < maxX) return true;
                  x = (maxY - y1) / m + x1;
                  if (x > minX && x < maxX) return true;
                  return false;
                };

                SkeletonBounds.prototype.aabbIntersectsSkeleton = function (bounds) {
                  return this.minX < bounds.maxX && this.maxX > bounds.minX && this.minY < bounds.maxY && this.maxY > bounds.minY;
                };

                SkeletonBounds.prototype.containsPoint = function (x, y) {
                  var polygons = this.polygons;

                  for (var i = 0, n = polygons.length; i < n; i++) {
                    if (this.containsPointPolygon(polygons[i], x, y)) return this.boundingBoxes[i];
                  }

                  return null;
                };

                SkeletonBounds.prototype.containsPointPolygon = function (polygon, x, y) {
                  var vertices = polygon;
                  var nn = polygon.length;
                  var prevIndex = nn - 2;
                  var inside = false;

                  for (var ii = 0; ii < nn; ii += 2) {
                    var vertexY = vertices[ii + 1];
                    var prevY = vertices[prevIndex + 1];

                    if (vertexY < y && prevY >= y || prevY < y && vertexY >= y) {
                      var vertexX = vertices[ii];
                      if (vertexX + (y - vertexY) / (prevY - vertexY) * (vertices[prevIndex] - vertexX) < x) inside = !inside;
                    }

                    prevIndex = ii;
                  }

                  return inside;
                };

                SkeletonBounds.prototype.intersectsSegment = function (x1, y1, x2, y2) {
                  var polygons = this.polygons;

                  for (var i = 0, n = polygons.length; i < n; i++) {
                    if (this.intersectsSegmentPolygon(polygons[i], x1, y1, x2, y2)) return this.boundingBoxes[i];
                  }

                  return null;
                };

                SkeletonBounds.prototype.intersectsSegmentPolygon = function (polygon, x1, y1, x2, y2) {
                  var vertices = polygon;
                  var nn = polygon.length;
                  var width12 = x1 - x2,
                      height12 = y1 - y2;
                  var det1 = x1 * y2 - y1 * x2;
                  var x3 = vertices[nn - 2],
                      y3 = vertices[nn - 1];

                  for (var ii = 0; ii < nn; ii += 2) {
                    var x4 = vertices[ii],
                        y4 = vertices[ii + 1];
                    var det2 = x3 * y4 - y3 * x4;
                    var width34 = x3 - x4,
                        height34 = y3 - y4;
                    var det3 = width12 * height34 - height12 * width34;
                    var x = (det1 * width34 - width12 * det2) / det3;

                    if ((x >= x3 && x <= x4 || x >= x4 && x <= x3) && (x >= x1 && x <= x2 || x >= x2 && x <= x1)) {
                      var y = (det1 * height34 - height12 * det2) / det3;
                      if ((y >= y3 && y <= y4 || y >= y4 && y <= y3) && (y >= y1 && y <= y2 || y >= y2 && y <= y1)) return true;
                    }

                    x3 = x4;
                    y3 = y4;
                  }

                  return false;
                };

                SkeletonBounds.prototype.getPolygon = function (boundingBox) {
                  if (boundingBox == null) throw new Error("boundingBox cannot be null.");
                  var index = this.boundingBoxes.indexOf(boundingBox);
                  return index == -1 ? null : this.polygons[index];
                };

                SkeletonBounds.prototype.getWidth = function () {
                  return this.maxX - this.minX;
                };

                SkeletonBounds.prototype.getHeight = function () {
                  return this.maxY - this.minY;
                };

                return SkeletonBounds;
              }();

              spine.SkeletonBounds = SkeletonBounds;
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var SkeletonClipping = function () {
                function SkeletonClipping() {
                  this.triangulator = new spine.Triangulator();
                  this.clippingPolygon = new Array();
                  this.clipOutput = new Array();
                  this.clippedVertices = new Array();
                  this.clippedTriangles = new Array();
                  this.scratch = new Array();
                }

                SkeletonClipping.prototype.clipStart = function (slot, clip) {
                  if (this.clipAttachment != null) return 0;
                  this.clipAttachment = clip;
                  var n = clip.worldVerticesLength;
                  var vertices = spine.Utils.setArraySize(this.clippingPolygon, n);
                  clip.computeWorldVertices(slot, 0, n, vertices, 0, 2);
                  var clippingPolygon = this.clippingPolygon;
                  SkeletonClipping.makeClockwise(clippingPolygon);
                  var clippingPolygons = this.clippingPolygons = this.triangulator.decompose(clippingPolygon, this.triangulator.triangulate(clippingPolygon));

                  for (var i = 0, n_1 = clippingPolygons.length; i < n_1; i++) {
                    var polygon = clippingPolygons[i];
                    SkeletonClipping.makeClockwise(polygon);
                    polygon.push(polygon[0]);
                    polygon.push(polygon[1]);
                  }

                  return clippingPolygons.length;
                };

                SkeletonClipping.prototype.clipEndWithSlot = function (slot) {
                  if (this.clipAttachment != null && this.clipAttachment.endSlot == slot.data) this.clipEnd();
                };

                SkeletonClipping.prototype.clipEnd = function () {
                  if (this.clipAttachment == null) return;
                  this.clipAttachment = null;
                  this.clippingPolygons = null;
                  this.clippedVertices.length = 0;
                  this.clippedTriangles.length = 0;
                  this.clippingPolygon.length = 0;
                };

                SkeletonClipping.prototype.isClipping = function () {
                  return this.clipAttachment != null;
                };

                SkeletonClipping.prototype.clipTriangles = function (vertices, verticesLength, triangles, trianglesLength, uvs, light, dark, twoColor, strideFloat, offsetV, offsetI) {
                  if (strideFloat === void 0) {
                    strideFloat = 2;
                  }

                  if (offsetV === void 0) {
                    offsetV = 0;
                  }

                  if (offsetI === void 0) {
                    offsetI = 0;
                  }

                  var clipOutput = this.clipOutput,
                      clippedVertices = this.clippedVertices;
                  var clippedTriangles = this.clippedTriangles;
                  var polygons = this.clippingPolygons;
                  var polygonsCount = this.clippingPolygons.length;
                  var vertexSize = twoColor ? 12 : 8;
                  var index = 0;
                  clippedVertices.length = 0;
                  clippedTriangles.length = 0;

                  outer: for (var i = 0; i < trianglesLength; i += 3) {
                    var vertexOffset = triangles[i] * strideFloat;
                    var x1 = vertices[vertexOffset + offsetV],
                        y1 = vertices[vertexOffset + offsetV + 1];
                    var u1 = uvs[vertexOffset + offsetI],
                        v1 = uvs[vertexOffset + offsetI + 1];
                    vertexOffset = triangles[i + 1] * strideFloat;
                    var x2 = vertices[vertexOffset + offsetV],
                        y2 = vertices[vertexOffset + offsetV + 1];
                    var u2 = uvs[vertexOffset + offsetI],
                        v2 = uvs[vertexOffset + offsetI + 1];
                    vertexOffset = triangles[i + 2] * strideFloat;
                    var x3 = vertices[vertexOffset + offsetV],
                        y3 = vertices[vertexOffset + offsetV + 1];
                    var u3 = uvs[vertexOffset + offsetI],
                        v3 = uvs[vertexOffset + offsetI + 1];

                    for (var p = 0; p < polygonsCount; p++) {
                      var s = clippedVertices.length;

                      if (this.clip(x1, y1, x2, y2, x3, y3, polygons[p], clipOutput)) {
                        var clipOutputLength = clipOutput.length;
                        if (clipOutputLength == 0) continue;
                        var d0 = y2 - y3,
                            d1 = x3 - x2,
                            d2 = x1 - x3,
                            d4 = y3 - y1;
                        var d = 1 / (d0 * d2 + d1 * (y1 - y3));
                        var clipOutputCount = clipOutputLength >> 1;
                        var clipOutputItems = this.clipOutput;
                        var clippedVerticesItems = spine.Utils.setArraySize(clippedVertices, s + clipOutputCount * vertexSize);

                        for (var ii = 0; ii < clipOutputLength; ii += 2) {
                          var x = clipOutputItems[ii],
                              y = clipOutputItems[ii + 1];
                          clippedVerticesItems[s] = x;
                          clippedVerticesItems[s + 1] = y;
                          clippedVerticesItems[s + 2] = light.r;
                          clippedVerticesItems[s + 3] = light.g;
                          clippedVerticesItems[s + 4] = light.b;
                          clippedVerticesItems[s + 5] = light.a;
                          var c0 = x - x3,
                              c1 = y - y3;
                          var a = (d0 * c0 + d1 * c1) * d;
                          var b = (d4 * c0 + d2 * c1) * d;
                          var c = 1 - a - b;
                          clippedVerticesItems[s + 6] = u1 * a + u2 * b + u3 * c;
                          clippedVerticesItems[s + 7] = v1 * a + v2 * b + v3 * c;

                          if (twoColor) {
                            clippedVerticesItems[s + 8] = dark.r;
                            clippedVerticesItems[s + 9] = dark.g;
                            clippedVerticesItems[s + 10] = dark.b;
                            clippedVerticesItems[s + 11] = dark.a;
                          }

                          s += vertexSize;
                        }

                        s = clippedTriangles.length;
                        var clippedTrianglesItems = spine.Utils.setArraySize(clippedTriangles, s + 3 * (clipOutputCount - 2));
                        clipOutputCount--;

                        for (var ii = 1; ii < clipOutputCount; ii++) {
                          clippedTrianglesItems[s] = index;
                          clippedTrianglesItems[s + 1] = index + ii;
                          clippedTrianglesItems[s + 2] = index + ii + 1;
                          s += 3;
                        }

                        index += clipOutputCount + 1;
                      } else {
                        var clippedVerticesItems = spine.Utils.setArraySize(clippedVertices, s + 3 * vertexSize);
                        clippedVerticesItems[s] = x1;
                        clippedVerticesItems[s + 1] = y1;
                        clippedVerticesItems[s + 2] = light.r;
                        clippedVerticesItems[s + 3] = light.g;
                        clippedVerticesItems[s + 4] = light.b;
                        clippedVerticesItems[s + 5] = light.a;

                        if (!twoColor) {
                          clippedVerticesItems[s + 6] = u1;
                          clippedVerticesItems[s + 7] = v1;
                          clippedVerticesItems[s + 8] = x2;
                          clippedVerticesItems[s + 9] = y2;
                          clippedVerticesItems[s + 10] = light.r;
                          clippedVerticesItems[s + 11] = light.g;
                          clippedVerticesItems[s + 12] = light.b;
                          clippedVerticesItems[s + 13] = light.a;
                          clippedVerticesItems[s + 14] = u2;
                          clippedVerticesItems[s + 15] = v2;
                          clippedVerticesItems[s + 16] = x3;
                          clippedVerticesItems[s + 17] = y3;
                          clippedVerticesItems[s + 18] = light.r;
                          clippedVerticesItems[s + 19] = light.g;
                          clippedVerticesItems[s + 20] = light.b;
                          clippedVerticesItems[s + 21] = light.a;
                          clippedVerticesItems[s + 22] = u3;
                          clippedVerticesItems[s + 23] = v3;
                        } else {
                          clippedVerticesItems[s + 6] = u1;
                          clippedVerticesItems[s + 7] = v1;
                          clippedVerticesItems[s + 8] = dark.r;
                          clippedVerticesItems[s + 9] = dark.g;
                          clippedVerticesItems[s + 10] = dark.b;
                          clippedVerticesItems[s + 11] = dark.a;
                          clippedVerticesItems[s + 12] = x2;
                          clippedVerticesItems[s + 13] = y2;
                          clippedVerticesItems[s + 14] = light.r;
                          clippedVerticesItems[s + 15] = light.g;
                          clippedVerticesItems[s + 16] = light.b;
                          clippedVerticesItems[s + 17] = light.a;
                          clippedVerticesItems[s + 18] = u2;
                          clippedVerticesItems[s + 19] = v2;
                          clippedVerticesItems[s + 20] = dark.r;
                          clippedVerticesItems[s + 21] = dark.g;
                          clippedVerticesItems[s + 22] = dark.b;
                          clippedVerticesItems[s + 23] = dark.a;
                          clippedVerticesItems[s + 24] = x3;
                          clippedVerticesItems[s + 25] = y3;
                          clippedVerticesItems[s + 26] = light.r;
                          clippedVerticesItems[s + 27] = light.g;
                          clippedVerticesItems[s + 28] = light.b;
                          clippedVerticesItems[s + 29] = light.a;
                          clippedVerticesItems[s + 30] = u3;
                          clippedVerticesItems[s + 31] = v3;
                          clippedVerticesItems[s + 32] = dark.r;
                          clippedVerticesItems[s + 33] = dark.g;
                          clippedVerticesItems[s + 34] = dark.b;
                          clippedVerticesItems[s + 35] = dark.a;
                        }

                        s = clippedTriangles.length;
                        var clippedTrianglesItems = spine.Utils.setArraySize(clippedTriangles, s + 3);
                        clippedTrianglesItems[s] = index;
                        clippedTrianglesItems[s + 1] = index + 1;
                        clippedTrianglesItems[s + 2] = index + 2;
                        index += 3;
                        continue outer;
                      }
                    }
                  }
                };

                SkeletonClipping.prototype.clip = function (x1, y1, x2, y2, x3, y3, clippingArea, output) {
                  var originalOutput = output;
                  var clipped = false;
                  var input = null;

                  if (clippingArea.length % 4 >= 2) {
                    input = output;
                    output = this.scratch;
                  } else input = this.scratch;

                  input.length = 0;
                  input.push(x1);
                  input.push(y1);
                  input.push(x2);
                  input.push(y2);
                  input.push(x3);
                  input.push(y3);
                  input.push(x1);
                  input.push(y1);
                  output.length = 0;
                  var clippingVertices = clippingArea;
                  var clippingVerticesLast = clippingArea.length - 4;

                  for (var i = 0;; i += 2) {
                    var edgeX = clippingVertices[i],
                        edgeY = clippingVertices[i + 1];
                    var edgeX2 = clippingVertices[i + 2],
                        edgeY2 = clippingVertices[i + 3];
                    var deltaX = edgeX - edgeX2,
                        deltaY = edgeY - edgeY2;
                    var inputVertices = input;
                    var inputVerticesLength = input.length - 2,
                        outputStart = output.length;

                    for (var ii = 0; ii < inputVerticesLength; ii += 2) {
                      var inputX = inputVertices[ii],
                          inputY = inputVertices[ii + 1];
                      var inputX2 = inputVertices[ii + 2],
                          inputY2 = inputVertices[ii + 3];
                      var side2 = deltaX * (inputY2 - edgeY2) - deltaY * (inputX2 - edgeX2) > 0;

                      if (deltaX * (inputY - edgeY2) - deltaY * (inputX - edgeX2) > 0) {
                        if (side2) {
                          output.push(inputX2);
                          output.push(inputY2);
                          continue;
                        }

                        var c0 = inputY2 - inputY,
                            c2 = inputX2 - inputX;
                        var s = c0 * (edgeX2 - edgeX) - c2 * (edgeY2 - edgeY);

                        if (Math.abs(s) > 0.000001) {
                          var ua = (c2 * (edgeY - inputY) - c0 * (edgeX - inputX)) / s;
                          output.push(edgeX + (edgeX2 - edgeX) * ua);
                          output.push(edgeY + (edgeY2 - edgeY) * ua);
                        } else {
                          output.push(edgeX);
                          output.push(edgeY);
                        }
                      } else if (side2) {
                        var c0 = inputY2 - inputY,
                            c2 = inputX2 - inputX;
                        var s = c0 * (edgeX2 - edgeX) - c2 * (edgeY2 - edgeY);

                        if (Math.abs(s) > 0.000001) {
                          var ua = (c2 * (edgeY - inputY) - c0 * (edgeX - inputX)) / s;
                          output.push(edgeX + (edgeX2 - edgeX) * ua);
                          output.push(edgeY + (edgeY2 - edgeY) * ua);
                        } else {
                          output.push(edgeX);
                          output.push(edgeY);
                        }

                        output.push(inputX2);
                        output.push(inputY2);
                      }

                      clipped = true;
                    }

                    if (outputStart == output.length) {
                      originalOutput.length = 0;
                      return true;
                    }

                    output.push(output[0]);
                    output.push(output[1]);
                    if (i == clippingVerticesLast) break;
                    var temp = output;
                    output = input;
                    output.length = 0;
                    input = temp;
                  }

                  if (originalOutput != output) {
                    originalOutput.length = 0;

                    for (var i = 0, n = output.length - 2; i < n; i++) {
                      originalOutput[i] = output[i];
                    }
                  } else originalOutput.length = originalOutput.length - 2;

                  return clipped;
                };

                SkeletonClipping.makeClockwise = function (polygon) {
                  var vertices = polygon;
                  var verticeslength = polygon.length;
                  var area = vertices[verticeslength - 2] * vertices[1] - vertices[0] * vertices[verticeslength - 1],
                      p1x = 0,
                      p1y = 0,
                      p2x = 0,
                      p2y = 0;

                  for (var i = 0, n = verticeslength - 3; i < n; i += 2) {
                    p1x = vertices[i];
                    p1y = vertices[i + 1];
                    p2x = vertices[i + 2];
                    p2y = vertices[i + 3];
                    area += p1x * p2y - p2x * p1y;
                  }

                  if (area < 0) return;

                  for (var i = 0, lastX = verticeslength - 2, n = verticeslength >> 1; i < n; i += 2) {
                    var x = vertices[i],
                        y = vertices[i + 1];
                    var other = lastX - i;
                    vertices[i] = vertices[other];
                    vertices[i + 1] = vertices[other + 1];
                    vertices[other] = x;
                    vertices[other + 1] = y;
                  }
                };

                return SkeletonClipping;
              }();

              spine.SkeletonClipping = SkeletonClipping;
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var SkeletonData = function () {
                function SkeletonData() {
                  this.bones = new Array();
                  this.slots = new Array();
                  this.skins = new Array();
                  this.events = new Array();
                  this.animations = new Array();
                  this.ikConstraints = new Array();
                  this.transformConstraints = new Array();
                  this.pathConstraints = new Array();
                  this.fps = 0;
                }

                SkeletonData.prototype.findBone = function (boneName) {
                  if (boneName == null) throw new Error("boneName cannot be null.");
                  var bones = this.bones;

                  for (var i = 0, n = bones.length; i < n; i++) {
                    var bone = bones[i];
                    if (bone.name == boneName) return bone;
                  }

                  return null;
                };

                SkeletonData.prototype.findBoneIndex = function (boneName) {
                  if (boneName == null) throw new Error("boneName cannot be null.");
                  var bones = this.bones;

                  for (var i = 0, n = bones.length; i < n; i++) {
                    if (bones[i].name == boneName) return i;
                  }

                  return -1;
                };

                SkeletonData.prototype.findSlot = function (slotName) {
                  if (slotName == null) throw new Error("slotName cannot be null.");
                  var slots = this.slots;

                  for (var i = 0, n = slots.length; i < n; i++) {
                    var slot = slots[i];
                    if (slot.name == slotName) return slot;
                  }

                  return null;
                };

                SkeletonData.prototype.findSlotIndex = function (slotName) {
                  if (slotName == null) throw new Error("slotName cannot be null.");
                  var slots = this.slots;

                  for (var i = 0, n = slots.length; i < n; i++) {
                    if (slots[i].name == slotName) return i;
                  }

                  return -1;
                };

                SkeletonData.prototype.findSkin = function (skinName) {
                  if (skinName == null) throw new Error("skinName cannot be null.");
                  var skins = this.skins;

                  for (var i = 0, n = skins.length; i < n; i++) {
                    var skin = skins[i];
                    if (skin.name == skinName) return skin;
                  }

                  return null;
                };

                SkeletonData.prototype.findEvent = function (eventDataName) {
                  if (eventDataName == null) throw new Error("eventDataName cannot be null.");
                  var events = this.events;

                  for (var i = 0, n = events.length; i < n; i++) {
                    var event_5 = events[i];
                    if (event_5.name == eventDataName) return event_5;
                  }

                  return null;
                };

                SkeletonData.prototype.findAnimation = function (animationName) {
                  if (animationName == null) throw new Error("animationName cannot be null.");
                  var animations = this.animations;

                  for (var i = 0, n = animations.length; i < n; i++) {
                    var animation = animations[i];
                    if (animation.name == animationName) return animation;
                  }

                  return null;
                };

                SkeletonData.prototype.findIkConstraint = function (constraintName) {
                  if (constraintName == null) throw new Error("constraintName cannot be null.");
                  var ikConstraints = this.ikConstraints;

                  for (var i = 0, n = ikConstraints.length; i < n; i++) {
                    var constraint = ikConstraints[i];
                    if (constraint.name == constraintName) return constraint;
                  }

                  return null;
                };

                SkeletonData.prototype.findTransformConstraint = function (constraintName) {
                  if (constraintName == null) throw new Error("constraintName cannot be null.");
                  var transformConstraints = this.transformConstraints;

                  for (var i = 0, n = transformConstraints.length; i < n; i++) {
                    var constraint = transformConstraints[i];
                    if (constraint.name == constraintName) return constraint;
                  }

                  return null;
                };

                SkeletonData.prototype.findPathConstraint = function (constraintName) {
                  if (constraintName == null) throw new Error("constraintName cannot be null.");
                  var pathConstraints = this.pathConstraints;

                  for (var i = 0, n = pathConstraints.length; i < n; i++) {
                    var constraint = pathConstraints[i];
                    if (constraint.name == constraintName) return constraint;
                  }

                  return null;
                };

                SkeletonData.prototype.findPathConstraintIndex = function (pathConstraintName) {
                  if (pathConstraintName == null) throw new Error("pathConstraintName cannot be null.");
                  var pathConstraints = this.pathConstraints;

                  for (var i = 0, n = pathConstraints.length; i < n; i++) {
                    if (pathConstraints[i].name == pathConstraintName) return i;
                  }

                  return -1;
                };

                return SkeletonData;
              }();

              spine.SkeletonData = SkeletonData;
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var SkeletonJson = function () {
                function SkeletonJson(attachmentLoader) {
                  this.scale = 1;
                  this.linkedMeshes = new Array();
                  this.attachmentLoader = attachmentLoader;
                }

                SkeletonJson.prototype.readSkeletonData = function (json) {
                  var scale = this.scale;
                  var skeletonData = new spine.SkeletonData();
                  var root = typeof json === "string" ? JSON.parse(json) : json;
                  var skeletonMap = root.skeleton;

                  if (skeletonMap != null) {
                    skeletonData.hash = skeletonMap.hash;
                    skeletonData.version = skeletonMap.spine;
                    skeletonData.x = skeletonMap.x;
                    skeletonData.y = skeletonMap.y;
                    skeletonData.width = skeletonMap.width;
                    skeletonData.height = skeletonMap.height;
                    skeletonData.fps = skeletonMap.fps;
                    skeletonData.imagesPath = skeletonMap.images;
                  }

                  if (root.bones) {
                    for (var i = 0; i < root.bones.length; i++) {
                      var boneMap = root.bones[i];
                      var parent_5 = null;
                      var parentName = this.getValue(boneMap, "parent", null);

                      if (parentName != null) {
                        parent_5 = skeletonData.findBone(parentName);
                        if (parent_5 == null) throw new Error("Parent bone not found: " + parentName);
                      }

                      var data = new spine.BoneData(skeletonData.bones.length, boneMap.name, parent_5);
                      data.length = this.getValue(boneMap, "length", 0) * scale;
                      data.x = this.getValue(boneMap, "x", 0) * scale;
                      data.y = this.getValue(boneMap, "y", 0) * scale;
                      data.rotation = this.getValue(boneMap, "rotation", 0);
                      data.scaleX = this.getValue(boneMap, "scaleX", 1);
                      data.scaleY = this.getValue(boneMap, "scaleY", 1);
                      data.shearX = this.getValue(boneMap, "shearX", 0);
                      data.shearY = this.getValue(boneMap, "shearY", 0);
                      data.transformMode = SkeletonJson.transformModeFromString(this.getValue(boneMap, "transform", "normal"));
                      data.skinRequired = this.getValue(boneMap, "skin", false);
                      skeletonData.bones.push(data);
                    }
                  }

                  if (root.slots) {
                    for (var i = 0; i < root.slots.length; i++) {
                      var slotMap = root.slots[i];
                      var slotName = slotMap.name;
                      var boneName = slotMap.bone;
                      var boneData = skeletonData.findBone(boneName);
                      if (boneData == null) throw new Error("Slot bone not found: " + boneName);
                      var data = new spine.SlotData(skeletonData.slots.length, slotName, boneData);
                      var color = this.getValue(slotMap, "color", null);
                      if (color != null) data.color.setFromString(color);
                      var dark = this.getValue(slotMap, "dark", null);

                      if (dark != null) {
                        data.darkColor = new spine.Color(1, 1, 1, 1);
                        data.darkColor.setFromString(dark);
                      }

                      data.attachmentName = this.getValue(slotMap, "attachment", null);
                      data.blendMode = SkeletonJson.blendModeFromString(this.getValue(slotMap, "blend", "normal"));
                      skeletonData.slots.push(data);
                    }
                  }

                  if (root.ik) {
                    for (var i = 0; i < root.ik.length; i++) {
                      var constraintMap = root.ik[i];
                      var data = new spine.IkConstraintData(constraintMap.name);
                      data.order = this.getValue(constraintMap, "order", 0);
                      data.skinRequired = this.getValue(constraintMap, "skin", false);

                      for (var j = 0; j < constraintMap.bones.length; j++) {
                        var boneName = constraintMap.bones[j];
                        var bone = skeletonData.findBone(boneName);
                        if (bone == null) throw new Error("IK bone not found: " + boneName);
                        data.bones.push(bone);
                      }

                      var targetName = constraintMap.target;
                      data.target = skeletonData.findBone(targetName);
                      if (data.target == null) throw new Error("IK target bone not found: " + targetName);
                      data.mix = this.getValue(constraintMap, "mix", 1);
                      data.softness = this.getValue(constraintMap, "softness", 0) * scale;
                      data.bendDirection = this.getValue(constraintMap, "bendPositive", true) ? 1 : -1;
                      data.compress = this.getValue(constraintMap, "compress", false);
                      data.stretch = this.getValue(constraintMap, "stretch", false);
                      data.uniform = this.getValue(constraintMap, "uniform", false);
                      skeletonData.ikConstraints.push(data);
                    }
                  }

                  if (root.transform) {
                    for (var i = 0; i < root.transform.length; i++) {
                      var constraintMap = root.transform[i];
                      var data = new spine.TransformConstraintData(constraintMap.name);
                      data.order = this.getValue(constraintMap, "order", 0);
                      data.skinRequired = this.getValue(constraintMap, "skin", false);

                      for (var j = 0; j < constraintMap.bones.length; j++) {
                        var boneName = constraintMap.bones[j];
                        var bone = skeletonData.findBone(boneName);
                        if (bone == null) throw new Error("Transform constraint bone not found: " + boneName);
                        data.bones.push(bone);
                      }

                      var targetName = constraintMap.target;
                      data.target = skeletonData.findBone(targetName);
                      if (data.target == null) throw new Error("Transform constraint target bone not found: " + targetName);
                      data.local = this.getValue(constraintMap, "local", false);
                      data.relative = this.getValue(constraintMap, "relative", false);
                      data.offsetRotation = this.getValue(constraintMap, "rotation", 0);
                      data.offsetX = this.getValue(constraintMap, "x", 0) * scale;
                      data.offsetY = this.getValue(constraintMap, "y", 0) * scale;
                      data.offsetScaleX = this.getValue(constraintMap, "scaleX", 0);
                      data.offsetScaleY = this.getValue(constraintMap, "scaleY", 0);
                      data.offsetShearY = this.getValue(constraintMap, "shearY", 0);
                      data.rotateMix = this.getValue(constraintMap, "rotateMix", 1);
                      data.translateMix = this.getValue(constraintMap, "translateMix", 1);
                      data.scaleMix = this.getValue(constraintMap, "scaleMix", 1);
                      data.shearMix = this.getValue(constraintMap, "shearMix", 1);
                      skeletonData.transformConstraints.push(data);
                    }
                  }

                  if (root.path) {
                    for (var i = 0; i < root.path.length; i++) {
                      var constraintMap = root.path[i];
                      var data = new spine.PathConstraintData(constraintMap.name);
                      data.order = this.getValue(constraintMap, "order", 0);
                      data.skinRequired = this.getValue(constraintMap, "skin", false);

                      for (var j = 0; j < constraintMap.bones.length; j++) {
                        var boneName = constraintMap.bones[j];
                        var bone = skeletonData.findBone(boneName);
                        if (bone == null) throw new Error("Transform constraint bone not found: " + boneName);
                        data.bones.push(bone);
                      }

                      var targetName = constraintMap.target;
                      data.target = skeletonData.findSlot(targetName);
                      if (data.target == null) throw new Error("Path target slot not found: " + targetName);
                      data.positionMode = SkeletonJson.positionModeFromString(this.getValue(constraintMap, "positionMode", "percent"));
                      data.spacingMode = SkeletonJson.spacingModeFromString(this.getValue(constraintMap, "spacingMode", "length"));
                      data.rotateMode = SkeletonJson.rotateModeFromString(this.getValue(constraintMap, "rotateMode", "tangent"));
                      data.offsetRotation = this.getValue(constraintMap, "rotation", 0);
                      data.position = this.getValue(constraintMap, "position", 0);
                      if (data.positionMode == spine.PositionMode.Fixed) data.position *= scale;
                      data.spacing = this.getValue(constraintMap, "spacing", 0);
                      if (data.spacingMode == spine.SpacingMode.Length || data.spacingMode == spine.SpacingMode.Fixed) data.spacing *= scale;
                      data.rotateMix = this.getValue(constraintMap, "rotateMix", 1);
                      data.translateMix = this.getValue(constraintMap, "translateMix", 1);
                      skeletonData.pathConstraints.push(data);
                    }
                  }

                  if (root.skins) {
                    var skins = root.skins;
                    var isArray = skins instanceof Array;

                    if (!isArray) {
                      var skinArr = [];

                      for (var skinName in skins) {
                        skinArr.push({
                          name: skinName,
                          attachments: skins[skinName]
                        });
                      }

                      skins = skinArr;
                    }

                    for (var i = 0; i < skins.length; i++) {
                      var skinMap = skins[i];
                      var skin = new spine.Skin(skinMap.name);

                      if (skinMap.bones) {
                        for (var ii = 0; ii < skinMap.bones.length; ii++) {
                          var bone = skeletonData.findBone(skinMap.bones[ii]);
                          if (bone == null) throw new Error("Skin bone not found: " + skinMap.bones[i]);
                          skin.bones.push(bone);
                        }
                      }

                      if (skinMap.ik) {
                        for (var ii = 0; ii < skinMap.ik.length; ii++) {
                          var constraint = skeletonData.findIkConstraint(skinMap.ik[ii]);
                          if (constraint == null) throw new Error("Skin IK constraint not found: " + skinMap.ik[i]);
                          skin.constraints.push(constraint);
                        }
                      }

                      if (skinMap.transform) {
                        for (var ii = 0; ii < skinMap.transform.length; ii++) {
                          var constraint = skeletonData.findTransformConstraint(skinMap.transform[ii]);
                          if (constraint == null) throw new Error("Skin transform constraint not found: " + skinMap.transform[i]);
                          skin.constraints.push(constraint);
                        }
                      }

                      if (skinMap.path) {
                        for (var ii = 0; ii < skinMap.path.length; ii++) {
                          var constraint = skeletonData.findPathConstraint(skinMap.path[ii]);
                          if (constraint == null) throw new Error("Skin path constraint not found: " + skinMap.path[i]);
                          skin.constraints.push(constraint);
                        }
                      }

                      for (var slotName in skinMap.attachments) {
                        var slot = skeletonData.findSlot(slotName);
                        if (slot == null) throw new Error("Slot not found: " + slotName);
                        var slotMap = skinMap.attachments[slotName];

                        for (var entryName in slotMap) {
                          var attachment = this.readAttachment(slotMap[entryName], skin, slot.index, entryName, skeletonData);
                          if (attachment != null) skin.setAttachment(slot.index, entryName, attachment);
                        }
                      }

                      skeletonData.skins.push(skin);
                      if (skin.name == "default") skeletonData.defaultSkin = skin;
                    }
                  }

                  for (var i = 0, n = this.linkedMeshes.length; i < n; i++) {
                    var linkedMesh = this.linkedMeshes[i];
                    var skin = linkedMesh.skin == null ? skeletonData.defaultSkin : skeletonData.findSkin(linkedMesh.skin);
                    if (skin == null) throw new Error("Skin not found: " + linkedMesh.skin);
                    var parent_6 = skin.getAttachment(linkedMesh.slotIndex, linkedMesh.parent);
                    if (parent_6 == null) throw new Error("Parent mesh not found: " + linkedMesh.parent);
                    linkedMesh.mesh.deformAttachment = linkedMesh.inheritDeform ? parent_6 : linkedMesh.mesh;
                    linkedMesh.mesh.setParentMesh(parent_6);
                    linkedMesh.mesh.updateUVs();
                  }

                  this.linkedMeshes.length = 0;

                  if (root.events) {
                    for (var eventName in root.events) {
                      var eventMap = root.events[eventName];
                      var data = new spine.EventData(eventName);
                      data.intValue = this.getValue(eventMap, "int", 0);
                      data.floatValue = this.getValue(eventMap, "float", 0);
                      data.stringValue = this.getValue(eventMap, "string", "");
                      data.audioPath = this.getValue(eventMap, "audio", null);

                      if (data.audioPath != null) {
                        data.volume = this.getValue(eventMap, "volume", 1);
                        data.balance = this.getValue(eventMap, "balance", 0);
                      }

                      skeletonData.events.push(data);
                    }
                  }

                  if (root.animations) {
                    for (var animationName in root.animations) {
                      var animationMap = root.animations[animationName];
                      this.readAnimation(animationMap, animationName, skeletonData);
                    }
                  }

                  return skeletonData;
                };

                SkeletonJson.prototype.readAttachment = function (map, skin, slotIndex, name, skeletonData) {
                  var scale = this.scale;
                  name = this.getValue(map, "name", name);
                  var type = this.getValue(map, "type", "region");

                  switch (type) {
                    case "region":
                      {
                        var path = this.getValue(map, "path", name);
                        var region = this.attachmentLoader.newRegionAttachment(skin, name, path);
                        if (region == null) return null;
                        region.path = path;
                        region.x = this.getValue(map, "x", 0) * scale;
                        region.y = this.getValue(map, "y", 0) * scale;
                        region.scaleX = this.getValue(map, "scaleX", 1);
                        region.scaleY = this.getValue(map, "scaleY", 1);
                        region.rotation = this.getValue(map, "rotation", 0);
                        region.width = map.width * scale;
                        region.height = map.height * scale;
                        var color = this.getValue(map, "color", null);
                        if (color != null) region.color.setFromString(color);
                        region.updateOffset();
                        return region;
                      }

                    case "boundingbox":
                      {
                        var box = this.attachmentLoader.newBoundingBoxAttachment(skin, name);
                        if (box == null) return null;
                        this.readVertices(map, box, map.vertexCount << 1);
                        var color = this.getValue(map, "color", null);
                        if (color != null) box.color.setFromString(color);
                        return box;
                      }

                    case "mesh":
                    case "linkedmesh":
                      {
                        var path = this.getValue(map, "path", name);
                        var mesh = this.attachmentLoader.newMeshAttachment(skin, name, path);
                        if (mesh == null) return null;
                        mesh.path = path;
                        var color = this.getValue(map, "color", null);
                        if (color != null) mesh.color.setFromString(color);
                        mesh.width = this.getValue(map, "width", 0) * scale;
                        mesh.height = this.getValue(map, "height", 0) * scale;
                        var parent_7 = this.getValue(map, "parent", null);

                        if (parent_7 != null) {
                          this.linkedMeshes.push(new LinkedMesh(mesh, this.getValue(map, "skin", null), slotIndex, parent_7, this.getValue(map, "deform", true)));
                          return mesh;
                        }

                        var uvs = map.uvs;
                        this.readVertices(map, mesh, uvs.length);
                        mesh.triangles = map.triangles;
                        mesh.regionUVs = uvs;
                        mesh.updateUVs();
                        mesh.edges = this.getValue(map, "edges", null);
                        mesh.hullLength = this.getValue(map, "hull", 0) * 2;
                        return mesh;
                      }

                    case "path":
                      {
                        var path = this.attachmentLoader.newPathAttachment(skin, name);
                        if (path == null) return null;
                        path.closed = this.getValue(map, "closed", false);
                        path.constantSpeed = this.getValue(map, "constantSpeed", true);
                        var vertexCount = map.vertexCount;
                        this.readVertices(map, path, vertexCount << 1);
                        var lengths = spine.Utils.newArray(vertexCount / 3, 0);

                        for (var i = 0; i < map.lengths.length; i++) {
                          lengths[i] = map.lengths[i] * scale;
                        }

                        path.lengths = lengths;
                        var color = this.getValue(map, "color", null);
                        if (color != null) path.color.setFromString(color);
                        return path;
                      }

                    case "point":
                      {
                        var point = this.attachmentLoader.newPointAttachment(skin, name);
                        if (point == null) return null;
                        point.x = this.getValue(map, "x", 0) * scale;
                        point.y = this.getValue(map, "y", 0) * scale;
                        point.rotation = this.getValue(map, "rotation", 0);
                        var color = this.getValue(map, "color", null);
                        if (color != null) point.color.setFromString(color);
                        return point;
                      }

                    case "clipping":
                      {
                        var clip = this.attachmentLoader.newClippingAttachment(skin, name);
                        if (clip == null) return null;
                        var end = this.getValue(map, "end", null);

                        if (end != null) {
                          var slot = skeletonData.findSlot(end);
                          if (slot == null) throw new Error("Clipping end slot not found: " + end);
                          clip.endSlot = slot;
                        }

                        var vertexCount = map.vertexCount;
                        this.readVertices(map, clip, vertexCount << 1);
                        var color = this.getValue(map, "color", null);
                        if (color != null) clip.color.setFromString(color);
                        return clip;
                      }
                  }

                  return null;
                };

                SkeletonJson.prototype.readVertices = function (map, attachment, verticesLength) {
                  var scale = this.scale;
                  attachment.worldVerticesLength = verticesLength;
                  var vertices = map.vertices;

                  if (verticesLength == vertices.length) {
                    var scaledVertices = spine.Utils.toFloatArray(vertices);

                    if (scale != 1) {
                      for (var i = 0, n = vertices.length; i < n; i++) {
                        scaledVertices[i] *= scale;
                      }
                    }

                    attachment.vertices = scaledVertices;
                    return;
                  }

                  var weights = new Array();
                  var bones = new Array();

                  for (var i = 0, n = vertices.length; i < n;) {
                    var boneCount = vertices[i++];
                    bones.push(boneCount);

                    for (var nn = i + boneCount * 4; i < nn; i += 4) {
                      bones.push(vertices[i]);
                      weights.push(vertices[i + 1] * scale);
                      weights.push(vertices[i + 2] * scale);
                      weights.push(vertices[i + 3]);
                    }
                  }

                  attachment.bones = bones;
                  attachment.vertices = spine.Utils.toFloatArray(weights);
                };

                SkeletonJson.prototype.readAnimation = function (map, name, skeletonData) {
                  var scale = this.scale;
                  var timelines = new Array();
                  var duration = 0;

                  if (map.slots) {
                    for (var slotName in map.slots) {
                      var slotMap = map.slots[slotName];
                      var slotIndex = skeletonData.findSlotIndex(slotName);
                      if (slotIndex == -1) throw new Error("Slot not found: " + slotName);

                      for (var timelineName in slotMap) {
                        var timelineMap = slotMap[timelineName];

                        if (timelineName == "attachment") {
                          var timeline = new spine.AttachmentTimeline(timelineMap.length);
                          timeline.slotIndex = slotIndex;
                          var frameIndex = 0;

                          for (var i = 0; i < timelineMap.length; i++) {
                            var valueMap = timelineMap[i];
                            timeline.setFrame(frameIndex++, this.getValue(valueMap, "time", 0), valueMap.name);
                          }

                          timelines.push(timeline);
                          duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]);
                        } else if (timelineName == "color") {
                          var timeline = new spine.ColorTimeline(timelineMap.length);
                          timeline.slotIndex = slotIndex;
                          var frameIndex = 0;

                          for (var i = 0; i < timelineMap.length; i++) {
                            var valueMap = timelineMap[i];
                            var color = new spine.Color();
                            color.setFromString(valueMap.color);
                            timeline.setFrame(frameIndex, this.getValue(valueMap, "time", 0), color.r, color.g, color.b, color.a);
                            this.readCurve(valueMap, timeline, frameIndex);
                            frameIndex++;
                          }

                          timelines.push(timeline);
                          duration = Math.max(duration, timeline.frames[(timeline.getFrameCount() - 1) * spine.ColorTimeline.ENTRIES]);
                        } else if (timelineName == "twoColor") {
                          var timeline = new spine.TwoColorTimeline(timelineMap.length);
                          timeline.slotIndex = slotIndex;
                          var frameIndex = 0;

                          for (var i = 0; i < timelineMap.length; i++) {
                            var valueMap = timelineMap[i];
                            var light = new spine.Color();
                            var dark = new spine.Color();
                            light.setFromString(valueMap.light);
                            dark.setFromString(valueMap.dark);
                            timeline.setFrame(frameIndex, this.getValue(valueMap, "time", 0), light.r, light.g, light.b, light.a, dark.r, dark.g, dark.b);
                            this.readCurve(valueMap, timeline, frameIndex);
                            frameIndex++;
                          }

                          timelines.push(timeline);
                          duration = Math.max(duration, timeline.frames[(timeline.getFrameCount() - 1) * spine.TwoColorTimeline.ENTRIES]);
                        } else throw new Error("Invalid timeline type for a slot: " + timelineName + " (" + slotName + ")");
                      }
                    }
                  }

                  if (map.bones) {
                    for (var boneName in map.bones) {
                      var boneMap = map.bones[boneName];
                      var boneIndex = skeletonData.findBoneIndex(boneName);
                      if (boneIndex == -1) throw new Error("Bone not found: " + boneName);

                      for (var timelineName in boneMap) {
                        var timelineMap = boneMap[timelineName];

                        if (timelineName === "rotate") {
                          var timeline = new spine.RotateTimeline(timelineMap.length);
                          timeline.boneIndex = boneIndex;
                          var frameIndex = 0;

                          for (var i = 0; i < timelineMap.length; i++) {
                            var valueMap = timelineMap[i];
                            timeline.setFrame(frameIndex, this.getValue(valueMap, "time", 0), this.getValue(valueMap, "angle", 0));
                            this.readCurve(valueMap, timeline, frameIndex);
                            frameIndex++;
                          }

                          timelines.push(timeline);
                          duration = Math.max(duration, timeline.frames[(timeline.getFrameCount() - 1) * spine.RotateTimeline.ENTRIES]);
                        } else if (timelineName === "translate" || timelineName === "scale" || timelineName === "shear") {
                          var timeline = null;
                          var timelineScale = 1,
                              defaultValue = 0;

                          if (timelineName === "scale") {
                            timeline = new spine.ScaleTimeline(timelineMap.length);
                            defaultValue = 1;
                          } else if (timelineName === "shear") timeline = new spine.ShearTimeline(timelineMap.length);else {
                            timeline = new spine.TranslateTimeline(timelineMap.length);
                            timelineScale = scale;
                          }

                          timeline.boneIndex = boneIndex;
                          var frameIndex = 0;

                          for (var i = 0; i < timelineMap.length; i++) {
                            var valueMap = timelineMap[i];
                            var x = this.getValue(valueMap, "x", defaultValue),
                                y = this.getValue(valueMap, "y", defaultValue);
                            timeline.setFrame(frameIndex, this.getValue(valueMap, "time", 0), x * timelineScale, y * timelineScale);
                            this.readCurve(valueMap, timeline, frameIndex);
                            frameIndex++;
                          }

                          timelines.push(timeline);
                          duration = Math.max(duration, timeline.frames[(timeline.getFrameCount() - 1) * spine.TranslateTimeline.ENTRIES]);
                        } else throw new Error("Invalid timeline type for a bone: " + timelineName + " (" + boneName + ")");
                      }
                    }
                  }

                  if (map.ik) {
                    for (var constraintName in map.ik) {
                      var constraintMap = map.ik[constraintName];
                      var constraint = skeletonData.findIkConstraint(constraintName);
                      var timeline = new spine.IkConstraintTimeline(constraintMap.length);
                      timeline.ikConstraintIndex = skeletonData.ikConstraints.indexOf(constraint);
                      var frameIndex = 0;

                      for (var i = 0; i < constraintMap.length; i++) {
                        var valueMap = constraintMap[i];
                        timeline.setFrame(frameIndex, this.getValue(valueMap, "time", 0), this.getValue(valueMap, "mix", 1), this.getValue(valueMap, "softness", 0) * scale, this.getValue(valueMap, "bendPositive", true) ? 1 : -1, this.getValue(valueMap, "compress", false), this.getValue(valueMap, "stretch", false));
                        this.readCurve(valueMap, timeline, frameIndex);
                        frameIndex++;
                      }

                      timelines.push(timeline);
                      duration = Math.max(duration, timeline.frames[(timeline.getFrameCount() - 1) * spine.IkConstraintTimeline.ENTRIES]);
                    }
                  }

                  if (map.transform) {
                    for (var constraintName in map.transform) {
                      var constraintMap = map.transform[constraintName];
                      var constraint = skeletonData.findTransformConstraint(constraintName);
                      var timeline = new spine.TransformConstraintTimeline(constraintMap.length);
                      timeline.transformConstraintIndex = skeletonData.transformConstraints.indexOf(constraint);
                      var frameIndex = 0;

                      for (var i = 0; i < constraintMap.length; i++) {
                        var valueMap = constraintMap[i];
                        timeline.setFrame(frameIndex, this.getValue(valueMap, "time", 0), this.getValue(valueMap, "rotateMix", 1), this.getValue(valueMap, "translateMix", 1), this.getValue(valueMap, "scaleMix", 1), this.getValue(valueMap, "shearMix", 1));
                        this.readCurve(valueMap, timeline, frameIndex);
                        frameIndex++;
                      }

                      timelines.push(timeline);
                      duration = Math.max(duration, timeline.frames[(timeline.getFrameCount() - 1) * spine.TransformConstraintTimeline.ENTRIES]);
                    }
                  }

                  var mapPath = map.path || map.paths;

                  if (mapPath) {
                    for (var constraintName in mapPath) {
                      var constraintMap = mapPath[constraintName];
                      var index = skeletonData.findPathConstraintIndex(constraintName);
                      if (index == -1) throw new Error("Path constraint not found: " + constraintName);
                      var data = skeletonData.pathConstraints[index];

                      for (var timelineName in constraintMap) {
                        var timelineMap = constraintMap[timelineName];

                        if (timelineName === "position" || timelineName === "spacing") {
                          var timeline = null;
                          var timelineScale = 1;

                          if (timelineName === "spacing") {
                            timeline = new spine.PathConstraintSpacingTimeline(timelineMap.length);
                            if (data.spacingMode == spine.SpacingMode.Length || data.spacingMode == spine.SpacingMode.Fixed) timelineScale = scale;
                          } else {
                            timeline = new spine.PathConstraintPositionTimeline(timelineMap.length);
                            if (data.positionMode == spine.PositionMode.Fixed) timelineScale = scale;
                          }

                          timeline.pathConstraintIndex = index;
                          var frameIndex = 0;

                          for (var i = 0; i < timelineMap.length; i++) {
                            var valueMap = timelineMap[i];
                            timeline.setFrame(frameIndex, this.getValue(valueMap, "time", 0), this.getValue(valueMap, timelineName, 0) * timelineScale);
                            this.readCurve(valueMap, timeline, frameIndex);
                            frameIndex++;
                          }

                          timelines.push(timeline);
                          duration = Math.max(duration, timeline.frames[(timeline.getFrameCount() - 1) * spine.PathConstraintPositionTimeline.ENTRIES]);
                        } else if (timelineName === "mix") {
                          var timeline = new spine.PathConstraintMixTimeline(timelineMap.length);
                          timeline.pathConstraintIndex = index;
                          var frameIndex = 0;

                          for (var i = 0; i < timelineMap.length; i++) {
                            var valueMap = timelineMap[i];
                            timeline.setFrame(frameIndex, this.getValue(valueMap, "time", 0), this.getValue(valueMap, "rotateMix", 1), this.getValue(valueMap, "translateMix", 1));
                            this.readCurve(valueMap, timeline, frameIndex);
                            frameIndex++;
                          }

                          timelines.push(timeline);
                          duration = Math.max(duration, timeline.frames[(timeline.getFrameCount() - 1) * spine.PathConstraintMixTimeline.ENTRIES]);
                        }
                      }
                    }
                  }

                  if (map.deform) {
                    for (var deformName in map.deform) {
                      var deformMap = map.deform[deformName];
                      var skin = skeletonData.findSkin(deformName);
                      if (skin == null) throw new Error("Skin not found: " + deformName);

                      for (var slotName in deformMap) {
                        var slotMap = deformMap[slotName];
                        var slotIndex = skeletonData.findSlotIndex(slotName);
                        if (slotIndex == -1) throw new Error("Slot not found: " + slotMap.name);

                        for (var timelineName in slotMap) {
                          var timelineMap = slotMap[timelineName];
                          var attachment = skin.getAttachment(slotIndex, timelineName);

                          if (attachment == null) {
                            continue;
                          }

                          var weighted = attachment.bones != null;
                          var vertices = attachment.vertices;
                          var deformLength = weighted ? vertices.length / 3 * 2 : vertices.length;
                          var timeline = new spine.DeformTimeline(timelineMap.length);
                          timeline.slotIndex = slotIndex;
                          timeline.attachment = attachment;
                          var frameIndex = 0;

                          for (var j = 0; j < timelineMap.length; j++) {
                            var valueMap = timelineMap[j];
                            var deform = void 0;
                            var verticesValue = this.getValue(valueMap, "vertices", null);
                            if (verticesValue == null) deform = weighted ? spine.Utils.newFloatArray(deformLength) : vertices;else {
                              deform = spine.Utils.newFloatArray(deformLength);
                              var start = this.getValue(valueMap, "offset", 0);
                              spine.Utils.arrayCopy(verticesValue, 0, deform, start, verticesValue.length);

                              if (scale != 1) {
                                for (var i = start, n = i + verticesValue.length; i < n; i++) {
                                  deform[i] *= scale;
                                }
                              }

                              if (!weighted) {
                                for (var i = 0; i < deformLength; i++) {
                                  deform[i] += vertices[i];
                                }
                              }
                            }
                            timeline.setFrame(frameIndex, this.getValue(valueMap, "time", 0), deform);
                            this.readCurve(valueMap, timeline, frameIndex);
                            frameIndex++;
                          }

                          timelines.push(timeline);
                          duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]);
                        }
                      }
                    }
                  }

                  var drawOrderNode = map.drawOrder;
                  if (drawOrderNode == null) drawOrderNode = map.draworder;

                  if (drawOrderNode != null) {
                    var timeline = new spine.DrawOrderTimeline(drawOrderNode.length);
                    var slotCount = skeletonData.slots.length;
                    var frameIndex = 0;

                    for (var j = 0; j < drawOrderNode.length; j++) {
                      var drawOrderMap = drawOrderNode[j];
                      var drawOrder = null;
                      var offsets = this.getValue(drawOrderMap, "offsets", null);

                      if (offsets != null) {
                        drawOrder = spine.Utils.newArray(slotCount, -1);
                        var unchanged = spine.Utils.newArray(slotCount - offsets.length, 0);
                        var originalIndex = 0,
                            unchangedIndex = 0;

                        for (var i = 0; i < offsets.length; i++) {
                          var offsetMap = offsets[i];
                          var slotIndex = skeletonData.findSlotIndex(offsetMap.slot);
                          if (slotIndex == -1) throw new Error("Slot not found: " + offsetMap.slot);

                          while (originalIndex != slotIndex) {
                            unchanged[unchangedIndex++] = originalIndex++;
                          }

                          drawOrder[originalIndex + offsetMap.offset] = originalIndex++;
                        }

                        while (originalIndex < slotCount) {
                          unchanged[unchangedIndex++] = originalIndex++;
                        }

                        for (var i = slotCount - 1; i >= 0; i--) {
                          if (drawOrder[i] == -1) drawOrder[i] = unchanged[--unchangedIndex];
                        }
                      }

                      timeline.setFrame(frameIndex++, this.getValue(drawOrderMap, "time", 0), drawOrder);
                    }

                    timelines.push(timeline);
                    duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]);
                  }

                  if (map.events) {
                    var timeline = new spine.EventTimeline(map.events.length);
                    var frameIndex = 0;

                    for (var i = 0; i < map.events.length; i++) {
                      var eventMap = map.events[i];
                      var eventData = skeletonData.findEvent(eventMap.name);
                      if (eventData == null) throw new Error("Event not found: " + eventMap.name);
                      var event_6 = new spine.Event(spine.Utils.toSinglePrecision(this.getValue(eventMap, "time", 0)), eventData);
                      event_6.intValue = this.getValue(eventMap, "int", eventData.intValue);
                      event_6.floatValue = this.getValue(eventMap, "float", eventData.floatValue);
                      event_6.stringValue = this.getValue(eventMap, "string", eventData.stringValue);

                      if (event_6.data.audioPath != null) {
                        event_6.volume = this.getValue(eventMap, "volume", 1);
                        event_6.balance = this.getValue(eventMap, "balance", 0);
                      }

                      timeline.setFrame(frameIndex++, event_6);
                    }

                    timelines.push(timeline);
                    duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]);
                  }

                  if (isNaN(duration)) {
                    throw new Error("Error while parsing animation, duration is NaN");
                  }

                  skeletonData.animations.push(new spine.Animation(name, timelines, duration));
                };

                SkeletonJson.prototype.readCurve = function (map, timeline, frameIndex) {
                  var curve = map.curve;
                  if (!curve) return;

                  if (curve == "stepped") {
                    timeline.setStepped(frameIndex);
                  } else if (Object.prototype.toString.call(curve) === '[object Array]') {
                    timeline.setCurve(frameIndex, curve[0], curve[1], curve[2], curve[3]);
                  } else {
                    timeline.setCurve(frameIndex, curve, this.getValue(map, "c2", 0), this.getValue(map, "c3", 1), this.getValue(map, "c4", 1));
                  }
                };

                SkeletonJson.prototype.getValue = function (map, prop, defaultValue) {
                  return map[prop] !== undefined ? map[prop] : defaultValue;
                };

                SkeletonJson.blendModeFromString = function (str) {
                  str = str.toLowerCase();
                  if (str == "normal") return spine.BlendMode.Normal;
                  if (str == "additive") return spine.BlendMode.Additive;
                  if (str == "multiply") return spine.BlendMode.Multiply;
                  if (str == "screen") return spine.BlendMode.Screen;
                  throw new Error("Unknown blend mode: " + str);
                };

                SkeletonJson.positionModeFromString = function (str) {
                  str = str.toLowerCase();
                  if (str == "fixed") return spine.PositionMode.Fixed;
                  if (str == "percent") return spine.PositionMode.Percent;
                  throw new Error("Unknown position mode: " + str);
                };

                SkeletonJson.spacingModeFromString = function (str) {
                  str = str.toLowerCase();
                  if (str == "length") return spine.SpacingMode.Length;
                  if (str == "fixed") return spine.SpacingMode.Fixed;
                  if (str == "percent") return spine.SpacingMode.Percent;
                  throw new Error("Unknown position mode: " + str);
                };

                SkeletonJson.rotateModeFromString = function (str) {
                  str = str.toLowerCase();
                  if (str == "tangent") return spine.RotateMode.Tangent;
                  if (str == "chain") return spine.RotateMode.Chain;
                  if (str == "chainscale") return spine.RotateMode.ChainScale;
                  throw new Error("Unknown rotate mode: " + str);
                };

                SkeletonJson.transformModeFromString = function (str) {
                  str = str.toLowerCase();
                  if (str == "normal") return spine.TransformMode.Normal;
                  if (str == "onlytranslation") return spine.TransformMode.OnlyTranslation;
                  if (str == "norotationorreflection") return spine.TransformMode.NoRotationOrReflection;
                  if (str == "noscale") return spine.TransformMode.NoScale;
                  if (str == "noscaleorreflection") return spine.TransformMode.NoScaleOrReflection;
                  throw new Error("Unknown transform mode: " + str);
                };

                return SkeletonJson;
              }();

              spine.SkeletonJson = SkeletonJson;

              var LinkedMesh = function () {
                function LinkedMesh(mesh, skin, slotIndex, parent, inheritDeform) {
                  this.mesh = mesh;
                  this.skin = skin;
                  this.slotIndex = slotIndex;
                  this.parent = parent;
                  this.inheritDeform = inheritDeform;
                }

                return LinkedMesh;
              }();
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var SkinEntry = function () {
                function SkinEntry(slotIndex, name, attachment) {
                  this.slotIndex = slotIndex;
                  this.name = name;
                  this.attachment = attachment;
                }

                return SkinEntry;
              }();

              spine.SkinEntry = SkinEntry;

              var Skin = function () {
                function Skin(name) {
                  this.attachments = new Array();
                  this.bones = Array();
                  this.constraints = new Array();
                  if (name == null) throw new Error("name cannot be null.");
                  this.name = name;
                }

                Skin.prototype.setAttachment = function (slotIndex, name, attachment) {
                  if (attachment == null) throw new Error("attachment cannot be null.");
                  var attachments = this.attachments;
                  if (slotIndex >= attachments.length) attachments.length = slotIndex + 1;
                  if (!attachments[slotIndex]) attachments[slotIndex] = {};
                  attachments[slotIndex][name] = attachment;
                };

                Skin.prototype.addSkin = function (skin) {
                  for (var i = 0; i < skin.bones.length; i++) {
                    var bone = skin.bones[i];
                    var contained = false;

                    for (var j = 0; j < this.bones.length; j++) {
                      if (this.bones[j] == bone) {
                        contained = true;
                        break;
                      }
                    }

                    if (!contained) this.bones.push(bone);
                  }

                  for (var i = 0; i < skin.constraints.length; i++) {
                    var constraint = skin.constraints[i];
                    var contained = false;

                    for (var j = 0; j < this.constraints.length; j++) {
                      if (this.constraints[j] == constraint) {
                        contained = true;
                        break;
                      }
                    }

                    if (!contained) this.constraints.push(constraint);
                  }

                  var attachments = skin.getAttachments();

                  for (var i = 0; i < attachments.length; i++) {
                    var attachment = attachments[i];
                    this.setAttachment(attachment.slotIndex, attachment.name, attachment.attachment);
                  }
                };

                Skin.prototype.copySkin = function (skin) {
                  for (var i = 0; i < skin.bones.length; i++) {
                    var bone = skin.bones[i];
                    var contained = false;

                    for (var j = 0; j < this.bones.length; j++) {
                      if (this.bones[j] == bone) {
                        contained = true;
                        break;
                      }
                    }

                    if (!contained) this.bones.push(bone);
                  }

                  for (var i = 0; i < skin.constraints.length; i++) {
                    var constraint = skin.constraints[i];
                    var contained = false;

                    for (var j = 0; j < this.constraints.length; j++) {
                      if (this.constraints[j] == constraint) {
                        contained = true;
                        break;
                      }
                    }

                    if (!contained) this.constraints.push(constraint);
                  }

                  var attachments = skin.getAttachments();

                  for (var i = 0; i < attachments.length; i++) {
                    var attachment = attachments[i];
                    if (attachment.attachment == null) continue;

                    if (attachment.attachment instanceof spine.MeshAttachment) {
                      attachment.attachment = attachment.attachment.newLinkedMesh();
                      this.setAttachment(attachment.slotIndex, attachment.name, attachment.attachment);
                    } else {
                      attachment.attachment = attachment.attachment.copy();
                      this.setAttachment(attachment.slotIndex, attachment.name, attachment.attachment);
                    }
                  }
                };

                Skin.prototype.getAttachment = function (slotIndex, name) {
                  var dictionary = this.attachments[slotIndex];
                  return dictionary ? dictionary[name] : null;
                };

                Skin.prototype.removeAttachment = function (slotIndex, name) {
                  var dictionary = this.attachments[slotIndex];
                  if (dictionary) dictionary[name] = null;
                };

                Skin.prototype.getAttachments = function () {
                  var entries = new Array();

                  for (var i = 0; i < this.attachments.length; i++) {
                    var slotAttachments = this.attachments[i];

                    if (slotAttachments) {
                      for (var name_4 in slotAttachments) {
                        var attachment = slotAttachments[name_4];
                        if (attachment) entries.push(new SkinEntry(i, name_4, attachment));
                      }
                    }
                  }

                  return entries;
                };

                Skin.prototype.getAttachmentsForSlot = function (slotIndex, attachments) {
                  var slotAttachments = this.attachments[slotIndex];

                  if (slotAttachments) {
                    for (var name_5 in slotAttachments) {
                      var attachment = slotAttachments[name_5];
                      if (attachment) attachments.push(new SkinEntry(slotIndex, name_5, attachment));
                    }
                  }
                };

                Skin.prototype.clear = function () {
                  this.attachments.length = 0;
                  this.bones.length = 0;
                  this.constraints.length = 0;
                };

                Skin.prototype.attachAll = function (skeleton, oldSkin) {
                  var slotIndex = 0;

                  for (var i = 0; i < skeleton.slots.length; i++) {
                    var slot = skeleton.slots[i];
                    var slotAttachment = slot.getAttachment();

                    if (slotAttachment && slotIndex < oldSkin.attachments.length) {
                      var dictionary = oldSkin.attachments[slotIndex];

                      for (var key in dictionary) {
                        var skinAttachment = dictionary[key];

                        if (slotAttachment == skinAttachment) {
                          var attachment = this.getAttachment(slotIndex, key);
                          if (attachment != null) slot.setAttachment(attachment);
                          break;
                        }
                      }
                    }

                    slotIndex++;
                  }
                };

                return Skin;
              }();

              spine.Skin = Skin;
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var Slot = function () {
                function Slot(data, bone) {
                  this.deform = new Array();
                  if (data == null) throw new Error("data cannot be null.");
                  if (bone == null) throw new Error("bone cannot be null.");
                  this.data = data;
                  this.bone = bone;
                  this.color = new spine.Color();
                  this.darkColor = data.darkColor == null ? null : new spine.Color();
                  this.setToSetupPose();
                }

                Slot.prototype.getSkeleton = function () {
                  return this.bone.skeleton;
                };

                Slot.prototype.getAttachment = function () {
                  return this.attachment;
                };

                Slot.prototype.setAttachment = function (attachment) {
                  if (this.attachment == attachment) return;
                  this.attachment = attachment;
                  this.attachmentTime = this.bone.skeleton.time;
                  this.deform.length = 0;
                };

                Slot.prototype.setAttachmentTime = function (time) {
                  this.attachmentTime = this.bone.skeleton.time - time;
                };

                Slot.prototype.getAttachmentTime = function () {
                  return this.bone.skeleton.time - this.attachmentTime;
                };

                Slot.prototype.setToSetupPose = function () {
                  this.color.setFromColor(this.data.color);
                  if (this.darkColor != null) this.darkColor.setFromColor(this.data.darkColor);
                  if (this.data.attachmentName == null) this.attachment = null;else {
                    this.attachment = null;
                    this.setAttachment(this.bone.skeleton.getAttachment(this.data.index, this.data.attachmentName));
                  }
                };

                return Slot;
              }();

              spine.Slot = Slot;
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var SlotData = function () {
                function SlotData(index, name, boneData) {
                  this.color = new spine.Color(1, 1, 1, 1);
                  if (index < 0) throw new Error("index must be >= 0.");
                  if (name == null) throw new Error("name cannot be null.");
                  if (boneData == null) throw new Error("boneData cannot be null.");
                  this.index = index;
                  this.name = name;
                  this.boneData = boneData;
                }

                return SlotData;
              }();

              spine.SlotData = SlotData;
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var Texture = function () {
                function Texture(image) {
                  this._image = image;
                }

                Texture.prototype.getImage = function () {
                  return this._image;
                };

                Texture.filterFromString = function (text) {
                  switch (text.toLowerCase()) {
                    case "nearest":
                      return TextureFilter.Nearest;

                    case "linear":
                      return TextureFilter.Linear;

                    case "mipmap":
                      return TextureFilter.MipMap;

                    case "mipmapnearestnearest":
                      return TextureFilter.MipMapNearestNearest;

                    case "mipmaplinearnearest":
                      return TextureFilter.MipMapLinearNearest;

                    case "mipmapnearestlinear":
                      return TextureFilter.MipMapNearestLinear;

                    case "mipmaplinearlinear":
                      return TextureFilter.MipMapLinearLinear;

                    default:
                      throw new Error("Unknown texture filter " + text);
                  }
                };

                Texture.wrapFromString = function (text) {
                  switch (text.toLowerCase()) {
                    case "mirroredtepeat":
                      return TextureWrap.MirroredRepeat;

                    case "clamptoedge":
                      return TextureWrap.ClampToEdge;

                    case "repeat":
                      return TextureWrap.Repeat;

                    default:
                      throw new Error("Unknown texture wrap " + text);
                  }
                };

                return Texture;
              }();

              spine.Texture = Texture;
              var TextureFilter;

              (function (TextureFilter) {
                TextureFilter[TextureFilter["Nearest"] = 9728] = "Nearest";
                TextureFilter[TextureFilter["Linear"] = 9729] = "Linear";
                TextureFilter[TextureFilter["MipMap"] = 9987] = "MipMap";
                TextureFilter[TextureFilter["MipMapNearestNearest"] = 9984] = "MipMapNearestNearest";
                TextureFilter[TextureFilter["MipMapLinearNearest"] = 9985] = "MipMapLinearNearest";
                TextureFilter[TextureFilter["MipMapNearestLinear"] = 9986] = "MipMapNearestLinear";
                TextureFilter[TextureFilter["MipMapLinearLinear"] = 9987] = "MipMapLinearLinear";
              })(TextureFilter = spine.TextureFilter || (spine.TextureFilter = {}));

              var TextureWrap;

              (function (TextureWrap) {
                TextureWrap[TextureWrap["MirroredRepeat"] = 33648] = "MirroredRepeat";
                TextureWrap[TextureWrap["ClampToEdge"] = 33071] = "ClampToEdge";
                TextureWrap[TextureWrap["Repeat"] = 10497] = "Repeat";
              })(TextureWrap = spine.TextureWrap || (spine.TextureWrap = {}));

              var TextureRegion = function () {
                function TextureRegion() {
                  this.u = 0;
                  this.v = 0;
                  this.u2 = 0;
                  this.v2 = 0;
                  this.width = 0;
                  this.height = 0;
                  this.rotate = false;
                  this.offsetX = 0;
                  this.offsetY = 0;
                  this.originalWidth = 0;
                  this.originalHeight = 0;
                }

                return TextureRegion;
              }();

              spine.TextureRegion = TextureRegion;

              var FakeTexture = function (_super) {
                __extends(FakeTexture, _super);

                function FakeTexture() {
                  return _super !== null && _super.apply(this, arguments) || this;
                }

                FakeTexture.prototype.setFilters = function (minFilter, magFilter) {};

                FakeTexture.prototype.setWraps = function (uWrap, vWrap) {};

                FakeTexture.prototype.dispose = function () {};

                return FakeTexture;
              }(Texture);

              spine.FakeTexture = FakeTexture;
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var TextureAtlas = function () {
                function TextureAtlas(atlasText, textureLoader) {
                  this.pages = new Array();
                  this.regions = new Array();
                  this.load(atlasText, textureLoader);
                }

                TextureAtlas.prototype.load = function (atlasText, textureLoader) {
                  if (textureLoader == null) throw new Error("textureLoader cannot be null.");
                  var reader = new TextureAtlasReader(atlasText);
                  var tuple = new Array(4);
                  var page = null;

                  while (true) {
                    var line = reader.readLine();
                    if (line == null) break;
                    line = line.trim();
                    if (line.length == 0) page = null;else if (!page) {
                      page = new TextureAtlasPage();
                      page.name = line;

                      if (reader.readTuple(tuple) == 2) {
                        page.width = parseInt(tuple[0]);
                        page.height = parseInt(tuple[1]);
                        reader.readTuple(tuple);
                      }

                      reader.readTuple(tuple);
                      page.minFilter = spine.Texture.filterFromString(tuple[0]);
                      page.magFilter = spine.Texture.filterFromString(tuple[1]);
                      var direction = reader.readValue();
                      page.uWrap = spine.TextureWrap.ClampToEdge;
                      page.vWrap = spine.TextureWrap.ClampToEdge;
                      if (direction == "x") page.uWrap = spine.TextureWrap.Repeat;else if (direction == "y") page.vWrap = spine.TextureWrap.Repeat;else if (direction == "xy") page.uWrap = page.vWrap = spine.TextureWrap.Repeat;
                      page.texture = textureLoader(line);
                      page.texture.setFilters(page.minFilter, page.magFilter);
                      page.texture.setWraps(page.uWrap, page.vWrap);
                      page.width = page.texture.getImage().width;
                      page.height = page.texture.getImage().height;
                      this.pages.push(page);
                    } else {
                      var region = new TextureAtlasRegion();
                      region.name = line;
                      region.page = page;
                      var rotateValue = reader.readValue();

                      if (rotateValue.toLocaleLowerCase() == "true") {
                        region.degrees = 90;
                      } else if (rotateValue.toLocaleLowerCase() == "false") {
                        region.degrees = 0;
                      } else {
                        region.degrees = parseFloat(rotateValue);
                      }

                      region.rotate = region.degrees == 90;
                      reader.readTuple(tuple);
                      var x = parseInt(tuple[0]);
                      var y = parseInt(tuple[1]);
                      reader.readTuple(tuple);
                      var width = parseInt(tuple[0]);
                      var height = parseInt(tuple[1]);
                      region.u = x / page.width;
                      region.v = y / page.height;

                      if (region.rotate) {
                        region.u2 = (x + height) / page.width;
                        region.v2 = (y + width) / page.height;
                      } else {
                        region.u2 = (x + width) / page.width;
                        region.v2 = (y + height) / page.height;
                      }

                      region.x = x;
                      region.y = y;
                      region.width = Math.abs(width);
                      region.height = Math.abs(height);

                      if (reader.readTuple(tuple) == 4) {
                        if (reader.readTuple(tuple) == 4) {
                          reader.readTuple(tuple);
                        }
                      }

                      region.originalWidth = parseInt(tuple[0]);
                      region.originalHeight = parseInt(tuple[1]);
                      reader.readTuple(tuple);
                      region.offsetX = parseInt(tuple[0]);
                      region.offsetY = parseInt(tuple[1]);
                      region.index = parseInt(reader.readValue());
                      region.texture = page.texture;
                      this.regions.push(region);
                    }
                  }
                };

                TextureAtlas.prototype.findRegion = function (name) {
                  for (var i = 0; i < this.regions.length; i++) {
                    if (this.regions[i].name == name) {
                      return this.regions[i];
                    }
                  }

                  return null;
                };

                TextureAtlas.prototype.dispose = function () {
                  for (var i = 0; i < this.pages.length; i++) {
                    this.pages[i].texture.dispose();
                  }
                };

                return TextureAtlas;
              }();

              spine.TextureAtlas = TextureAtlas;

              var TextureAtlasReader = function () {
                function TextureAtlasReader(text) {
                  this.index = 0;
                  this.lines = text.split(/\r\n|\r|\n/);
                }

                TextureAtlasReader.prototype.readLine = function () {
                  if (this.index >= this.lines.length) return null;
                  return this.lines[this.index++];
                };

                TextureAtlasReader.prototype.readValue = function () {
                  var line = this.readLine();
                  var colon = line.indexOf(":");
                  if (colon == -1) throw new Error("Invalid line: " + line);
                  return line.substring(colon + 1).trim();
                };

                TextureAtlasReader.prototype.readTuple = function (tuple) {
                  var line = this.readLine();
                  var colon = line.indexOf(":");
                  if (colon == -1) throw new Error("Invalid line: " + line);
                  var i = 0,
                      lastMatch = colon + 1;

                  for (; i < 3; i++) {
                    var comma = line.indexOf(",", lastMatch);
                    if (comma == -1) break;
                    tuple[i] = line.substr(lastMatch, comma - lastMatch).trim();
                    lastMatch = comma + 1;
                  }

                  tuple[i] = line.substring(lastMatch).trim();
                  return i + 1;
                };

                return TextureAtlasReader;
              }();

              var TextureAtlasPage = function () {
                function TextureAtlasPage() {}

                return TextureAtlasPage;
              }();

              spine.TextureAtlasPage = TextureAtlasPage;

              var TextureAtlasRegion = function (_super) {
                __extends(TextureAtlasRegion, _super);

                function TextureAtlasRegion() {
                  return _super !== null && _super.apply(this, arguments) || this;
                }

                return TextureAtlasRegion;
              }(spine.TextureRegion);

              spine.TextureAtlasRegion = TextureAtlasRegion;
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var TransformConstraint = function () {
                function TransformConstraint(data, skeleton) {
                  this.rotateMix = 0;
                  this.translateMix = 0;
                  this.scaleMix = 0;
                  this.shearMix = 0;
                  this.temp = new spine.Vector2();
                  this.active = false;
                  if (data == null) throw new Error("data cannot be null.");
                  if (skeleton == null) throw new Error("skeleton cannot be null.");
                  this.data = data;
                  this.rotateMix = data.rotateMix;
                  this.translateMix = data.translateMix;
                  this.scaleMix = data.scaleMix;
                  this.shearMix = data.shearMix;
                  this.bones = new Array();

                  for (var i = 0; i < data.bones.length; i++) {
                    this.bones.push(skeleton.findBone(data.bones[i].name));
                  }

                  this.target = skeleton.findBone(data.target.name);
                }

                TransformConstraint.prototype.isActive = function () {
                  return this.active;
                };

                TransformConstraint.prototype.apply = function () {
                  this.update();
                };

                TransformConstraint.prototype.update = function () {
                  if (this.data.local) {
                    if (this.data.relative) this.applyRelativeLocal();else this.applyAbsoluteLocal();
                  } else {
                    if (this.data.relative) this.applyRelativeWorld();else this.applyAbsoluteWorld();
                  }
                };

                TransformConstraint.prototype.applyAbsoluteWorld = function () {
                  var rotateMix = this.rotateMix,
                      translateMix = this.translateMix,
                      scaleMix = this.scaleMix,
                      shearMix = this.shearMix;
                  var target = this.target;
                  var ta = target.a,
                      tb = target.b,
                      tc = target.c,
                      td = target.d;
                  var degRadReflect = ta * td - tb * tc > 0 ? spine.MathUtils.degRad : -spine.MathUtils.degRad;
                  var offsetRotation = this.data.offsetRotation * degRadReflect;
                  var offsetShearY = this.data.offsetShearY * degRadReflect;
                  var bones = this.bones;

                  for (var i = 0, n = bones.length; i < n; i++) {
                    var bone = bones[i];
                    var modified = false;

                    if (rotateMix != 0) {
                      var a = bone.a,
                          b = bone.b,
                          c = bone.c,
                          d = bone.d;
                      var r = Math.atan2(tc, ta) - Math.atan2(c, a) + offsetRotation;
                      if (r > spine.MathUtils.PI) r -= spine.MathUtils.PI2;else if (r < -spine.MathUtils.PI) r += spine.MathUtils.PI2;
                      r *= rotateMix;
                      var cos = Math.cos(r),
                          sin = Math.sin(r);
                      bone.a = cos * a - sin * c;
                      bone.b = cos * b - sin * d;
                      bone.c = sin * a + cos * c;
                      bone.d = sin * b + cos * d;
                      modified = true;
                    }

                    if (translateMix != 0) {
                      var temp = this.temp;
                      target.localToWorld(temp.set(this.data.offsetX, this.data.offsetY));
                      bone.worldX += (temp.x - bone.worldX) * translateMix;
                      bone.worldY += (temp.y - bone.worldY) * translateMix;
                      modified = true;
                    }

                    if (scaleMix > 0) {
                      var s = Math.sqrt(bone.a * bone.a + bone.c * bone.c);
                      var ts = Math.sqrt(ta * ta + tc * tc);
                      if (s > 0.00001) s = (s + (ts - s + this.data.offsetScaleX) * scaleMix) / s;
                      bone.a *= s;
                      bone.c *= s;
                      s = Math.sqrt(bone.b * bone.b + bone.d * bone.d);
                      ts = Math.sqrt(tb * tb + td * td);
                      if (s > 0.00001) s = (s + (ts - s + this.data.offsetScaleY) * scaleMix) / s;
                      bone.b *= s;
                      bone.d *= s;
                      modified = true;
                    }

                    if (shearMix > 0) {
                      var b = bone.b,
                          d = bone.d;
                      var by = Math.atan2(d, b);
                      var r = Math.atan2(td, tb) - Math.atan2(tc, ta) - (by - Math.atan2(bone.c, bone.a));
                      if (r > spine.MathUtils.PI) r -= spine.MathUtils.PI2;else if (r < -spine.MathUtils.PI) r += spine.MathUtils.PI2;
                      r = by + (r + offsetShearY) * shearMix;
                      var s = Math.sqrt(b * b + d * d);
                      bone.b = Math.cos(r) * s;
                      bone.d = Math.sin(r) * s;
                      modified = true;
                    }

                    if (modified) bone.appliedValid = false;
                  }
                };

                TransformConstraint.prototype.applyRelativeWorld = function () {
                  var rotateMix = this.rotateMix,
                      translateMix = this.translateMix,
                      scaleMix = this.scaleMix,
                      shearMix = this.shearMix;
                  var target = this.target;
                  var ta = target.a,
                      tb = target.b,
                      tc = target.c,
                      td = target.d;
                  var degRadReflect = ta * td - tb * tc > 0 ? spine.MathUtils.degRad : -spine.MathUtils.degRad;
                  var offsetRotation = this.data.offsetRotation * degRadReflect,
                      offsetShearY = this.data.offsetShearY * degRadReflect;
                  var bones = this.bones;

                  for (var i = 0, n = bones.length; i < n; i++) {
                    var bone = bones[i];
                    var modified = false;

                    if (rotateMix != 0) {
                      var a = bone.a,
                          b = bone.b,
                          c = bone.c,
                          d = bone.d;
                      var r = Math.atan2(tc, ta) + offsetRotation;
                      if (r > spine.MathUtils.PI) r -= spine.MathUtils.PI2;else if (r < -spine.MathUtils.PI) r += spine.MathUtils.PI2;
                      r *= rotateMix;
                      var cos = Math.cos(r),
                          sin = Math.sin(r);
                      bone.a = cos * a - sin * c;
                      bone.b = cos * b - sin * d;
                      bone.c = sin * a + cos * c;
                      bone.d = sin * b + cos * d;
                      modified = true;
                    }

                    if (translateMix != 0) {
                      var temp = this.temp;
                      target.localToWorld(temp.set(this.data.offsetX, this.data.offsetY));
                      bone.worldX += temp.x * translateMix;
                      bone.worldY += temp.y * translateMix;
                      modified = true;
                    }

                    if (scaleMix > 0) {
                      var s = (Math.sqrt(ta * ta + tc * tc) - 1 + this.data.offsetScaleX) * scaleMix + 1;
                      bone.a *= s;
                      bone.c *= s;
                      s = (Math.sqrt(tb * tb + td * td) - 1 + this.data.offsetScaleY) * scaleMix + 1;
                      bone.b *= s;
                      bone.d *= s;
                      modified = true;
                    }

                    if (shearMix > 0) {
                      var r = Math.atan2(td, tb) - Math.atan2(tc, ta);
                      if (r > spine.MathUtils.PI) r -= spine.MathUtils.PI2;else if (r < -spine.MathUtils.PI) r += spine.MathUtils.PI2;
                      var b = bone.b,
                          d = bone.d;
                      r = Math.atan2(d, b) + (r - spine.MathUtils.PI / 2 + offsetShearY) * shearMix;
                      var s = Math.sqrt(b * b + d * d);
                      bone.b = Math.cos(r) * s;
                      bone.d = Math.sin(r) * s;
                      modified = true;
                    }

                    if (modified) bone.appliedValid = false;
                  }
                };

                TransformConstraint.prototype.applyAbsoluteLocal = function () {
                  var rotateMix = this.rotateMix,
                      translateMix = this.translateMix,
                      scaleMix = this.scaleMix,
                      shearMix = this.shearMix;
                  var target = this.target;
                  if (!target.appliedValid) target.updateAppliedTransform();
                  var bones = this.bones;

                  for (var i = 0, n = bones.length; i < n; i++) {
                    var bone = bones[i];
                    if (!bone.appliedValid) bone.updateAppliedTransform();
                    var rotation = bone.arotation;

                    if (rotateMix != 0) {
                      var r = target.arotation - rotation + this.data.offsetRotation;
                      r -= (16384 - (16384.499999999996 - r / 360 | 0)) * 360;
                      rotation += r * rotateMix;
                    }

                    var x = bone.ax,
                        y = bone.ay;

                    if (translateMix != 0) {
                      x += (target.ax - x + this.data.offsetX) * translateMix;
                      y += (target.ay - y + this.data.offsetY) * translateMix;
                    }

                    var scaleX = bone.ascaleX,
                        scaleY = bone.ascaleY;

                    if (scaleMix != 0) {
                      if (scaleX > 0.00001) scaleX = (scaleX + (target.ascaleX - scaleX + this.data.offsetScaleX) * scaleMix) / scaleX;
                      if (scaleY > 0.00001) scaleY = (scaleY + (target.ascaleY - scaleY + this.data.offsetScaleY) * scaleMix) / scaleY;
                    }

                    var shearY = bone.ashearY;

                    if (shearMix != 0) {
                      var r = target.ashearY - shearY + this.data.offsetShearY;
                      r -= (16384 - (16384.499999999996 - r / 360 | 0)) * 360;
                      bone.shearY += r * shearMix;
                    }

                    bone.updateWorldTransformWith(x, y, rotation, scaleX, scaleY, bone.ashearX, shearY);
                  }
                };

                TransformConstraint.prototype.applyRelativeLocal = function () {
                  var rotateMix = this.rotateMix,
                      translateMix = this.translateMix,
                      scaleMix = this.scaleMix,
                      shearMix = this.shearMix;
                  var target = this.target;
                  if (!target.appliedValid) target.updateAppliedTransform();
                  var bones = this.bones;

                  for (var i = 0, n = bones.length; i < n; i++) {
                    var bone = bones[i];
                    if (!bone.appliedValid) bone.updateAppliedTransform();
                    var rotation = bone.arotation;
                    if (rotateMix != 0) rotation += (target.arotation + this.data.offsetRotation) * rotateMix;
                    var x = bone.ax,
                        y = bone.ay;

                    if (translateMix != 0) {
                      x += (target.ax + this.data.offsetX) * translateMix;
                      y += (target.ay + this.data.offsetY) * translateMix;
                    }

                    var scaleX = bone.ascaleX,
                        scaleY = bone.ascaleY;

                    if (scaleMix != 0) {
                      if (scaleX > 0.00001) scaleX *= (target.ascaleX - 1 + this.data.offsetScaleX) * scaleMix + 1;
                      if (scaleY > 0.00001) scaleY *= (target.ascaleY - 1 + this.data.offsetScaleY) * scaleMix + 1;
                    }

                    var shearY = bone.ashearY;
                    if (shearMix != 0) shearY += (target.ashearY + this.data.offsetShearY) * shearMix;
                    bone.updateWorldTransformWith(x, y, rotation, scaleX, scaleY, bone.ashearX, shearY);
                  }
                };

                return TransformConstraint;
              }();

              spine.TransformConstraint = TransformConstraint;
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var TransformConstraintData = function (_super) {
                __extends(TransformConstraintData, _super);

                function TransformConstraintData(name) {
                  var _this = _super.call(this, name, 0, false) || this;

                  _this.bones = new Array();
                  _this.rotateMix = 0;
                  _this.translateMix = 0;
                  _this.scaleMix = 0;
                  _this.shearMix = 0;
                  _this.offsetRotation = 0;
                  _this.offsetX = 0;
                  _this.offsetY = 0;
                  _this.offsetScaleX = 0;
                  _this.offsetScaleY = 0;
                  _this.offsetShearY = 0;
                  _this.relative = false;
                  _this.local = false;
                  return _this;
                }

                return TransformConstraintData;
              }(spine.ConstraintData);

              spine.TransformConstraintData = TransformConstraintData;
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var Triangulator = function () {
                function Triangulator() {
                  this.convexPolygons = new Array();
                  this.convexPolygonsIndices = new Array();
                  this.indicesArray = new Array();
                  this.isConcaveArray = new Array();
                  this.triangles = new Array();
                  this.polygonPool = new spine.Pool(function () {
                    return new Array();
                  });
                  this.polygonIndicesPool = new spine.Pool(function () {
                    return new Array();
                  });
                }

                Triangulator.prototype.triangulate = function (verticesArray) {
                  var vertices = verticesArray;
                  var vertexCount = verticesArray.length >> 1;
                  var indices = this.indicesArray;
                  indices.length = 0;

                  for (var i = 0; i < vertexCount; i++) {
                    indices[i] = i;
                  }

                  var isConcave = this.isConcaveArray;
                  isConcave.length = 0;

                  for (var i = 0, n = vertexCount; i < n; ++i) {
                    isConcave[i] = Triangulator.isConcave(i, vertexCount, vertices, indices);
                  }

                  var triangles = this.triangles;
                  triangles.length = 0;

                  while (vertexCount > 3) {
                    var previous = vertexCount - 1,
                        i = 0,
                        next = 1;

                    while (true) {
                      outer: if (!isConcave[i]) {
                        var p1 = indices[previous] << 1,
                            p2 = indices[i] << 1,
                            p3 = indices[next] << 1;
                        var p1x = vertices[p1],
                            p1y = vertices[p1 + 1];
                        var p2x = vertices[p2],
                            p2y = vertices[p2 + 1];
                        var p3x = vertices[p3],
                            p3y = vertices[p3 + 1];

                        for (var ii = (next + 1) % vertexCount; ii != previous; ii = (ii + 1) % vertexCount) {
                          if (!isConcave[ii]) continue;
                          var v = indices[ii] << 1;
                          var vx = vertices[v],
                              vy = vertices[v + 1];

                          if (Triangulator.positiveArea(p3x, p3y, p1x, p1y, vx, vy)) {
                            if (Triangulator.positiveArea(p1x, p1y, p2x, p2y, vx, vy)) {
                              if (Triangulator.positiveArea(p2x, p2y, p3x, p3y, vx, vy)) break outer;
                            }
                          }
                        }

                        break;
                      }

                      if (next == 0) {
                        do {
                          if (!isConcave[i]) break;
                          i--;
                        } while (i > 0);

                        break;
                      }

                      previous = i;
                      i = next;
                      next = (next + 1) % vertexCount;
                    }

                    triangles.push(indices[(vertexCount + i - 1) % vertexCount]);
                    triangles.push(indices[i]);
                    triangles.push(indices[(i + 1) % vertexCount]);
                    indices.splice(i, 1);
                    isConcave.splice(i, 1);
                    vertexCount--;
                    var previousIndex = (vertexCount + i - 1) % vertexCount;
                    var nextIndex = i == vertexCount ? 0 : i;
                    isConcave[previousIndex] = Triangulator.isConcave(previousIndex, vertexCount, vertices, indices);
                    isConcave[nextIndex] = Triangulator.isConcave(nextIndex, vertexCount, vertices, indices);
                  }

                  if (vertexCount == 3) {
                    triangles.push(indices[2]);
                    triangles.push(indices[0]);
                    triangles.push(indices[1]);
                  }

                  return triangles;
                };

                Triangulator.prototype.decompose = function (verticesArray, triangles) {
                  var vertices = verticesArray;
                  var convexPolygons = this.convexPolygons;
                  this.polygonPool.freeAll(convexPolygons);
                  convexPolygons.length = 0;
                  var convexPolygonsIndices = this.convexPolygonsIndices;
                  this.polygonIndicesPool.freeAll(convexPolygonsIndices);
                  convexPolygonsIndices.length = 0;
                  var polygonIndices = this.polygonIndicesPool.obtain();
                  polygonIndices.length = 0;
                  var polygon = this.polygonPool.obtain();
                  polygon.length = 0;
                  var fanBaseIndex = -1,
                      lastWinding = 0;

                  for (var i = 0, n = triangles.length; i < n; i += 3) {
                    var t1 = triangles[i] << 1,
                        t2 = triangles[i + 1] << 1,
                        t3 = triangles[i + 2] << 1;
                    var x1 = vertices[t1],
                        y1 = vertices[t1 + 1];
                    var x2 = vertices[t2],
                        y2 = vertices[t2 + 1];
                    var x3 = vertices[t3],
                        y3 = vertices[t3 + 1];
                    var merged = false;

                    if (fanBaseIndex == t1) {
                      var o = polygon.length - 4;
                      var winding1 = Triangulator.winding(polygon[o], polygon[o + 1], polygon[o + 2], polygon[o + 3], x3, y3);
                      var winding2 = Triangulator.winding(x3, y3, polygon[0], polygon[1], polygon[2], polygon[3]);

                      if (winding1 == lastWinding && winding2 == lastWinding) {
                        polygon.push(x3);
                        polygon.push(y3);
                        polygonIndices.push(t3);
                        merged = true;
                      }
                    }

                    if (!merged) {
                      if (polygon.length > 0) {
                        convexPolygons.push(polygon);
                        convexPolygonsIndices.push(polygonIndices);
                      } else {
                        this.polygonPool.free(polygon);
                        this.polygonIndicesPool.free(polygonIndices);
                      }

                      polygon = this.polygonPool.obtain();
                      polygon.length = 0;
                      polygon.push(x1);
                      polygon.push(y1);
                      polygon.push(x2);
                      polygon.push(y2);
                      polygon.push(x3);
                      polygon.push(y3);
                      polygonIndices = this.polygonIndicesPool.obtain();
                      polygonIndices.length = 0;
                      polygonIndices.push(t1);
                      polygonIndices.push(t2);
                      polygonIndices.push(t3);
                      lastWinding = Triangulator.winding(x1, y1, x2, y2, x3, y3);
                      fanBaseIndex = t1;
                    }
                  }

                  if (polygon.length > 0) {
                    convexPolygons.push(polygon);
                    convexPolygonsIndices.push(polygonIndices);
                  }

                  for (var i = 0, n = convexPolygons.length; i < n; i++) {
                    polygonIndices = convexPolygonsIndices[i];
                    if (polygonIndices.length == 0) continue;
                    var firstIndex = polygonIndices[0];
                    var lastIndex = polygonIndices[polygonIndices.length - 1];
                    polygon = convexPolygons[i];
                    var o = polygon.length - 4;
                    var prevPrevX = polygon[o],
                        prevPrevY = polygon[o + 1];
                    var prevX = polygon[o + 2],
                        prevY = polygon[o + 3];
                    var firstX = polygon[0],
                        firstY = polygon[1];
                    var secondX = polygon[2],
                        secondY = polygon[3];
                    var winding = Triangulator.winding(prevPrevX, prevPrevY, prevX, prevY, firstX, firstY);

                    for (var ii = 0; ii < n; ii++) {
                      if (ii == i) continue;
                      var otherIndices = convexPolygonsIndices[ii];
                      if (otherIndices.length != 3) continue;
                      var otherFirstIndex = otherIndices[0];
                      var otherSecondIndex = otherIndices[1];
                      var otherLastIndex = otherIndices[2];
                      var otherPoly = convexPolygons[ii];
                      var x3 = otherPoly[otherPoly.length - 2],
                          y3 = otherPoly[otherPoly.length - 1];
                      if (otherFirstIndex != firstIndex || otherSecondIndex != lastIndex) continue;
                      var winding1 = Triangulator.winding(prevPrevX, prevPrevY, prevX, prevY, x3, y3);
                      var winding2 = Triangulator.winding(x3, y3, firstX, firstY, secondX, secondY);

                      if (winding1 == winding && winding2 == winding) {
                        otherPoly.length = 0;
                        otherIndices.length = 0;
                        polygon.push(x3);
                        polygon.push(y3);
                        polygonIndices.push(otherLastIndex);
                        prevPrevX = prevX;
                        prevPrevY = prevY;
                        prevX = x3;
                        prevY = y3;
                        ii = 0;
                      }
                    }
                  }

                  for (var i = convexPolygons.length - 1; i >= 0; i--) {
                    polygon = convexPolygons[i];

                    if (polygon.length == 0) {
                      convexPolygons.splice(i, 1);
                      this.polygonPool.free(polygon);
                      polygonIndices = convexPolygonsIndices[i];
                      convexPolygonsIndices.splice(i, 1);
                      this.polygonIndicesPool.free(polygonIndices);
                    }
                  }

                  return convexPolygons;
                };

                Triangulator.isConcave = function (index, vertexCount, vertices, indices) {
                  var previous = indices[(vertexCount + index - 1) % vertexCount] << 1;
                  var current = indices[index] << 1;
                  var next = indices[(index + 1) % vertexCount] << 1;
                  return !this.positiveArea(vertices[previous], vertices[previous + 1], vertices[current], vertices[current + 1], vertices[next], vertices[next + 1]);
                };

                Triangulator.positiveArea = function (p1x, p1y, p2x, p2y, p3x, p3y) {
                  return p1x * (p3y - p2y) + p2x * (p1y - p3y) + p3x * (p2y - p1y) >= 0;
                };

                Triangulator.winding = function (p1x, p1y, p2x, p2y, p3x, p3y) {
                  var px = p2x - p1x,
                      py = p2y - p1y;
                  return p3x * py - p3y * px + px * p1y - p1x * py >= 0 ? 1 : -1;
                };

                return Triangulator;
              }();

              spine.Triangulator = Triangulator;
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var IntSet = function () {
                function IntSet() {
                  this.array = new Array();
                }

                IntSet.prototype.add = function (value) {
                  var contains = this.contains(value);
                  this.array[value | 0] = value | 0;
                  return !contains;
                };

                IntSet.prototype.contains = function (value) {
                  return this.array[value | 0] != undefined;
                };

                IntSet.prototype.remove = function (value) {
                  this.array[value | 0] = undefined;
                };

                IntSet.prototype.clear = function () {
                  this.array.length = 0;
                };

                return IntSet;
              }();

              spine.IntSet = IntSet;

              var Color = function () {
                function Color(r, g, b, a) {
                  if (r === void 0) {
                    r = 0;
                  }

                  if (g === void 0) {
                    g = 0;
                  }

                  if (b === void 0) {
                    b = 0;
                  }

                  if (a === void 0) {
                    a = 0;
                  }

                  this.r = r;
                  this.g = g;
                  this.b = b;
                  this.a = a;
                }

                Color.prototype.set = function (r, g, b, a) {
                  this.r = r;
                  this.g = g;
                  this.b = b;
                  this.a = a;
                  this.clamp();
                  return this;
                };

                Color.prototype.setFromColor = function (c) {
                  this.r = c.r;
                  this.g = c.g;
                  this.b = c.b;
                  this.a = c.a;
                  return this;
                };

                Color.prototype.setFromString = function (hex) {
                  hex = hex.charAt(0) == '#' ? hex.substr(1) : hex;
                  this.r = parseInt(hex.substr(0, 2), 16) / 255.0;
                  this.g = parseInt(hex.substr(2, 2), 16) / 255.0;
                  this.b = parseInt(hex.substr(4, 2), 16) / 255.0;
                  this.a = (hex.length != 8 ? 255 : parseInt(hex.substr(6, 2), 16)) / 255.0;
                  return this;
                };

                Color.prototype.add = function (r, g, b, a) {
                  this.r += r;
                  this.g += g;
                  this.b += b;
                  this.a += a;
                  this.clamp();
                  return this;
                };

                Color.prototype.clamp = function () {
                  if (this.r < 0) this.r = 0;else if (this.r > 1) this.r = 1;
                  if (this.g < 0) this.g = 0;else if (this.g > 1) this.g = 1;
                  if (this.b < 0) this.b = 0;else if (this.b > 1) this.b = 1;
                  if (this.a < 0) this.a = 0;else if (this.a > 1) this.a = 1;
                  return this;
                };

                Color.rgba8888ToColor = function (color, value) {
                  color.r = ((value & 0xff000000) >>> 24) / 255;
                  color.g = ((value & 0x00ff0000) >>> 16) / 255;
                  color.b = ((value & 0x0000ff00) >>> 8) / 255;
                  color.a = (value & 0x000000ff) / 255;
                };

                Color.rgb888ToColor = function (color, value) {
                  color.r = ((value & 0x00ff0000) >>> 16) / 255;
                  color.g = ((value & 0x0000ff00) >>> 8) / 255;
                  color.b = (value & 0x000000ff) / 255;
                };

                Color.WHITE = new Color(1, 1, 1, 1);
                Color.RED = new Color(1, 0, 0, 1);
                Color.GREEN = new Color(0, 1, 0, 1);
                Color.BLUE = new Color(0, 0, 1, 1);
                Color.MAGENTA = new Color(1, 0, 1, 1);
                return Color;
              }();

              spine.Color = Color;

              var MathUtils = function () {
                function MathUtils() {}

                MathUtils.clamp = function (value, min, max) {
                  if (value < min) return min;
                  if (value > max) return max;
                  return value;
                };

                MathUtils.cosDeg = function (degrees) {
                  return Math.cos(degrees * MathUtils.degRad);
                };

                MathUtils.sinDeg = function (degrees) {
                  return Math.sin(degrees * MathUtils.degRad);
                };

                MathUtils.signum = function (value) {
                  return value > 0 ? 1 : value < 0 ? -1 : 0;
                };

                MathUtils.toInt = function (x) {
                  return x > 0 ? Math.floor(x) : Math.ceil(x);
                };

                MathUtils.cbrt = function (x) {
                  var y = Math.pow(Math.abs(x), 1 / 3);
                  return x < 0 ? -y : y;
                };

                MathUtils.randomTriangular = function (min, max) {
                  return MathUtils.randomTriangularWith(min, max, (min + max) * 0.5);
                };

                MathUtils.randomTriangularWith = function (min, max, mode) {
                  var u = Math.random();
                  var 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));
                };

                MathUtils.PI = 3.1415927;
                MathUtils.PI2 = MathUtils.PI * 2;
                MathUtils.radiansToDegrees = 180 / MathUtils.PI;
                MathUtils.radDeg = MathUtils.radiansToDegrees;
                MathUtils.degreesToRadians = MathUtils.PI / 180;
                MathUtils.degRad = MathUtils.degreesToRadians;
                return MathUtils;
              }();

              spine.MathUtils = MathUtils;

              var Interpolation = function () {
                function Interpolation() {}

                Interpolation.prototype.apply = function (start, end, a) {
                  return start + (end - start) * this.applyInternal(a);
                };

                return Interpolation;
              }();

              spine.Interpolation = Interpolation;

              var Pow = function (_super) {
                __extends(Pow, _super);

                function Pow(power) {
                  var _this = _super.call(this) || this;

                  _this.power = 2;
                  _this.power = power;
                  return _this;
                }

                Pow.prototype.applyInternal = function (a) {
                  if (a <= 0.5) return Math.pow(a * 2, this.power) / 2;
                  return Math.pow((a - 1) * 2, this.power) / (this.power % 2 == 0 ? -2 : 2) + 1;
                };

                return Pow;
              }(Interpolation);

              spine.Pow = Pow;

              var PowOut = function (_super) {
                __extends(PowOut, _super);

                function PowOut(power) {
                  return _super.call(this, power) || this;
                }

                PowOut.prototype.applyInternal = function (a) {
                  return Math.pow(a - 1, this.power) * (this.power % 2 == 0 ? -1 : 1) + 1;
                };

                return PowOut;
              }(Pow);

              spine.PowOut = PowOut;

              var Utils = function () {
                function Utils() {}

                Utils.arrayCopy = function (source, sourceStart, dest, destStart, numElements) {
                  for (var i = sourceStart, j = destStart; i < sourceStart + numElements; i++, j++) {
                    dest[j] = source[i];
                  }
                };

                Utils.setArraySize = function (array, size, value) {
                  if (value === void 0) {
                    value = 0;
                  }

                  var oldSize = array.length;
                  if (oldSize == size) return array;
                  array.length = size;

                  if (oldSize < size) {
                    for (var i = oldSize; i < size; i++) {
                      array[i] = value;
                    }
                  }

                  return array;
                };

                Utils.ensureArrayCapacity = function (array, size, value) {
                  if (value === void 0) {
                    value = 0;
                  }

                  if (array.length >= size) return array;
                  return Utils.setArraySize(array, size, value);
                };

                Utils.newArray = function (size, defaultValue) {
                  var array = new Array(size);

                  for (var i = 0; i < size; i++) {
                    array[i] = defaultValue;
                  }

                  return array;
                };

                Utils.newFloatArray = function (size) {
                  if (Utils.SUPPORTS_TYPED_ARRAYS) {
                    return new Float32Array(size);
                  } else {
                    var array = new Array(size);

                    for (var i = 0; i < array.length; i++) {
                      array[i] = 0;
                    }

                    return array;
                  }
                };

                Utils.newShortArray = function (size) {
                  if (Utils.SUPPORTS_TYPED_ARRAYS) {
                    return new Int16Array(size);
                  } else {
                    var array = new Array(size);

                    for (var i = 0; i < array.length; i++) {
                      array[i] = 0;
                    }

                    return array;
                  }
                };

                Utils.toFloatArray = function (array) {
                  return Utils.SUPPORTS_TYPED_ARRAYS ? new Float32Array(array) : array;
                };

                Utils.toSinglePrecision = function (value) {
                  return Utils.SUPPORTS_TYPED_ARRAYS ? Math.fround(value) : value;
                };

                Utils.webkit602BugfixHelper = function (alpha, blend) {};

                Utils.contains = function (array, element, identity) {

                  for (var i = 0; i < array.length; i++) {
                    if (array[i] == element) return true;
                  }

                  return false;
                };

                Utils.SUPPORTS_TYPED_ARRAYS = typeof Float32Array !== "undefined";
                return Utils;
              }();

              spine.Utils = Utils;

              var DebugUtils = function () {
                function DebugUtils() {}

                DebugUtils.logBones = function (skeleton) {
                  for (var i = 0; i < skeleton.bones.length; i++) {
                    var bone = skeleton.bones[i];
                    console.log(bone.data.name + ", " + bone.a + ", " + bone.b + ", " + bone.c + ", " + bone.d + ", " + bone.worldX + ", " + bone.worldY);
                  }
                };

                return DebugUtils;
              }();

              spine.DebugUtils = DebugUtils;

              var Pool = function () {
                function Pool(instantiator) {
                  this.items = new Array();
                  this.instantiator = instantiator;
                }

                Pool.prototype.obtain = function () {
                  return this.items.length > 0 ? this.items.pop() : this.instantiator();
                };

                Pool.prototype.free = function (item) {
                  if (item.reset) item.reset();
                  this.items.push(item);
                };

                Pool.prototype.freeAll = function (items) {
                  for (var i = 0; i < items.length; i++) {
                    if (items[i].reset) items[i].reset();
                    this.items[i] = items[i];
                  }
                };

                Pool.prototype.clear = function () {
                  this.items.length = 0;
                };

                return Pool;
              }();

              spine.Pool = Pool;

              var Vector2 = function () {
                function Vector2(x, y) {
                  if (x === void 0) {
                    x = 0;
                  }

                  if (y === void 0) {
                    y = 0;
                  }

                  this.x = x;
                  this.y = y;
                }

                Vector2.prototype.set = function (x, y) {
                  this.x = x;
                  this.y = y;
                  return this;
                };

                Vector2.prototype.length = function () {
                  var x = this.x;
                  var y = this.y;
                  return Math.sqrt(x * x + y * y);
                };

                Vector2.prototype.normalize = function () {
                  var len = this.length();

                  if (len != 0) {
                    this.x /= len;
                    this.y /= len;
                  }

                  return this;
                };

                return Vector2;
              }();

              spine.Vector2 = Vector2;

              var TimeKeeper = function () {
                function TimeKeeper() {
                  this.maxDelta = 0.064;
                  this.framesPerSecond = 0;
                  this.delta = 0;
                  this.totalTime = 0;
                  this.lastTime = Date.now() / 1000;
                  this.frameCount = 0;
                  this.frameTime = 0;
                }

                TimeKeeper.prototype.update = function () {
                  var now = Date.now() / 1000;
                  this.delta = now - this.lastTime;
                  this.frameTime += this.delta;
                  this.totalTime += this.delta;
                  if (this.delta > this.maxDelta) this.delta = this.maxDelta;
                  this.lastTime = now;
                  this.frameCount++;

                  if (this.frameTime > 1) {
                    this.framesPerSecond = this.frameCount / this.frameTime;
                    this.frameTime = 0;
                    this.frameCount = 0;
                  }
                };

                return TimeKeeper;
              }();

              spine.TimeKeeper = TimeKeeper;

              var WindowedMean = function () {
                function WindowedMean(windowSize) {
                  if (windowSize === void 0) {
                    windowSize = 32;
                  }

                  this.addedValues = 0;
                  this.lastValue = 0;
                  this.mean = 0;
                  this.dirty = true;
                  this.values = new Array(windowSize);
                }

                WindowedMean.prototype.hasEnoughData = function () {
                  return this.addedValues >= this.values.length;
                };

                WindowedMean.prototype.addValue = function (value) {
                  if (this.addedValues < this.values.length) this.addedValues++;
                  this.values[this.lastValue++] = value;
                  if (this.lastValue > this.values.length - 1) this.lastValue = 0;
                  this.dirty = true;
                };

                WindowedMean.prototype.getMean = function () {
                  if (this.hasEnoughData()) {
                    if (this.dirty) {
                      var mean = 0;

                      for (var i = 0; i < this.values.length; i++) {
                        mean += this.values[i];
                      }

                      this.mean = mean / this.values.length;
                      this.dirty = false;
                    }

                    return this.mean;
                  } else {
                    return 0;
                  }
                };

                return WindowedMean;
              }();

              spine.WindowedMean = WindowedMean;
            })(spine || (spine = {}));

            (function () {
              if (!Math.fround) {
                Math.fround = function (array) {
                  return function (x) {
                    return array[0] = x, array[0];
                  };
                }(new Float32Array(1));
              }
            })();

            var spine;

            (function (spine) {
              var Attachment = function () {
                function Attachment(name) {
                  if (name == null) throw new Error("name cannot be null.");
                  this.name = name;
                }

                return Attachment;
              }();

              spine.Attachment = Attachment;

              var VertexAttachment = function (_super) {
                __extends(VertexAttachment, _super);

                function VertexAttachment(name) {
                  var _this = _super.call(this, name) || this;

                  _this.id = (VertexAttachment.nextID++ & 65535) << 11;
                  _this.worldVerticesLength = 0;
                  _this.deformAttachment = _this;
                  return _this;
                }

                VertexAttachment.prototype.computeWorldVertices = function (slot, start, count, worldVertices, offset, stride) {
                  count = offset + (count >> 1) * stride;
                  var skeleton = slot.bone.skeleton;
                  var deformArray = slot.deform;
                  var vertices = this.vertices;
                  var bones = this.bones;

                  if (bones == null) {
                    if (deformArray.length > 0) vertices = deformArray;
                    var bone = slot.bone;
                    var x = bone.worldX;
                    var y = bone.worldY;
                    var a = bone.a,
                        b = bone.b,
                        c = bone.c,
                        d = bone.d;

                    for (var v_1 = start, w = offset; w < count; v_1 += 2, w += stride) {
                      var vx = vertices[v_1],
                          vy = vertices[v_1 + 1];
                      worldVertices[w] = vx * a + vy * b + x;
                      worldVertices[w + 1] = vx * c + vy * d + y;
                    }

                    return;
                  }

                  var v = 0,
                      skip = 0;

                  for (var i = 0; i < start; i += 2) {
                    var n = bones[v];
                    v += n + 1;
                    skip += n;
                  }

                  var skeletonBones = skeleton.bones;

                  if (deformArray.length == 0) {
                    for (var w = offset, b = skip * 3; w < count; w += stride) {
                      var wx = 0,
                          wy = 0;
                      var n = bones[v++];
                      n += v;

                      for (; v < n; v++, b += 3) {
                        var bone = skeletonBones[bones[v]];
                        var vx = vertices[b],
                            vy = vertices[b + 1],
                            weight = vertices[b + 2];
                        wx += (vx * bone.a + vy * bone.b + bone.worldX) * weight;
                        wy += (vx * bone.c + vy * bone.d + bone.worldY) * weight;
                      }

                      worldVertices[w] = wx;
                      worldVertices[w + 1] = wy;
                    }
                  } else {
                    var deform = deformArray;

                    for (var w = offset, b = skip * 3, f = skip << 1; w < count; w += stride) {
                      var wx = 0,
                          wy = 0;
                      var n = bones[v++];
                      n += v;

                      for (; v < n; v++, b += 3, f += 2) {
                        var bone = skeletonBones[bones[v]];
                        var vx = vertices[b] + deform[f],
                            vy = vertices[b + 1] + deform[f + 1],
                            weight = vertices[b + 2];
                        wx += (vx * bone.a + vy * bone.b + bone.worldX) * weight;
                        wy += (vx * bone.c + vy * bone.d + bone.worldY) * weight;
                      }

                      worldVertices[w] = wx;
                      worldVertices[w + 1] = wy;
                    }
                  }
                };

                VertexAttachment.prototype.copyTo = function (attachment) {
                  if (this.bones != null) {
                    attachment.bones = new Array(this.bones.length);
                    spine.Utils.arrayCopy(this.bones, 0, attachment.bones, 0, this.bones.length);
                  } else attachment.bones = null;

                  if (this.vertices != null) {
                    attachment.vertices = spine.Utils.newFloatArray(this.vertices.length);
                    spine.Utils.arrayCopy(this.vertices, 0, attachment.vertices, 0, this.vertices.length);
                  } else attachment.vertices = null;

                  attachment.worldVerticesLength = this.worldVerticesLength;
                  attachment.deformAttachment = this.deformAttachment;
                };

                VertexAttachment.nextID = 0;
                return VertexAttachment;
              }(Attachment);

              spine.VertexAttachment = VertexAttachment;
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var AttachmentType;

              (function (AttachmentType) {
                AttachmentType[AttachmentType["Region"] = 0] = "Region";
                AttachmentType[AttachmentType["BoundingBox"] = 1] = "BoundingBox";
                AttachmentType[AttachmentType["Mesh"] = 2] = "Mesh";
                AttachmentType[AttachmentType["LinkedMesh"] = 3] = "LinkedMesh";
                AttachmentType[AttachmentType["Path"] = 4] = "Path";
                AttachmentType[AttachmentType["Point"] = 5] = "Point";
                AttachmentType[AttachmentType["Clipping"] = 6] = "Clipping";
              })(AttachmentType = spine.AttachmentType || (spine.AttachmentType = {}));
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var BoundingBoxAttachment = function (_super) {
                __extends(BoundingBoxAttachment, _super);

                function BoundingBoxAttachment(name) {
                  var _this = _super.call(this, name) || this;

                  _this.color = new spine.Color(1, 1, 1, 1);
                  return _this;
                }

                BoundingBoxAttachment.prototype.copy = function () {
                  var copy = new BoundingBoxAttachment(name);
                  this.copyTo(copy);
                  copy.color.setFromColor(this.color);
                  return copy;
                };

                return BoundingBoxAttachment;
              }(spine.VertexAttachment);

              spine.BoundingBoxAttachment = BoundingBoxAttachment;
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var ClippingAttachment = function (_super) {
                __extends(ClippingAttachment, _super);

                function ClippingAttachment(name) {
                  var _this = _super.call(this, name) || this;

                  _this.color = new spine.Color(0.2275, 0.2275, 0.8078, 1);
                  return _this;
                }

                ClippingAttachment.prototype.copy = function () {
                  var copy = new ClippingAttachment(name);
                  this.copyTo(copy);
                  copy.endSlot = this.endSlot;
                  copy.color.setFromColor(this.color);
                  return copy;
                };

                return ClippingAttachment;
              }(spine.VertexAttachment);

              spine.ClippingAttachment = ClippingAttachment;
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var MeshAttachment = function (_super) {
                __extends(MeshAttachment, _super);

                function MeshAttachment(name) {
                  var _this = _super.call(this, name) || this;

                  _this.color = new spine.Color(1, 1, 1, 1);
                  _this.tempColor = new spine.Color(0, 0, 0, 0);
                  return _this;
                }

                MeshAttachment.prototype.updateUVs = function () {
                  var regionUVs = this.regionUVs;
                  if (this.uvs == null || this.uvs.length != regionUVs.length) this.uvs = spine.Utils.newFloatArray(regionUVs.length);
                  var uvs = this.uvs;
                  var n = this.uvs.length;
                  var u = this.region.u,
                      v = this.region.v,
                      width = 0,
                      height = 0;

                  if (this.region instanceof spine.TextureAtlasRegion) {
                    var region = this.region;
                    var textureWidth = region.texture.getImage().width,
                        textureHeight = region.texture.getImage().height;

                    switch (region.degrees) {
                      case 90:
                        u -= (region.originalHeight - region.offsetY - region.height) / textureWidth;
                        v -= (region.originalWidth - region.offsetX - region.width) / textureHeight;
                        width = region.originalHeight / textureWidth;
                        height = region.originalWidth / textureHeight;

                        for (var i = 0; i < n; i += 2) {
                          uvs[i] = u + regionUVs[i + 1] * width;
                          uvs[i + 1] = v + (1 - regionUVs[i]) * height;
                        }

                        return;

                      case 180:
                        u -= (region.originalWidth - region.offsetX - region.width) / textureWidth;
                        v -= region.offsetY / textureHeight;
                        width = region.originalWidth / textureWidth;
                        height = region.originalHeight / textureHeight;

                        for (var i = 0; i < n; i += 2) {
                          uvs[i] = u + (1 - regionUVs[i]) * width;
                          uvs[i + 1] = v + (1 - regionUVs[i + 1]) * height;
                        }

                        return;

                      case 270:
                        u -= region.offsetY / textureWidth;
                        v -= region.offsetX / textureHeight;
                        width = region.originalHeight / textureWidth;
                        height = region.originalWidth / textureHeight;

                        for (var i = 0; i < n; i += 2) {
                          uvs[i] = u + (1 - regionUVs[i + 1]) * width;
                          uvs[i + 1] = v + regionUVs[i] * height;
                        }

                        return;
                    }

                    u -= region.offsetX / textureWidth;
                    v -= (region.originalHeight - region.offsetY - region.height) / textureHeight;
                    width = region.originalWidth / textureWidth;
                    height = region.originalHeight / textureHeight;
                  } else if (this.region == null) {
                    u = v = 0;
                    width = height = 1;
                  } else {
                    width = this.region.u2 - u;
                    height = this.region.v2 - v;
                  }

                  for (var i = 0; i < n; i += 2) {
                    uvs[i] = u + regionUVs[i] * width;
                    uvs[i + 1] = v + regionUVs[i + 1] * height;
                  }
                };

                MeshAttachment.prototype.getParentMesh = function () {
                  return this.parentMesh;
                };

                MeshAttachment.prototype.setParentMesh = function (parentMesh) {
                  this.parentMesh = parentMesh;

                  if (parentMesh != null) {
                    this.bones = parentMesh.bones;
                    this.vertices = parentMesh.vertices;
                    this.worldVerticesLength = parentMesh.worldVerticesLength;
                    this.regionUVs = parentMesh.regionUVs;
                    this.triangles = parentMesh.triangles;
                    this.hullLength = parentMesh.hullLength;
                    this.worldVerticesLength = parentMesh.worldVerticesLength;
                  }
                };

                MeshAttachment.prototype.copy = function () {
                  if (this.parentMesh != null) return this.newLinkedMesh();
                  var copy = new MeshAttachment(this.name);
                  copy.region = this.region;
                  copy.path = this.path;
                  copy.color.setFromColor(this.color);
                  this.copyTo(copy);
                  copy.regionUVs = new Array(this.regionUVs.length);
                  spine.Utils.arrayCopy(this.regionUVs, 0, copy.regionUVs, 0, this.regionUVs.length);
                  copy.uvs = new Array(this.uvs.length);
                  spine.Utils.arrayCopy(this.uvs, 0, copy.uvs, 0, this.uvs.length);
                  copy.triangles = new Array(this.triangles.length);
                  spine.Utils.arrayCopy(this.triangles, 0, copy.triangles, 0, this.triangles.length);
                  copy.hullLength = this.hullLength;

                  if (this.edges != null) {
                    copy.edges = new Array(this.edges.length);
                    spine.Utils.arrayCopy(this.edges, 0, copy.edges, 0, this.edges.length);
                  }

                  copy.width = this.width;
                  copy.height = this.height;
                  return copy;
                };

                MeshAttachment.prototype.newLinkedMesh = function () {
                  var copy = new MeshAttachment(this.name);
                  copy.region = this.region;
                  copy.path = this.path;
                  copy.color.setFromColor(this.color);
                  copy.deformAttachment = this.deformAttachment;
                  copy.setParentMesh(this.parentMesh != null ? this.parentMesh : this);
                  copy.updateUVs();
                  return copy;
                };

                return MeshAttachment;
              }(spine.VertexAttachment);

              spine.MeshAttachment = MeshAttachment;
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var PathAttachment = function (_super) {
                __extends(PathAttachment, _super);

                function PathAttachment(name) {
                  var _this = _super.call(this, name) || this;

                  _this.closed = false;
                  _this.constantSpeed = false;
                  _this.color = new spine.Color(1, 1, 1, 1);
                  return _this;
                }

                PathAttachment.prototype.copy = function () {
                  var copy = new PathAttachment(name);
                  this.copyTo(copy);
                  copy.lengths = new Array(this.lengths.length);
                  spine.Utils.arrayCopy(this.lengths, 0, copy.lengths, 0, this.lengths.length);
                  copy.closed = closed;
                  copy.constantSpeed = this.constantSpeed;
                  copy.color.setFromColor(this.color);
                  return copy;
                };

                return PathAttachment;
              }(spine.VertexAttachment);

              spine.PathAttachment = PathAttachment;
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var PointAttachment = function (_super) {
                __extends(PointAttachment, _super);

                function PointAttachment(name) {
                  var _this = _super.call(this, name) || this;

                  _this.color = new spine.Color(0.38, 0.94, 0, 1);
                  return _this;
                }

                PointAttachment.prototype.computeWorldPosition = function (bone, point) {
                  point.x = this.x * bone.a + this.y * bone.b + bone.worldX;
                  point.y = this.x * bone.c + this.y * bone.d + bone.worldY;
                  return point;
                };

                PointAttachment.prototype.computeWorldRotation = function (bone) {
                  var cos = spine.MathUtils.cosDeg(this.rotation),
                      sin = spine.MathUtils.sinDeg(this.rotation);
                  var x = cos * bone.a + sin * bone.b;
                  var y = cos * bone.c + sin * bone.d;
                  return Math.atan2(y, x) * spine.MathUtils.radDeg;
                };

                PointAttachment.prototype.copy = function () {
                  var copy = new PointAttachment(name);
                  copy.x = this.x;
                  copy.y = this.y;
                  copy.rotation = this.rotation;
                  copy.color.setFromColor(this.color);
                  return copy;
                };

                return PointAttachment;
              }(spine.VertexAttachment);

              spine.PointAttachment = PointAttachment;
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var RegionAttachment = function (_super) {
                __extends(RegionAttachment, _super);

                function RegionAttachment(name) {
                  var _this = _super.call(this, name) || this;

                  _this.x = 0;
                  _this.y = 0;
                  _this.scaleX = 1;
                  _this.scaleY = 1;
                  _this.rotation = 0;
                  _this.width = 0;
                  _this.height = 0;
                  _this.color = new spine.Color(1, 1, 1, 1);
                  _this.offset = spine.Utils.newFloatArray(8);
                  _this.uvs = spine.Utils.newFloatArray(8);
                  _this.tempColor = new spine.Color(1, 1, 1, 1);
                  return _this;
                }

                RegionAttachment.prototype.updateOffset = function () {
                  var regionScaleX = this.width / this.region.originalWidth * this.scaleX;
                  var regionScaleY = this.height / this.region.originalHeight * this.scaleY;
                  var localX = -this.width / 2 * this.scaleX + this.region.offsetX * regionScaleX;
                  var localY = -this.height / 2 * this.scaleY + this.region.offsetY * regionScaleY;
                  var localX2 = localX + this.region.width * regionScaleX;
                  var localY2 = localY + this.region.height * regionScaleY;
                  var radians = this.rotation * Math.PI / 180;
                  var cos = Math.cos(radians);
                  var sin = Math.sin(radians);
                  var localXCos = localX * cos + this.x;
                  var localXSin = localX * sin;
                  var localYCos = localY * cos + this.y;
                  var localYSin = localY * sin;
                  var localX2Cos = localX2 * cos + this.x;
                  var localX2Sin = localX2 * sin;
                  var localY2Cos = localY2 * cos + this.y;
                  var localY2Sin = localY2 * sin;
                  var offset = this.offset;
                  offset[RegionAttachment.OX1] = localXCos - localYSin;
                  offset[RegionAttachment.OY1] = localYCos + localXSin;
                  offset[RegionAttachment.OX2] = localXCos - localY2Sin;
                  offset[RegionAttachment.OY2] = localY2Cos + localXSin;
                  offset[RegionAttachment.OX3] = localX2Cos - localY2Sin;
                  offset[RegionAttachment.OY3] = localY2Cos + localX2Sin;
                  offset[RegionAttachment.OX4] = localX2Cos - localYSin;
                  offset[RegionAttachment.OY4] = localYCos + localX2Sin;
                };

                RegionAttachment.prototype.setRegion = function (region) {
                  this.region = region;
                  var uvs = this.uvs;

                  if (region.rotate) {
                    uvs[2] = region.u;
                    uvs[3] = region.v2;
                    uvs[4] = region.u;
                    uvs[5] = region.v;
                    uvs[6] = region.u2;
                    uvs[7] = region.v;
                    uvs[0] = region.u2;
                    uvs[1] = region.v2;
                  } else {
                    uvs[0] = region.u;
                    uvs[1] = region.v2;
                    uvs[2] = region.u;
                    uvs[3] = region.v;
                    uvs[4] = region.u2;
                    uvs[5] = region.v;
                    uvs[6] = region.u2;
                    uvs[7] = region.v2;
                  }
                };

                RegionAttachment.prototype.computeWorldVertices = function (bone, worldVertices, offset, stride) {
                  var vertexOffset = this.offset;
                  var x = bone.worldX,
                      y = bone.worldY;
                  var a = bone.a,
                      b = bone.b,
                      c = bone.c,
                      d = bone.d;
                  var offsetX = 0,
                      offsetY = 0;
                  offsetX = vertexOffset[RegionAttachment.OX1];
                  offsetY = vertexOffset[RegionAttachment.OY1];
                  worldVertices[offset] = offsetX * a + offsetY * b + x;
                  worldVertices[offset + 1] = offsetX * c + offsetY * d + y;
                  offset += stride;
                  offsetX = vertexOffset[RegionAttachment.OX2];
                  offsetY = vertexOffset[RegionAttachment.OY2];
                  worldVertices[offset] = offsetX * a + offsetY * b + x;
                  worldVertices[offset + 1] = offsetX * c + offsetY * d + y;
                  offset += stride;
                  offsetX = vertexOffset[RegionAttachment.OX3];
                  offsetY = vertexOffset[RegionAttachment.OY3];
                  worldVertices[offset] = offsetX * a + offsetY * b + x;
                  worldVertices[offset + 1] = offsetX * c + offsetY * d + y;
                  offset += stride;
                  offsetX = vertexOffset[RegionAttachment.OX4];
                  offsetY = vertexOffset[RegionAttachment.OY4];
                  worldVertices[offset] = offsetX * a + offsetY * b + x;
                  worldVertices[offset + 1] = offsetX * c + offsetY * d + y;
                };

                RegionAttachment.prototype.copy = function () {
                  var copy = new RegionAttachment(name);
                  copy.region = this.region;
                  copy.rendererObject = this.rendererObject;
                  copy.path = this.path;
                  copy.x = this.x;
                  copy.y = this.y;
                  copy.scaleX = this.scaleX;
                  copy.scaleY = this.scaleY;
                  copy.rotation = this.rotation;
                  copy.width = this.width;
                  copy.height = this.height;
                  spine.Utils.arrayCopy(this.uvs, 0, copy.uvs, 0, 8);
                  spine.Utils.arrayCopy(this.offset, 0, copy.offset, 0, 8);
                  copy.color.setFromColor(this.color);
                  return copy;
                };

                RegionAttachment.OX1 = 0;
                RegionAttachment.OY1 = 1;
                RegionAttachment.OX2 = 2;
                RegionAttachment.OY2 = 3;
                RegionAttachment.OX3 = 4;
                RegionAttachment.OY3 = 5;
                RegionAttachment.OX4 = 6;
                RegionAttachment.OY4 = 7;
                RegionAttachment.X1 = 0;
                RegionAttachment.Y1 = 1;
                RegionAttachment.C1R = 2;
                RegionAttachment.C1G = 3;
                RegionAttachment.C1B = 4;
                RegionAttachment.C1A = 5;
                RegionAttachment.U1 = 6;
                RegionAttachment.V1 = 7;
                RegionAttachment.X2 = 8;
                RegionAttachment.Y2 = 9;
                RegionAttachment.C2R = 10;
                RegionAttachment.C2G = 11;
                RegionAttachment.C2B = 12;
                RegionAttachment.C2A = 13;
                RegionAttachment.U2 = 14;
                RegionAttachment.V2 = 15;
                RegionAttachment.X3 = 16;
                RegionAttachment.Y3 = 17;
                RegionAttachment.C3R = 18;
                RegionAttachment.C3G = 19;
                RegionAttachment.C3B = 20;
                RegionAttachment.C3A = 21;
                RegionAttachment.U3 = 22;
                RegionAttachment.V3 = 23;
                RegionAttachment.X4 = 24;
                RegionAttachment.Y4 = 25;
                RegionAttachment.C4R = 26;
                RegionAttachment.C4G = 27;
                RegionAttachment.C4B = 28;
                RegionAttachment.C4A = 29;
                RegionAttachment.U4 = 30;
                RegionAttachment.V4 = 31;
                return RegionAttachment;
              }(spine.Attachment);

              spine.RegionAttachment = RegionAttachment;
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var JitterEffect = function () {
                function JitterEffect(jitterX, jitterY) {
                  this.jitterX = 0;
                  this.jitterY = 0;
                  this.jitterX = jitterX;
                  this.jitterY = jitterY;
                }

                JitterEffect.prototype.begin = function (skeleton) {};

                JitterEffect.prototype.transform = function (position, uv, light, dark) {
                  position.x += spine.MathUtils.randomTriangular(-this.jitterX, this.jitterY);
                  position.y += spine.MathUtils.randomTriangular(-this.jitterX, this.jitterY);
                };

                JitterEffect.prototype.end = function () {};

                return JitterEffect;
              }();

              spine.JitterEffect = JitterEffect;
            })(spine || (spine = {}));

            var spine;

            (function (spine) {
              var SwirlEffect = function () {
                function SwirlEffect(radius, interpolation) {
                  this.centerX = 0;
                  this.centerY = 0;
                  this.radius = 0;
                  this.angle = 0;
                  this.worldX = 0;
                  this.worldY = 0;
                  this.radius = radius;
                  this.interpolation = interpolation;
                }

                SwirlEffect.prototype.begin = function (skeleton) {
                  this.worldX = skeleton.x + this.centerX;
                  this.worldY = skeleton.y + this.centerY;
                };

                SwirlEffect.prototype.transform = function (position, uv, light, dark) {
                  var radAngle = this.angle * spine.MathUtils.degreesToRadians;
                  var x = position.x - this.worldX;
                  var y = position.y - this.worldY;
                  var dist = Math.sqrt(x * x + y * y);

                  if (dist < this.radius) {
                    var theta = this.interpolation.apply(0, radAngle, (this.radius - dist) / this.radius);
                    var cos = Math.cos(theta);
                    var sin = Math.sin(theta);
                    position.x = cos * x - sin * y + this.worldX;
                    position.y = sin * x + cos * y + this.worldY;
                  }
                };

                SwirlEffect.prototype.end = function () {};

                SwirlEffect.interpolation = new spine.PowOut(2);
                return SwirlEffect;
              }();

              spine.SwirlEffect = SwirlEffect;
            })(spine || (spine = {}));

            var spine$1 = spine;

            var TrackEntryListeners = function () {
              function TrackEntryListeners() {
                this.start = void 0;
                this.interrupt = void 0;
                this.end = void 0;
                this.dispose = void 0;
                this.complete = void 0;
                this.event = void 0;
              }

              TrackEntryListeners.getListeners = function getListeners(entry) {
                if (!entry.listener) {
                  entry.listener = new TrackEntryListeners();
                }

                return entry.listener;
              };

              return TrackEntryListeners;
            }();

            var MaxCacheTime = 30;
            var FrameTime = 1 / 60;
            var _vertices$1 = [];
            var _indices = [];
            var _boneInfoOffset = 0;
            var _indexOffset = 0;
            var _vfOffset$1 = 0;
            var _preTexUrl = null;
            var _preBlendMode = null;
            var _segVCount = 0;
            var _segICount = 0;
            var _segOffset = 0;
            var _colorOffset = 0;
            var _preFinalColor = null;
            var _preDarkColor = null;
            var PerVertexSize = 6;
            var PerClipVertexSize = 12;
            var ExportVertexSize = 13;
            var _vfCount = 0;
            var _indexCount = 0;

            var _tempr;

            var _tempg;

            var _tempb;

            var _tempa;

            var _finalColor32;

            var _darkColor32;

            var _finalColor = new spine$1.Color(1, 1, 1, 1);

            var _darkColor = new spine$1.Color(1, 1, 1, 1);

            var _quadTriangles = [0, 1, 2, 2, 3, 0];
            var AnimationCache = function () {
              function AnimationCache() {
                this.frames = [];
                this.totalTime = 0;
                this.isCompleted = false;
                this._privateMode = false;
                this._inited = false;
                this._invalid = true;
                this._enableCacheAttachedInfo = false;
                this._frameIdx = -1;
                this._skeletonInfo = null;
                this._animationName = null;
                this._tempSegments = null;
                this._tempColors = null;
                this._tempBoneInfos = null;
                this._privateMode = false;
                this._inited = false;
                this._invalid = true;
                this._enableCacheAttachedInfo = false;
                this.frames = [];
                this.totalTime = 0;
                this._frameIdx = -1;
                this.isCompleted = false;
                this._skeletonInfo = null;
                this._animationName = null;
                this._tempSegments = null;
                this._tempColors = null;
                this._tempBoneInfos = null;
              }

              var _proto = AnimationCache.prototype;

              _proto.init = function init(skeletonInfo, animationName) {
                this._inited = true;
                this._animationName = animationName;
                this._skeletonInfo = skeletonInfo;
              };

              _proto.clear = function clear() {
                this._inited = false;

                for (var i = 0, n = this.frames.length; i < n; i++) {
                  var frame = this.frames[i];
                  frame.segments.length = 0;
                }

                this.invalidAllFrame();
              };

              _proto.bind = function bind(listener) {
                var _this = this;

                var completeHandle = function completeHandle(entry) {
                  if (entry && entry.animation.name === _this._animationName) {
                    _this.isCompleted = true;
                  }
                };

                listener.complete = completeHandle;
              };

              _proto.unbind = function unbind(listener) {
                listener.complete = null;
              };

              _proto.begin = function begin() {
                if (!this._invalid) return;
                var skeletonInfo = this._skeletonInfo;
                var preAnimationCache = skeletonInfo === null || skeletonInfo === void 0 ? void 0 : skeletonInfo.curAnimationCache;

                if (preAnimationCache && preAnimationCache !== this) {
                  if (this._privateMode) {
                    preAnimationCache.invalidAllFrame();
                  } else {
                    preAnimationCache.updateToFrame();
                  }
                }

                var skeleton = skeletonInfo === null || skeletonInfo === void 0 ? void 0 : skeletonInfo.skeleton;
                var listener = skeletonInfo === null || skeletonInfo === void 0 ? void 0 : skeletonInfo.listener;
                var state = skeletonInfo === null || skeletonInfo === void 0 ? void 0 : skeletonInfo.state;
                var animation = skeleton === null || skeleton === void 0 ? void 0 : skeleton.data.findAnimation(this._animationName);
                state === null || state === void 0 ? void 0 : state.setAnimationWith(0, animation, false);
                this.bind(listener);
                skeletonInfo.curAnimationCache = this;
                this._frameIdx = -1;
                this.isCompleted = false;
                this.totalTime = 0;
                this._invalid = false;
              };

              _proto.end = function end() {
                if (!this.needToUpdate()) {
                  this._skeletonInfo.curAnimationCache = null;
                  this.frames.length = this._frameIdx + 1;
                  this.isCompleted = true;
                  this.unbind(this._skeletonInfo.listener);
                }
              };

              _proto.updateToFrame = function updateToFrame(toFrameIdx) {
                if (!this._inited) return;
                this.begin();
                if (!this.needToUpdate(toFrameIdx)) return;
                var skeletonInfo = this._skeletonInfo;
                var skeleton = skeletonInfo === null || skeletonInfo === void 0 ? void 0 : skeletonInfo.skeleton;
                var clipper = skeletonInfo === null || skeletonInfo === void 0 ? void 0 : skeletonInfo.clipper;
                var state = skeletonInfo === null || skeletonInfo === void 0 ? void 0 : skeletonInfo.state;

                do {
                  skeleton === null || skeleton === void 0 ? void 0 : skeleton.update(FrameTime);
                  state === null || state === void 0 ? void 0 : state.update(FrameTime);
                  state === null || state === void 0 ? void 0 : state.apply(skeleton);
                  skeleton === null || skeleton === void 0 ? void 0 : skeleton.updateWorldTransform();
                  this._frameIdx++;
                  this.updateFrame(skeleton, clipper, this._frameIdx);
                  this.totalTime += FrameTime;
                } while (this.needToUpdate(toFrameIdx));

                this.end();
              };

              _proto.isInited = function isInited() {
                return this._inited;
              };

              _proto.isInvalid = function isInvalid() {
                return this._invalid;
              };

              _proto.invalidAllFrame = function invalidAllFrame() {
                this.isCompleted = false;
                this._invalid = true;
              };

              _proto.updateAllFrame = function updateAllFrame() {
                this.invalidAllFrame();
                this.updateToFrame();
              };

              _proto.enableCacheAttachedInfo = function enableCacheAttachedInfo() {
                if (!this._enableCacheAttachedInfo) {
                  this._enableCacheAttachedInfo = true;
                  this.invalidAllFrame();
                }
              };

              _proto.fillVertices = function fillVertices(skeletonColor, attachmentColor, slotColor, clipper, slot) {
                _tempa = slotColor.a * attachmentColor.a * skeletonColor.a * 255;
                _tempr = attachmentColor.r * skeletonColor.r * 255;
                _tempg = attachmentColor.g * skeletonColor.g * 255;
                _tempb = attachmentColor.b * skeletonColor.b * 255;
                _finalColor.r = _tempr * slotColor.r;
                _finalColor.g = _tempg * slotColor.g;
                _finalColor.b = _tempb * slotColor.b;
                _finalColor.a = _tempa;

                if (slot.darkColor == null) {
                  _darkColor.set(0.0, 0, 0, 1.0);
                } else {
                  _darkColor.r = slot.darkColor.r * _tempr;
                  _darkColor.g = slot.darkColor.g * _tempg;
                  _darkColor.b = slot.darkColor.b * _tempb;
                }

                _darkColor.a = 0;
                _finalColor32 = (_finalColor.a << 24 >>> 0) + (_finalColor.b << 16) + (_finalColor.g << 8) + _finalColor.r;
                _darkColor32 = (_darkColor.a << 24 >>> 0) + (_darkColor.b << 16) + (_darkColor.g << 8) + _darkColor.r;

                if (_preFinalColor !== _finalColor32 || _preDarkColor !== _darkColor32) {
                  var colors = this._tempColors;
                  _preFinalColor = _finalColor32;
                  _preDarkColor = _darkColor32;

                  if (_colorOffset > 0) {
                    colors[_colorOffset - 1].vfOffset = _vfOffset$1;
                  }

                  colors[_colorOffset++] = {
                    fr: _finalColor.r,
                    fg: _finalColor.g,
                    fb: _finalColor.b,
                    fa: _finalColor.a,
                    dr: _darkColor.r,
                    dg: _darkColor.g,
                    db: _darkColor.b,
                    da: _darkColor.a,
                    vfOffset: 0
                  };
                }

                if (!clipper.isClipping()) {
                  for (var v = _vfOffset$1, n = _vfOffset$1 + _vfCount; v < n; v += PerVertexSize) {
                    _vertices$1[v + 4] = _finalColor32;
                    _vertices$1[v + 5] = _darkColor32;
                  }
                } else {
                  clipper.clipTriangles(_vertices$1, _vfCount, _indices, _indexCount, _vertices$1, _finalColor, _darkColor, true, PerVertexSize, _vfOffset$1, _vfOffset$1 + 2);
                  var clippedVertices = clipper.clippedVertices;
                  var clippedTriangles = clipper.clippedTriangles;
                  _indexCount = clippedTriangles.length;
                  _vfCount = clippedVertices.length / PerClipVertexSize * PerVertexSize;

                  for (var ii = 0, jj = _indexOffset, nn = clippedTriangles.length; ii < nn;) {
                    _indices[jj++] = clippedTriangles[ii++];
                  }

                  for (var _v = 0, _n = clippedVertices.length, offset = _vfOffset$1; _v < _n; _v += PerClipVertexSize, offset += PerVertexSize) {
                    _vertices$1[offset] = clippedVertices[_v];
                    _vertices$1[offset + 1] = clippedVertices[_v + 1];
                    _vertices$1[offset + 2] = clippedVertices[_v + 6];
                    _vertices$1[offset + 3] = clippedVertices[_v + 7];
                    _vertices$1[offset + 4] = _finalColor32;
                    _vertices$1[offset + 5] = _darkColor32;
                  }
                }
              };

              _proto.updateFrame = function updateFrame(skeleton, clipper, index) {
                _vfOffset$1 = 0;
                _boneInfoOffset = 0;
                _indexOffset = 0;
                _preTexUrl = null;
                _preBlendMode = null;
                _segVCount = 0;
                _segICount = 0;
                _segOffset = 0;
                _colorOffset = 0;
                _preFinalColor = null;
                _preDarkColor = null;
                this.frames[index] = this.frames[index] || {
                  segments: [],
                  colors: [],
                  boneInfos: [],
                  vertices: null,
                  uintVert: null,
                  indices: null
                };
                var frame = this.frames[index];
                var segments = this._tempSegments = frame.segments;
                var colors = this._tempColors = frame.colors;
                var boneInfos = this._tempBoneInfos = frame.boneInfos;
                this.traverseSkeleton(skeleton, clipper);

                if (_colorOffset > 0) {
                  colors[_colorOffset - 1].vfOffset = _vfOffset$1;
                }

                colors.length = _colorOffset;
                boneInfos.length = _boneInfoOffset;
                var preSegOffset = _segOffset - 1;

                if (preSegOffset >= 0) {
                  if (_segICount > 0) {
                    var preSegInfo = segments[preSegOffset];
                    preSegInfo.indexCount = _segICount;
                    preSegInfo.vfCount = _segVCount * ExportVertexSize;
                    preSegInfo.vertexCount = _segVCount;
                    segments.length = _segOffset;
                  } else {
                    segments.length = _segOffset - 1;
                  }
                }

                if (segments.length === 0) return;
                var vertices = frame.vertices;
                var copyOutVerticeSize = _vfOffset$1 / PerVertexSize * ExportVertexSize;

                if (!vertices || vertices.length < copyOutVerticeSize) {
                  vertices = frame.vertices = new Float32Array(copyOutVerticeSize);
                }

                for (var i = 0, j = 0; i < copyOutVerticeSize;) {
                  vertices[i] = _vertices$1[j++];
                  vertices[i + 1] = _vertices$1[j++];
                  vertices[i + 3] = _vertices$1[j++];
                  vertices[i + 4] = _vertices$1[j++];

                  this._setVerticeColor(_vertices$1[j++], vertices, i + 5);

                  this._setVerticeColor(_vertices$1[j++], vertices, i + 9);

                  i += ExportVertexSize;
                }

                var indices = frame.indices;

                if (!indices || indices.length < _indexOffset) {
                  indices = frame.indices = new Uint16Array(_indexOffset);
                }

                for (var _i = 0; _i < _indexOffset; _i++) {
                  indices[_i] = _indices[_i];
                }

                frame.vertices = vertices;
                frame.indices = indices;
              };

              _proto.needToUpdate = function needToUpdate(toFrameIdx) {
                return !this.isCompleted && this.totalTime < MaxCacheTime && (toFrameIdx === undefined || this._frameIdx < toFrameIdx);
              };

              _proto.traverseSkeleton = function traverseSkeleton(skeleton, clipper) {
                var segments = this._tempSegments;
                var boneInfos = this._tempBoneInfos;
                var skeletonColor = skeleton.color;
                var attachment;
                var attachmentColor;
                var slotColor;
                var uvs;
                var triangles;
                var isRegion;
                var isMesh;
                var isClip;
                var texture;
                var preSegOffset;
                var preSegInfo;
                var blendMode;
                var slot;
                var bones = skeleton.bones;

                if (this._enableCacheAttachedInfo) {
                  for (var i = 0, l = bones.length; i < l; i++, _boneInfoOffset++) {
                    var bone = bones[i];
                    var boneInfo = boneInfos[_boneInfoOffset];

                    if (!boneInfo) {
                      boneInfo = boneInfos[_boneInfoOffset] = {};
                    }

                    boneInfo.a = bone.a;
                    boneInfo.b = bone.b;
                    boneInfo.c = bone.c;
                    boneInfo.d = bone.d;
                    boneInfo.worldX = bone.worldX;
                    boneInfo.worldY = bone.worldY;
                  }
                }

                for (var slotIdx = 0, slotCount = skeleton.drawOrder.length; slotIdx < slotCount; slotIdx++) {
                  slot = skeleton.drawOrder[slotIdx];
                  _vfCount = 0;
                  _indexCount = 0;
                  attachment = slot.getAttachment();

                  if (!attachment) {
                    clipper.clipEndWithSlot(slot);
                    continue;
                  }

                  isRegion = attachment instanceof spine$1.RegionAttachment;
                  isMesh = attachment instanceof spine$1.MeshAttachment;
                  isClip = attachment instanceof spine$1.ClippingAttachment;

                  if (isClip) {
                    clipper.clipStart(slot, attachment);
                    continue;
                  }

                  if (!isRegion && !isMesh) {
                    clipper.clipEndWithSlot(slot);
                    continue;
                  }

                  texture = attachment.region.texture.getRealTexture();

                  if (!texture) {
                    clipper.clipEndWithSlot(slot);
                    continue;
                  }

                  blendMode = slot.data.blendMode;

                  if (_preTexUrl !== texture.nativeUrl || _preBlendMode !== blendMode) {
                    _preTexUrl = texture.nativeUrl;
                    _preBlendMode = blendMode;
                    preSegOffset = _segOffset - 1;

                    if (preSegOffset >= 0) {
                      if (_segICount > 0) {
                        preSegInfo = segments[preSegOffset];
                        preSegInfo.indexCount = _segICount;
                        preSegInfo.vertexCount = _segVCount;
                        preSegInfo.vfCount = _segVCount * ExportVertexSize;
                      } else {
                        _segOffset--;
                      }
                    }

                    segments[_segOffset] = {
                      tex: texture,
                      blendMode: blendMode,
                      indexCount: 0,
                      vertexCount: 0,
                      vfCount: 0
                    };
                    _segOffset++;
                    _segICount = 0;
                    _segVCount = 0;
                  }

                  if (isRegion) {
                    triangles = _quadTriangles;
                    _vfCount = 4 * PerVertexSize;
                    _indexCount = 6;
                    attachment.computeWorldVertices(slot.bone, _vertices$1, _vfOffset$1, PerVertexSize);
                  } else if (isMesh) {
                    var meshAttachment = attachment;
                    triangles = meshAttachment.triangles;
                    _vfCount = (meshAttachment.worldVerticesLength >> 1) * PerVertexSize;
                    _indexCount = triangles.length;
                    meshAttachment.computeWorldVertices(slot, 0, meshAttachment.worldVerticesLength, _vertices$1, _vfOffset$1, PerVertexSize);
                  }

                  if (_vfCount === 0 || _indexCount === 0) {
                    clipper.clipEndWithSlot(slot);
                    continue;
                  }

                  for (var ii = 0, jj = _indexOffset, nn = triangles.length; ii < nn;) {
                    _indices[jj++] = triangles[ii++];
                  }

                  uvs = attachment.uvs;

                  for (var v = _vfOffset$1, n = _vfOffset$1 + _vfCount, u = 0; v < n; v += PerVertexSize, u += 2) {
                    _vertices$1[v + 2] = uvs[u];
                    _vertices$1[v + 3] = uvs[u + 1];
                  }

                  attachmentColor = attachment.color;
                  slotColor = slot.color;
                  this.fillVertices(skeletonColor, attachmentColor, slotColor, clipper, slot);

                  if (_indexCount > 0) {
                    for (var _ii = _indexOffset, _nn = _indexOffset + _indexCount; _ii < _nn; _ii++) {
                      _indices[_ii] += _segVCount;
                    }

                    _indexOffset += _indexCount;
                    _vfOffset$1 += _vfCount;
                    _segICount += _indexCount;
                    _segVCount += _vfCount / PerVertexSize;
                  }

                  clipper.clipEndWithSlot(slot);
                }

                clipper.clipEnd();
              };

              _proto._setVerticeColor = function _setVerticeColor(colorI32, buffer, offset) {
                buffer[offset] = (colorI32 & 0xff) / 255.0;
                buffer[offset + 1] = (colorI32 >> 8 & 0xff) / 255.0;
                buffer[offset + 2] = (colorI32 >> 16 & 0xff) / 255.0;
                buffer[offset + 3] = (colorI32 >> 24 & 0xff) / 255.0;
              };

              return AnimationCache;
            }();

            var SkeletonCache = function () {
              function SkeletonCache() {
                this._privateMode = void 0;
                this._skeletonCache = void 0;
                this._animationPool = void 0;
                this._privateMode = false;
                this._animationPool = {};
                this._skeletonCache = {};
              }

              var _proto2 = SkeletonCache.prototype;

              _proto2.enablePrivateMode = function enablePrivateMode() {
                this._privateMode = true;
              };

              _proto2.clear = function clear() {
                this._animationPool = {};
                this._skeletonCache = {};
              };

              _proto2.removeSkeleton = function removeSkeleton(uuid) {
                var skeletonInfo = this._skeletonCache[uuid];
                if (!skeletonInfo) return;
                var animationsCache = skeletonInfo.animationsCache;

                for (var aniKey in animationsCache) {
                  var animationCache = animationsCache[aniKey];
                  if (!animationCache) continue;
                  this._animationPool[uuid + "#" + aniKey] = animationCache;
                  animationCache.clear();
                }

                delete this._skeletonCache[uuid];
              };

              _proto2.getSkeletonCache = function getSkeletonCache(uuid, skeletonData) {
                var skeletonInfo = this._skeletonCache[uuid];

                if (!skeletonInfo) {
                  var skeleton = new spine$1.Skeleton(skeletonData);
                  var clipper = new spine$1.SkeletonClipping();
                  var stateData = new spine$1.AnimationStateData(skeleton.data);
                  var state = new spine$1.AnimationState(stateData);
                  var listener = new TrackEntryListeners();
                  state.addListener(listener);
                  this._skeletonCache[uuid] = skeletonInfo = {
                    skeleton: skeleton,
                    clipper: clipper,
                    state: state,
                    listener: listener,
                    animationsCache: {},
                    curAnimationCache: null
                  };
                }

                return skeletonInfo;
              };

              _proto2.getAnimationCache = function getAnimationCache(uuid, animationName) {
                var skeletonInfo = this._skeletonCache[uuid];
                if (!skeletonInfo) return null;
                var animationsCache = skeletonInfo.animationsCache;
                return animationsCache[animationName];
              };

              _proto2.invalidAnimationCache = function invalidAnimationCache(uuid) {
                var skeletonInfo = this._skeletonCache[uuid];
                var skeleton = skeletonInfo && skeletonInfo.skeleton;
                if (!skeleton) return;
                var animationsCache = skeletonInfo.animationsCache;

                for (var aniKey in animationsCache) {
                  var animationCache = animationsCache[aniKey];
                  animationCache.invalidAllFrame();
                }
              };

              _proto2.initAnimationCache = function initAnimationCache(uuid, animationName) {
                if (!animationName) return null;
                var skeletonInfo = this._skeletonCache[uuid];
                var skeleton = skeletonInfo && skeletonInfo.skeleton;
                if (!skeleton) return null;
                var animation = skeleton.data.findAnimation(animationName);

                if (!animation) {
                  return null;
                }

                var animationsCache = skeletonInfo.animationsCache;
                var animationCache = animationsCache[animationName];

                if (!animationCache) {
                  var poolKey = uuid + "#" + animationName;
                  animationCache = this._animationPool[poolKey];

                  if (animationCache) {
                    delete this._animationPool[poolKey];
                  } else {
                    animationCache = new AnimationCache();
                    animationCache._privateMode = this._privateMode;
                  }

                  animationCache.init(skeletonInfo, animationName);
                  animationsCache[animationName] = animationCache;
                }

                return animationCache;
              };

              _proto2.updateAnimationCache = function updateAnimationCache(uuid, animationName) {
                if (animationName) {
                  var animationCache = this.initAnimationCache(uuid, animationName);
                  if (!animationCache) return null;
                  animationCache.updateAllFrame();
                } else {
                  var skeletonInfo = this._skeletonCache[uuid];
                  var skeleton = skeletonInfo && skeletonInfo.skeleton;
                  if (!skeleton) return;
                  var animationsCache = skeletonInfo.animationsCache;

                  for (var aniKey in animationsCache) {
                    var _animationCache = animationsCache[aniKey];

                    _animationCache.updateAllFrame();
                  }
                }
              };

              return SkeletonCache;
            }();

            SkeletonCache.FrameTime = FrameTime;
            SkeletonCache.sharedCache = new SkeletonCache();

            var tempMat4 = new Mat4();
            var nodeScale = new Vec3();
            var AttachUtil = function () {
              function AttachUtil() {
                this._inited = false;
                this._skeleton = null;
                this._skeletonNode = null;
                this._skeletonComp = null;
                this._inited = false;
                this._skeleton = null;
                this._skeletonNode = null;
                this._skeletonComp = null;
              }

              var _proto = AttachUtil.prototype;

              _proto.init = function init(skeletonComp) {
                this._inited = true;
                this._skeleton = skeletonComp._skeleton;
                this._skeletonNode = skeletonComp.node;
                this._skeletonComp = skeletonComp;
              };

              _proto.reset = function reset() {
                this._inited = false;
                this._skeleton = null;
                this._skeletonNode = null;
                this._skeletonComp = null;
              };

              _proto._syncAttachedNode = function _syncAttachedNode() {
                if (!this._inited) return;
                var socketNodes = this._skeletonComp.socketNodes;
                if (socketNodes.size === 0) return;
                var boneInfos = null;

                var isCached = this._skeletonComp.isAnimationCached();

                if (isCached) {
                  boneInfos = this._skeletonComp._curFrame && this._skeletonComp._curFrame.boneInfos;
                } else {
                  boneInfos = this._skeleton.bones;
                }

                if (!boneInfos) return;

                var matrixHandle = function matrixHandle(node, bone) {
                  nodeScale.set(node.scale);
                  var 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;
                  node.scale = nodeScale;
                };

                for (var _iterator = _createForOfIteratorHelperLoose(socketNodes.keys()), _step; !(_step = _iterator()).done;) {
                  var boneIdx = _step.value;
                  var boneNode = socketNodes.get(boneIdx);

                  if (!boneNode || !boneNode.isValid) {
                    socketNodes["delete"](boneIdx);
                    continue;
                  }

                  var bone = boneInfos[boneIdx];

                  if (!bone) {
                    boneNode.removeFromParent();
                    boneNode.destroy();
                    socketNodes["delete"](boneIdx);
                    continue;
                  }

                  matrixHandle(boneNode, bone);
                }
              };

              return AttachUtil;
            }();

            var SkeletonTexture = function (_spine$Texture) {
              _inheritsLoose(SkeletonTexture, _spine$Texture);

              function SkeletonTexture(opt) {
                var _this;

                _this = _spine$Texture.call(this, opt) || this;
                _this.name = 'sp.SkeletonTexture';
                _this._texture = null;
                _this._material = null;
                return _this;
              }

              var _proto = SkeletonTexture.prototype;

              _proto.setRealTexture = function setRealTexture(tex) {
                this._texture = tex;
              };

              _proto.getRealTexture = function getRealTexture() {
                if (!this._texture) {
                  return null;
                }

                return this._texture instanceof ImageAsset ? this._texture._texture : this._texture;
              };

              _proto.setFilters = function setFilters(minFilter, magFilter) {
                if (this._texture) {
                  this.getRealTexture().setFilters(convertFilter(minFilter), convertFilter(magFilter));
                }
              };

              _proto.setWraps = function setWraps(uWrap, vWrap) {
                if (this._texture) {
                  this.getRealTexture().setWrapMode(convertWraps(uWrap), convertWraps(vWrap));
                }
              };

              _proto.dispose = function dispose() {};

              return SkeletonTexture;
            }(spine$1.Texture);
            function convertFilter(filter) {
              switch (filter) {
                case spine$1.TextureFilter.Nearest:
                case spine$1.TextureFilter.MipMapNearestNearest:
                case spine$1.TextureFilter.MipMapLinearNearest:
                  return Filter$1.NEAREST;

                case spine$1.TextureFilter.MipMap:
                case spine$1.TextureFilter.MipMapNearestLinear:
                case spine$1.TextureFilter.MipMapLinearLinear:
                case spine$1.TextureFilter.Linear:
                default:
                  return Filter$1.LINEAR;
              }
            }
            function convertWraps(wrap) {
              switch (wrap) {
                case spine$1.TextureWrap.MirroredRepeat:
                  return WrapMode$2.MIRRORED_REPEAT;

                case spine$1.TextureWrap.ClampToEdge:
                  return WrapMode$2.CLAMP_TO_EDGE;

                case spine$1.TextureWrap.Repeat:
                default:
                  return WrapMode$2.REPEAT;
              }
            }

            var _dec$1S, _dec2$1m, _dec3$10, _class$1V, _class2$1F, _descriptor$1t, _descriptor2$19, _descriptor3$S, _descriptor4$K, _descriptor5$B, _temp$1M;
            var SkeletonData = (_dec$1S = ccclass('sp.SkeletonData'), _dec2$1m = type([Texture2D]), _dec3$10 = type([CCString]), _dec$1S(_class$1V = (_class2$1F = (_temp$1M = function (_Asset) {
              _inheritsLoose(SkeletonData, _Asset);

              function SkeletonData() {
                var _this;

                _this = _Asset.call(this) || this;

                _initializerDefineProperty(_this, "_skeletonJson", _descriptor$1t, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "textures", _descriptor2$19, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "textureNames", _descriptor3$S, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "scale", _descriptor4$K, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_atlasText", _descriptor5$B, _assertThisInitialized(_this));

                _this._buffer = void 0;
                _this._skeletonCache = null;
                _this._atlasCache = null;
                _this._skinsEnum = null;
                _this._animsEnum = null;

                _this.reset();

                return _this;
              }

              var _proto = SkeletonData.prototype;

              _proto.createNode = function createNode(callback) {
                var node = new Node$1(this.name);
                var skeleton = node.addComponent('cc.Skeleton');
                skeleton.skeletonData = this;
                return callback(null, node);
              };

              _proto.reset = function reset() {
                this._skeletonCache = null;
                this._atlasCache = null;
              };

              _proto.resetEnums = function resetEnums() {
              };

              _proto.ensureTexturesLoaded = function ensureTexturesLoaded(loaded, caller) {
                var textures = this.textures;
                var texsLen = textures.length;

                if (texsLen === 0) {
                  if (loaded) loaded.call(caller, false);
                  return;
                }

                var loadedCount = 0;

                var loadedItem = function loadedItem() {
                  loadedCount++;

                  if (loadedCount >= texsLen) {
                    if (loaded) loaded.call(caller, true);
                    loaded = null;
                  }
                };

                for (var i = 0; i < texsLen; i++) {
                  var tex = textures[i];

                  if (tex.loaded) {
                    loadedItem();
                  } else {
                    tex.once('load', loadedItem);
                  }
                }
              };

              _proto.isTexturesLoaded = function isTexturesLoaded() {
                var textures = this.textures;
                var texsLen = textures.length;

                for (var i = 0; i < texsLen; i++) {
                  var tex = textures[i];

                  if (!tex.loaded) {
                    return false;
                  }
                }

                return true;
              };

              _proto.getRuntimeData = function getRuntimeData(quiet) {
                if (this._skeletonCache) {
                  return this._skeletonCache;
                }

                if (!(this.textures && this.textures.length > 0) && this.textureNames && this.textureNames.length > 0) {
                  if (!quiet) {
                    console.error(this.name + " no textures found!");
                  }

                  return null;
                }

                var atlas = this._getAtlas(quiet);

                if (!atlas) {
                  return null;
                }

                var attachmentLoader = new spine$1.AtlasAttachmentLoader(atlas);
                var resData = null;
                var reader = null;

                if (this.skeletonJson) {
                  reader = new spine$1.SkeletonJson(attachmentLoader);
                  resData = this.skeletonJson;
                } else {
                  reader = new spine$1.SkeletonBinary(attachmentLoader);
                  resData = new Uint8Array(this._nativeAsset);
                }

                reader.scale = this.scale;
                this._skeletonCache = reader.readSkeletonData(resData);
                atlas.dispose();
                return this._skeletonCache;
              };

              _proto.getSkinsEnum = function getSkinsEnum() {
                if (this._skinsEnum) {
                    return this._skinsEnum;
                  }

                var sd = this.getRuntimeData(true);

                if (sd) {
                  var skins = sd.skins;
                  var enumDef = {};

                  for (var i = 0; i < skins.length; i++) {
                    var name = skins[i].name;
                    enumDef[name] = i;
                  }

                  return this._skinsEnum = Enum(enumDef);
                }

                return null;
              };

              _proto.getAnimsEnum = function getAnimsEnum() {
                if (this._animsEnum && Object.keys(this._animsEnum).length > 1) {
                  return this._animsEnum;
                }

                var sd = this.getRuntimeData(true);

                if (sd) {
                  var enumDef = {
                    '<None>': 0
                  };
                  var anims = sd.animations;

                  for (var i = 0; i < anims.length; i++) {
                    var name = anims[i].name;
                    enumDef[name] = i + 1;
                  }

                  return this._animsEnum = Enum(enumDef);
                }

                return null;
              };

              _proto.destroy = function destroy() {
                SkeletonCache.sharedCache.removeSkeleton(this._uuid);
                return _Asset.prototype.destroy.call(this);
              };

              _proto._getTexture = function _getTexture(line) {
                var names = this.textureNames;

                for (var i = 0; i < names.length; i++) {
                  if (names[i] === line) {
                    var texture = this.textures[i];
                    var tex = new SkeletonTexture({
                      width: texture.width,
                      height: texture.height
                    });
                    tex.setRealTexture(texture);
                    return tex;
                  }
                }

                console.error(this.name + " no textures found!");
                return null;
              };

              _proto._getAtlas = function _getAtlas(quiet) {
                if (this._atlasCache) {
                  return this._atlasCache;
                }

                if (!this.atlasText) {
                  if (!quiet) {
                    console.error(this.name + " no atlas found!");
                  }

                  return null;
                }

                return this._atlasCache = new spine$1.TextureAtlas(this.atlasText, this._getTexture.bind(this));
              };

              _createClass(SkeletonData, [{
                key: "skeletonJsonStr",
                get: function get() {
                  if (this._skeletonJson) {
                    return JSON.stringify(this._skeletonJson);
                  }

                  return '';
                }
              }, {
                key: "skeletonJson",
                get: function get() {
                  return this._skeletonJson;
                },
                set: function set(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;
                  }
                }
              }, {
                key: "atlasText",
                get: function get() {
                  return this._atlasText;
                },
                set: function set(value) {
                  this._atlasText = value;
                  this.reset();
                }
              }, {
                key: "_nativeAsset",
                get: function get() {
                  return this._buffer;
                },
                set: function set(bin) {
                  this._buffer = bin;
                  this.reset();
                }
              }]);

              return SkeletonData;
            }(Asset), _temp$1M), (_descriptor$1t = _applyDecoratedDescriptor(_class2$1F.prototype, "_skeletonJson", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor2$19 = _applyDecoratedDescriptor(_class2$1F.prototype, "textures", [serializable, _dec2$1m], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor3$S = _applyDecoratedDescriptor(_class2$1F.prototype, "textureNames", [serializable, _dec3$10], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor4$K = _applyDecoratedDescriptor(_class2$1F.prototype, "scale", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1;
              }
            }), _descriptor5$B = _applyDecoratedDescriptor(_class2$1F.prototype, "_atlasText", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return '';
              }
            })), _class2$1F)) || _class$1V);
            legacyCC.internal.SpineSkeletonData = SkeletonData;

            var _dec$1T, _dec2$1n, _class$1W, _class2$1G, _descriptor$1u, _descriptor2$1a, _temp$1N, _dec3$11, _dec4$V, _dec5$K, _dec6$D, _dec7$A, _dec8$x, _dec9$s, _dec10$q, _dec11$o, _dec12$n, _dec13$k, _dec14$h, _dec15$h, _dec16$g, _dec17$f, _dec18$f, _dec19$f, _dec20$e, _dec21$e, _dec22$e, _dec23$e, _dec24$c, _dec25$c, _dec26$b, _dec27$9, _dec28$9, _dec29$9, _dec30$9, _class4$8, _class5$6, _descriptor3$T, _descriptor4$L, _descriptor5$C, _descriptor6$s, _descriptor7$m, _descriptor8$m, _descriptor9$i, _descriptor10$i, _descriptor11$h, _descriptor12$e, _descriptor13$a, _descriptor14$9, _descriptor15$8, _descriptor16$8, _descriptor17$6, _class6$1, _temp2$7;
            var timeScale = 1.0;
            var DefaultSkinsEnum;

            (function (DefaultSkinsEnum) {
              DefaultSkinsEnum[DefaultSkinsEnum["default"] = 0] = "default";
            })(DefaultSkinsEnum || (DefaultSkinsEnum = {}));

            ccenum(DefaultSkinsEnum);
            var DefaultAnimsEnum;

            (function (DefaultAnimsEnum) {
              DefaultAnimsEnum[DefaultAnimsEnum["<None>"] = 0] = "<None>";
            })(DefaultAnimsEnum || (DefaultAnimsEnum = {}));

            ccenum(DefaultAnimsEnum);
            var AnimationCacheMode;

            (function (AnimationCacheMode) {
              AnimationCacheMode[AnimationCacheMode["REALTIME"] = 0] = "REALTIME";
              AnimationCacheMode[AnimationCacheMode["SHARED_CACHE"] = 1] = "SHARED_CACHE";
              AnimationCacheMode[AnimationCacheMode["PRIVATE_CACHE"] = 2] = "PRIVATE_CACHE";
            })(AnimationCacheMode || (AnimationCacheMode = {}));

            ccenum(AnimationCacheMode);

            function setEnumAttr(obj, propName, enumDef) {
              CCClass.Attr.setClassAttr(obj, propName, 'type', 'Enum');
              CCClass.Attr.setClassAttr(obj, propName, 'enumList', Enum.getList(enumDef));
            }

            var SpineMaterialType;

            (function (SpineMaterialType) {
              SpineMaterialType[SpineMaterialType["COLORED_TEXTURED"] = 0] = "COLORED_TEXTURED";
              SpineMaterialType[SpineMaterialType["TWO_COLORED"] = 1] = "TWO_COLORED";
            })(SpineMaterialType || (SpineMaterialType = {}));

            var SpineSocket = (_dec$1T = ccclass('sp.Skeleton.SpineSocket'), _dec2$1n = type(Node$1), _dec$1T(_class$1W = (_class2$1G = (_temp$1N = function SpineSocket(path, target) {
              if (path === void 0) {
                path = '';
              }

              if (target === void 0) {
                target = null;
              }

              _initializerDefineProperty(this, "path", _descriptor$1u, this);

              _initializerDefineProperty(this, "target", _descriptor2$1a, this);

              this.path = path;
              this.target = target;
            }, _temp$1N), (_descriptor$1u = _applyDecoratedDescriptor(_class2$1G.prototype, "path", [serializable, editable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return '';
              }
            }), _descriptor2$1a = _applyDecoratedDescriptor(_class2$1G.prototype, "target", [_dec2$1n, editable, serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            })), _class2$1G)) || _class$1W);
            js.setClassAlias(SpineSocket, 'sp.Skeleton.SpineSocket');
            var Skeleton = (_dec3$11 = ccclass('sp.Skeleton'), _dec4$V = help(), _dec5$K = menu(), _dec6$D = type(Material), _dec7$A = displayOrder(), _dec8$x = displayName(), _dec9$s = visible(), _dec10$q = type(SkeletonData), _dec11$o = displayName(), _dec12$n = type(DefaultSkinsEnum), _dec13$k = tooltip(), _dec14$h = displayName(), _dec15$h = type(DefaultAnimsEnum), _dec16$g = tooltip(), _dec17$f = displayName(), _dec18$f = tooltip(), _dec19$f = type(AnimationCacheMode), _dec20$e = tooltip(), _dec21$e = tooltip(), _dec22$e = tooltip(), _dec23$e = tooltip(), _dec24$c = tooltip(), _dec25$c = tooltip(), _dec26$b = tooltip(), _dec27$9 = type([SpineSocket]), _dec28$9 = tooltip(), _dec29$9 = visible(), _dec30$9 = visible(), _dec3$11(_class4$8 = _dec4$V(_class4$8 = _dec5$K(_class4$8 = executeInEditMode(_class4$8 = (_class5$6 = (_temp2$7 = _class6$1 = function (_Renderable2D) {
              _inheritsLoose(Skeleton, _Renderable2D);

              function Skeleton() {
                var _this;

                _this = _Renderable2D.call(this) || this;

                _initializerDefineProperty(_this, "paused", _descriptor3$T, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "loop", _descriptor4$L, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_premultipliedAlpha", _descriptor5$C, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_timeScale", _descriptor6$s, _assertThisInitialized(_this));

                _this.enableBatch = false;
                _this._frameCache = null;
                _this._curFrame = null;
                _this._effectDelegate = null;
                _this._skeleton = void 0;
                _this._clipper = void 0;
                _this._debugRenderer = void 0;
                _this._startSlotIndex = void 0;
                _this._endSlotIndex = void 0;
                _this._startEntry = void 0;
                _this._endEntry = void 0;
                _this.attachUtil = void 0;
                _this._materialCache = {};
                _this._enumSkins = Enum({});
                _this._enumAnimations = Enum({});
                _this._accTime = 0;
                _this._playCount = 0;
                _this._skeletonCache = null;
                _this._animationName = '';
                _this._animationQueue = [];
                _this._headAniInfo = null;
                _this._playTimes = 0;
                _this._isAniComplete = true;

                _initializerDefineProperty(_this, "_useTint", _descriptor7$m, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_preCacheMode", _descriptor8$m, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_cacheMode", _descriptor9$i, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_defaultCacheMode", _descriptor10$i, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_debugBones", _descriptor11$h, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_debugSlots", _descriptor12$e, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_skeletonData", _descriptor13$a, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "defaultSkin", _descriptor14$9, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "defaultAnimation", _descriptor15$8, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_sockets", _descriptor16$8, _assertThisInitialized(_this));

                _this._meshRenderDataArray = [];

                _initializerDefineProperty(_this, "_debugMesh", _descriptor17$6, _assertThisInitialized(_this));

                _this._rootBone = void 0;
                _this._state = void 0;
                _this._listener = void 0;
                _this._socketNodes = new Map();
                _this._cachedSockets = new Map();
                _this._meshRenderDataArrayIdx = 0;
                _this._effectDelegate = null;
                _this._skeleton = null;
                _this._rootBone = null;
                _this._listener = null;
                _this._debugRenderer = null;
                _this._startSlotIndex = -1;
                _this._endSlotIndex = -1;
                _this._startEntry = {
                  animation: {
                    name: ''
                  },
                  trackIndex: 0
                };
                _this._endEntry = {
                  animation: {
                    name: ''
                  },
                  trackIndex: 0
                };
                _this.attachUtil = new AttachUtil();
                setEnumAttr(_assertThisInitialized(_this), '_defaultSkinIndex', _this._enumSkins);
                setEnumAttr(_assertThisInitialized(_this), '_animationIndex', _this._enumAnimations);
                return _this;
              }

              var _proto = Skeleton.prototype;

              _proto.disableRender = function disableRender() {
                this.destroyRenderData();
              };

              _proto.setSkeletonData = function setSkeletonData(skeletonData) {
                var uiTrans = this.node._uiProps.uiTransformComp;

                if (skeletonData.width != null && skeletonData.height != null) {
                  uiTrans.setContentSize(skeletonData.width, skeletonData.height);
                }

                {
                  if (this._cacheMode === AnimationCacheMode.SHARED_CACHE) {
                    this._skeletonCache = SkeletonCache.sharedCache;
                  } else if (this._cacheMode === AnimationCacheMode.PRIVATE_CACHE) {
                    this._skeletonCache = new SkeletonCache();

                    this._skeletonCache.enablePrivateMode();
                  }
                }

                if (this.isAnimationCached()) {
                  if (this.debugBones || this.debugSlots) {
                    warn('Debug bones or slots is invalid in cached mode');
                  }

                  var skeletonInfo = this._skeletonCache.getSkeletonCache(this.skeletonData._uuid, skeletonData);

                  this._skeleton = skeletonInfo.skeleton;
                  this._clipper = skeletonInfo.clipper;
                  this._rootBone = this._skeleton.getRootBone();
                } else {
                  this._skeleton = new spine$1.Skeleton(skeletonData);
                  this._clipper = new spine$1.SkeletonClipping();
                  this._rootBone = this._skeleton.getRootBone();
                }

                this.markForUpdateRenderData();
              };

              _proto.setSlotsRange = function setSlotsRange(startSlotIndex, endSlotIndex) {
                if (this.isAnimationCached()) {
                  warn('Slots visible range can not be modified in cached mode.');
                } else {
                  this._startSlotIndex = startSlotIndex;
                  this._endSlotIndex = endSlotIndex;
                }
              };

              _proto.setAnimationStateData = function setAnimationStateData(stateData) {
                if (this.isAnimationCached()) {
                  warn('\'setAnimationStateData\' interface can not be invoked in cached mode.');
                } else {
                  var state = new spine$1.AnimationState(stateData);

                  if (this._listener) {
                    if (this._state) {
                      this._state.removeListener(this._listener);
                    }

                    state.addListener(this._listener);
                  }

                  this._state = state;
                }
              };

              _proto.__preload = function __preload() {
                _Renderable2D.prototype.__preload.call(this);

                var children = this.node.children;

                for (var i = 0, n = children.length; i < n; i++) {
                  var child = children[i];

                  if (child && child.name === 'DEBUG_DRAW_NODE') {
                    child.destroy();
                  }
                }

                this._updateSkeletonData();

                this._updateDebugDraw();

                this._updateUseTint();

                this._indexBoneSockets();

                this._updateSocketBindings();
              };

              _proto.setAnimationCacheMode = function setAnimationCacheMode(cacheMode) {
                if (this._preCacheMode !== cacheMode) {
                  this._cacheMode = cacheMode;

                  this._updateSkeletonData();

                  this._updateUseTint();

                  this._updateSocketBindings();

                  this.markForUpdateRenderData();
                }
              };

              _proto.isAnimationCached = function isAnimationCached() {
                return this._cacheMode !== AnimationCacheMode.REALTIME;
              };

              _proto.update = function update(dt) {
                if (this.paused) return;
                dt *= this._timeScale * timeScale;

                if (this.isAnimationCached()) {
                  if (this._isAniComplete) {
                    if (this._animationQueue.length === 0 && !this._headAniInfo) {
                      var frameCache = this._frameCache;

                      if (frameCache && frameCache.isInvalid()) {
                        frameCache.updateToFrame();
                        var 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.delay) {
                      var aniInfo = this._headAniInfo;
                      this._headAniInfo = null;
                      this.setAnimation(0, aniInfo.animationName, aniInfo.loop);
                    }

                    return;
                  }

                  this._updateCache(dt);
                } else {
                  this._updateRealtime(dt);
                }
              };

              _proto.setVertexEffectDelegate = function setVertexEffectDelegate(effectDelegate) {
                this._effectDelegate = effectDelegate;
              };

              _proto.setToSetupPose = function setToSetupPose() {
                if (this._skeleton) {
                  this._skeleton.setToSetupPose();
                }
              };

              _proto.setBonesToSetupPose = function setBonesToSetupPose() {
                if (this._skeleton) {
                  this._skeleton.setBonesToSetupPose();
                }
              };

              _proto.setSlotsToSetupPose = function setSlotsToSetupPose() {
                if (this._skeleton) {
                  this._skeleton.setSlotsToSetupPose();
                }
              };

              _proto.updateAnimationCache = function updateAnimationCache(animName) {
                if (!this.isAnimationCached()) return;
                var uuid = this._skeletonData._uuid;

                if (this._skeletonCache) {
                  this._skeletonCache.updateAnimationCache(uuid, animName);
                }
              };

              _proto.invalidAnimationCache = function invalidAnimationCache() {
                if (!this.isAnimationCached()) return;

                if (this._skeletonCache) {
                  this._skeletonCache.invalidAnimationCache(this._skeletonData._uuid);
                }
              };

              _proto.findBone = function findBone(boneName) {
                if (this._skeleton) {
                  return this._skeleton.findBone(boneName);
                }

                return null;
              };

              _proto.findSlot = function findSlot(slotName) {
                if (this._skeleton) {
                  return this._skeleton.findSlot(slotName);
                }

                return null;
              };

              _proto.setSkin = function setSkin(skinName) {
                if (this._skeleton) {
                  this._skeleton.setSkinByName(skinName);

                  this._skeleton.setSlotsToSetupPose();
                }

                this.invalidAnimationCache();
              };

              _proto.getAttachment = function getAttachment(slotName, attachmentName) {
                if (this._skeleton) {
                  return this._skeleton.getAttachmentByName(slotName, attachmentName);
                }

                return null;
              };

              _proto.setAttachment = function setAttachment(slotName, attachmentName) {
                if (this._skeleton) {
                  this._skeleton.setAttachment(slotName, attachmentName);
                }

                this.invalidAnimationCache();
              };

              _proto.getTextureAtlas = function getTextureAtlas(regionAttachment) {
                return regionAttachment.region;
              };

              _proto.setMix = function setMix(fromAnimation, toAnimation, duration) {
                if (this._state) {
                  this._state.data.setMix(fromAnimation, toAnimation, duration);
                }
              };

              _proto.setAnimation = function setAnimation(trackIndex, name, loop) {
                this._playTimes = loop ? 0 : 1;
                this._animationName = name;

                if (this.isAnimationCached()) {
                  if (trackIndex !== 0) {
                    warn('Track index can not greater than 0 in cached mode.');
                  }

                  if (!this._skeletonCache) return null;

                  var cache = this._skeletonCache.getAnimationCache(this._skeletonData._uuid, name);

                  if (!cache) {
                    cache = this._skeletonCache.initAnimationCache(this._skeletonData._uuid, name);
                  }

                  if (cache) {
                    this._isAniComplete = false;
                    this._accTime = 0;
                    this._playCount = 0;
                    this._frameCache = cache;

                    if (this._socketNodes.size > 0) {
                      this._frameCache.enableCacheAttachedInfo();
                    }

                    this._frameCache.updateToFrame(0);

                    this._curFrame = this._frameCache.frames[0];
                  }
                } else if (this._skeleton) {
                  var animation = this._skeleton.data.findAnimation(name);

                  if (!animation) {
                    logID(7509, name);
                    return null;
                  }

                  var res = this._state.setAnimationWith(trackIndex, animation, loop);

                  this._state.apply(this._skeleton);

                  return res;
                }

                return null;
              };

              _proto.addAnimation = function 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: loop,
                    delay: delay
                  });
                } else if (this._skeleton) {
                  var _this$_state;

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

              _proto.findAnimation = function findAnimation(name) {
                if (this._skeleton) {
                  return this._skeleton.data.findAnimation(name);
                }

                return null;
              };

              _proto.getCurrent = function 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;
              };

              _proto.clearTracks = function clearTracks() {
                if (this.isAnimationCached()) {
                  warn('\'clearTracks\' interface can not be invoked in cached mode.');
                } else if (this._state) {
                  this._state.clearTracks();

                  this.setToSetupPose();
                }
              };

              _proto.clearTrack = function clearTrack(trackIndex) {
                if (this.isAnimationCached()) {
                  warn('\'clearTrack\' interface can not be invoked in cached mode.');
                } else if (this._state) {
                  this._state.clearTrack(trackIndex);
                }
              };

              _proto.setStartListener = function setStartListener(listener) {
                this._ensureListener();

                this._listener.start = listener;
              };

              _proto.setInterruptListener = function setInterruptListener(listener) {
                this._ensureListener();

                this._listener.interrupt = listener;
              };

              _proto.setEndListener = function setEndListener(listener) {
                this._ensureListener();

                this._listener.end = listener;
              };

              _proto.setDisposeListener = function setDisposeListener(listener) {
                this._ensureListener();

                this._listener.dispose = listener;
              };

              _proto.setCompleteListener = function setCompleteListener(listener) {
                this._ensureListener();

                this._listener.complete = listener;
              };

              _proto.setEventListener = function setEventListener(listener) {
                this._ensureListener();

                this._listener.event = listener;
              };

              _proto.setTrackStartListener = function setTrackStartListener(entry, listener) {
                TrackEntryListeners.getListeners(entry).start = listener;
              };

              _proto.setTrackInterruptListener = function setTrackInterruptListener(entry, listener) {
                TrackEntryListeners.getListeners(entry).interrupt = listener;
              };

              _proto.setTrackEndListener = function setTrackEndListener(entry, listener) {
                TrackEntryListeners.getListeners(entry).end = listener;
              };

              _proto.setTrackDisposeListener = function setTrackDisposeListener(entry, listener) {
                TrackEntryListeners.getListeners(entry).dispose = listener;
              };

              _proto.setTrackCompleteListener = function setTrackCompleteListener(entry, listener) {
                TrackEntryListeners.getListeners(entry).complete = function (trackEntry) {
                  var loopCount = Math.floor(trackEntry.trackTime / trackEntry.animationEnd);
                  listener(trackEntry, loopCount);
                };
              };

              _proto.setTrackEventListener = function setTrackEventListener(entry, listener) {
                TrackEntryListeners.getListeners(entry).event = listener;
              };

              _proto.getState = function getState() {
                return this._state;
              };

              _proto.onEnable = function onEnable() {
                _Renderable2D.prototype.onEnable.call(this);

                this._flushAssembler();
              };

              _proto.onDisable = function onDisable() {
                _Renderable2D.prototype.onDisable.call(this);
              };

              _proto.onDestroy = function onDestroy() {
                this._cleanMaterialCache();

                this.destroyRenderData();

                _Renderable2D.prototype.onDestroy.call(this);
              };

              _proto.requestMeshRenderData = function requestMeshRenderData(vertexFloatCnt) {
                if (this._meshRenderDataArray.length > 0 && this._meshRenderDataArray[this._meshRenderDataArray.length - 1].renderData.vertexCount === 0) {
                  return this._meshRenderDataArray[this._meshRenderDataArray.length - 1];
                }

                var renderData = new MeshRenderData(vertexFloatCnt);
                var comb = {
                  renderData: renderData
                };
                renderData.material = null;

                this._meshRenderDataArray.push(comb);

                return comb;
              };

              _proto.destroyRenderData = function destroyRenderData() {
                if (this._meshRenderDataArray.length > 0) {
                  this._meshRenderDataArray.forEach(function (rd) {
                    rd.renderData.reset();
                  });

                  this._meshRenderDataArray.length = 0;
                }
              };

              _proto.getMaterialForBlendAndTint = function getMaterialForBlendAndTint(src, dst, type) {
                var key = type + "/" + src + "/" + dst;
                var inst = this._materialCache[key];

                if (inst) {
                  return inst;
                }

                var material = this.customMaterial;

                if (material === null) {
                  material = builtinResMgr.get('default-spine-material');
                }

                var useTwoColor = false;

                switch (type) {
                  case SpineMaterialType.TWO_COLORED:
                    useTwoColor = true;
                    break;

                  case SpineMaterialType.COLORED_TEXTURED:
                }

                var matInfo = {
                  parent: material,
                  subModelIdx: 0,
                  owner: this
                };
                inst = new MaterialInstance(matInfo);
                this._materialCache[key] = inst;
                inst.overridePipelineStates({
                  blendState: {
                    blendColor: Color.WHITE,
                    targets: [{
                      blendEq: BlendOp.ADD,
                      blendAlphaEq: BlendOp.ADD,
                      blendSrc: src,
                      blendDst: dst,
                      blendSrcAlpha: src,
                      blendDstAlpha: dst
                    }]
                  }
                });
                inst.recompileShaders({
                  TWO_COLORED: useTwoColor
                });
                return inst;
              };

              _proto.updateMaterial = function updateMaterial() {
                if (this._customMaterial) {
                  this.setMaterial(this._customMaterial, 0);
                  this._blendHash = -1;
                  return;
                }

                var mat = this._updateBuiltinMaterial();

                this.setMaterial(mat, 0);

                this._updateBlendFunc();

                this._blendHash = -1;
              };

              _proto.querySockets = function 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 [];
              };

              _proto._render = function _render(ui) {
                if (this._meshRenderDataArray) {
                  for (var i = 0; i < this._meshRenderDataArray.length; i++) {
                    var mat = this.material;
                    this._meshRenderDataArrayIdx = i;
                    var m = this._meshRenderDataArray[i];

                    if (m.renderData.material) {
                      this.material = m.renderData.material;
                    }

                    if (m.texture) {
                      ui.commitComp(this, m.texture, this._assembler, null);
                    }

                    this.material = mat;
                  }
                }
              };

              _proto.updateWorldTransform = function updateWorldTransform() {
                if (!this.isAnimationCached()) return;

                if (this._skeleton) {
                  this._skeleton.updateWorldTransform();
                }
              };

              _proto._emitCacheCompleteEvent = function _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);
              };

              _proto._updateCache = function _updateCache(dt) {
                var frameCache = this._frameCache;

                if (!frameCache.isInited()) {
                  return;
                }

                var frames = frameCache.frames;
                var 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;
                var frameIdx = Math.floor(this._accTime / frameTime);

                if (!frameCache.isCompleted) {
                  frameCache.updateToFrame(frameIdx);
                }

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

                    this.markForUpdateRenderData();
                    return;
                  }

                  this._accTime = 0;
                  frameIdx = 0;

                  this._emitCacheCompleteEvent();
                }

                this._curFrame = frames[frameIdx];
                this.markForUpdateRenderData();
              };

              _proto._updateRealtime = function _updateRealtime(dt) {
                var skeleton = this._skeleton;
                var state = this._state;

                if (skeleton) {
                  skeleton.update(dt);

                  if (state) {
                    state.update(dt);
                    state.apply(skeleton);
                  }

                  this.markForUpdateRenderData();
                }
              };

              _proto._indexBoneSockets = function _indexBoneSockets() {
                if (!this._skeleton) {
                  return;
                }

                this._cachedSockets.clear();

                var bones = this._skeleton.bones;

                var getBoneName = function getBoneName(bone) {
                  if (bone.parent == null) return bone.data.name || '<Unamed>';
                  return getBoneName(bones[bone.parent.data.index]) + "/" + bone.data.name;
                };

                for (var i = 0, l = bones.length; i < l; i++) {
                  var bd = bones[i].data;
                  var boneName = getBoneName(bones[i]);

                  this._cachedSockets.set(boneName, bd.index);
                }
              };

              _proto._updateUseTint = function _updateUseTint() {
                this._cleanMaterialCache();

                this.destroyRenderData();
              };

              _proto._updateBatch = function _updateBatch() {
                this.markForUpdateRenderData();
              };

              _proto._validateRender = function _validateRender() {
                var skeletonData = this.skeletonData;

                if (!skeletonData || !skeletonData.isTexturesLoaded()) {
                  this.disableRender();
                }
              };

              _proto._updateAnimEnum = function _updateAnimEnum() {
                var animEnum;

                if (this.skeletonData) {
                  animEnum = this.skeletonData.getAnimsEnum();
                } else {
                  animEnum = DefaultAnimsEnum;
                }

                this._enumAnimations = Enum({});
                Object.assign(this._enumAnimations, animEnum);
                Enum.update(this._enumAnimations);
                setEnumAttr(this, '_animationIndex', this._enumAnimations);
              };

              _proto._updateSkinEnum = function _updateSkinEnum() {
                var skinEnum;

                if (this.skeletonData) {
                  skinEnum = this.skeletonData.getSkinsEnum();
                } else {
                  skinEnum = DefaultSkinsEnum;
                }

                this._enumSkins = Enum({});
                Object.assign(this._enumSkins, skinEnum);
                Enum.update(this._enumSkins);
                setEnumAttr(this, '_defaultSkinIndex', this._enumSkins);
              };

              _proto._ensureListener = function _ensureListener() {
                if (!this._listener) {
                  this._listener = new TrackEntryListeners();

                  if (this._state) {
                    this._state.addListener(this._listener);
                  }
                }
              };

              _proto._updateSkeletonData = function _updateSkeletonData() {
                if (!this.skeletonData) {
                  this.disableRender();
                  return;
                }

                var data = this.skeletonData.getRuntimeData();

                if (!data) {
                  this.disableRender();
                  return;
                }

                try {
                  this.setSkeletonData(data);

                  if (!this.isAnimationCached()) {
                    this.setAnimationStateData(new spine$1.AnimationStateData(this._skeleton.data));
                  }

                  if (this.defaultSkin) this.setSkin(this.defaultSkin);
                } catch (e) {
                  warn(e);
                }

                this.attachUtil.init(this);
                this._preCacheMode = this._cacheMode;
                this.animation = this.defaultAnimation;
              };

              _proto._refreshInspector = function _refreshInspector() {
                this._updateAnimEnum();

                this._updateSkinEnum();
              };

              _proto._updateDebugDraw = function _updateDebugDraw() {
                if (this.debugBones || this.debugSlots || this.debugMesh) {
                  if (!this._debugRenderer) {
                    var debugDrawNode = new Node$1('DEBUG_DRAW_NODE');
                    debugDrawNode.hideFlags |= CCObject.Flags.DontSave | CCObject.Flags.HideInHierarchy;
                    var debugDraw = debugDrawNode.addComponent(Graphics);
                    debugDraw.lineWidth = 1;
                    debugDraw.strokeColor = new Color(255, 0, 0, 255);
                    this._debugRenderer = debugDraw;
                    debugDrawNode.parent = this.node;
                  }

                  if (this.isAnimationCached()) {
                    warn('Debug bones or slots is invalid in cached mode');
                  }
                } else if (this._debugRenderer) {
                  this._debugRenderer.node.destroy();

                  this._debugRenderer = null;
                }
              };

              _proto._flushAssembler = function _flushAssembler() {
                var assembler = Skeleton.Assembler.getAssembler(this);

                if (this._assembler !== assembler) {
                  this._assembler = assembler;
                }

                if (this._meshRenderDataArray.length === 0) {
                  if (this._assembler && this._assembler.createData) {
                    this._assembler.createData(this);

                    this.markForUpdateRenderData();
                    this._colorDirty = true;

                    this._updateColor();
                  }
                }
              };

              _proto._updateSocketBindings = function _updateSocketBindings() {
                if (!this._skeleton) return;

                this._socketNodes.clear();

                for (var i = 0, l = this._sockets.length; i < l; i++) {
                  var socket = this._sockets[i];

                  if (socket.path && socket.target) {
                    var boneIdx = this._cachedSockets.get(socket.path);

                    if (!boneIdx) {
                      console.error("Skeleton data does not contain path " + socket.path);
                      continue;
                    }

                    this._socketNodes.set(boneIdx, socket.target);
                  }
                }
              };

              _proto._verifySockets = function _verifySockets(sockets) {
                for (var i = 0, l = sockets.length; i < l; i++) {
                  var 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;
                    }
                  }
                }

                var uniqueSocketNode = new Map();
                sockets.forEach(function (x) {
                  if (x.target) {
                    if (uniqueSocketNode.get(x.target)) {
                      console.error("Target node " + x.target.name + " has existed.");
                    } else {
                      uniqueSocketNode.set(x.target, true);
                    }
                  }
                });
              };

              _proto._cleanMaterialCache = function _cleanMaterialCache() {
                for (var val in this._materialCache) {
                  this._materialCache[val].destroy();
                }

                this._materialCache = {};
              };

              _createClass(Skeleton, [{
                key: "meshRenderDataArray",
                get: function get() {
                  return this._meshRenderDataArray;
                }
              }, {
                key: "customMaterial",
                get: function get() {
                  return this._customMaterial;
                },
                set: function set(val) {
                  this._customMaterial = val;

                  this._cleanMaterialCache();
                }
              }, {
                key: "skeletonData",
                get: function get() {
                  return this._skeletonData;
                },
                set: function set(value) {
                  if (value) value.resetEnums();

                  if (this._skeletonData !== value) {
                    this._skeletonData = value;
                    this.defaultSkin = '';
                    this.defaultAnimation = '';

                    this._updateSkeletonData();
                  }
                }
              }, {
                key: "animation",
                get: function get() {
                  if (this.isAnimationCached()) {
                    return this._animationName;
                  }

                  var entry = this.getCurrent(0);
                  return entry && entry.animation.name || '';
                },
                set: function set(value) {
                  if (value) {
                    this.setAnimation(0, value, this.loop);
                    this.destroyRenderData();
                    this.markForUpdateRenderData();
                  } else if (!this.isAnimationCached()) {
                    this.clearTrack(0);
                    this.setToSetupPose();
                  }
                }
              }, {
                key: "_defaultSkinIndex",
                get: function get() {
                  if (this.skeletonData) {
                    var skinsEnum = this.skeletonData.getSkinsEnum();

                    if (skinsEnum) {
                      if (this.defaultSkin === '') {
                        if (skinsEnum.hasOwnProperty(0)) {
                          this._defaultSkinIndex = 0;
                          return 0;
                        }
                      } else {
                        var skinIndex = skinsEnum[this.defaultSkin];

                        if (skinIndex !== undefined) {
                          return skinIndex;
                        }
                      }
                    }
                  }

                  return 0;
                },
                set: function set(value) {
                  var skinsEnum;

                  if (this.skeletonData) {
                    skinsEnum = this.skeletonData.getSkinsEnum();
                  }

                  if (!skinsEnum) {
                    console.error(this.name + " skin enums are invalid");
                    return;
                  }

                  var skinName = skinsEnum[value];

                  if (skinName !== undefined) {
                    this.defaultSkin = skinName;
                    this.setSkin(this.defaultSkin);
                  } else {
                    console.error(this.name + " skin enums are invalid");
                  }
                }
              }, {
                key: "_animationIndex",
                get: function get() {
                  var animationName =  this.animation;

                  if (this.skeletonData) {
                    if (animationName) {
                      var animsEnum = this.skeletonData.getAnimsEnum();

                      if (animsEnum) {
                        var animIndex = animsEnum[animationName];

                        if (animIndex !== undefined) {
                          return animIndex;
                        }
                      }
                    } else {
                      this._refreshInspector();
                    }
                  }

                  return 0;
                },
                set: function set(value) {
                  var animsEnum;

                  if (this.skeletonData) {
                    animsEnum = this.skeletonData.getAnimsEnum();
                  }

                  if (!animsEnum) {
                    console.error(this.name + " animation enums are invalid");
                    return;
                  }

                  var animName = animsEnum[value];

                  if (animName !== undefined) {
                    this.animation = animName;

                    {
                      this.animation = animName;
                    }
                  } else {
                    console.error(this.name + " animation enums are invalid");
                  }
                }
              }, {
                key: "defaultCacheMode",
                get: function get() {
                  return this._defaultCacheMode;
                },
                set: function set(mode) {
                  this._defaultCacheMode = mode;
                  this.setAnimationCacheMode(this._defaultCacheMode);
                }
              }, {
                key: "premultipliedAlpha",
                get: function get() {
                  return this._premultipliedAlpha;
                },
                set: function set(v) {
                  if (v !== this._premultipliedAlpha) {
                    this._premultipliedAlpha = v;
                    this.markForUpdateRenderData();
                  }
                }
              }, {
                key: "timeScale",
                get: function get() {
                  return this._timeScale;
                },
                set: function set(value) {
                  if (value !== this._timeScale) {
                    this._timeScale = value;
                  }
                }
              }, {
                key: "debugSlots",
                get: function get() {
                  return this._debugSlots;
                },
                set: function set(v) {
                  if (v !== this._debugSlots) {
                    this._debugSlots = v;

                    this._updateDebugDraw();

                    this.markForUpdateRenderData();
                  }
                }
              }, {
                key: "debugBones",
                get: function get() {
                  return this._debugBones;
                },
                set: function set(v) {
                  if (v !== this._debugBones) {
                    this._debugBones = v;

                    this._updateDebugDraw();

                    this.markForUpdateRenderData();
                  }
                }
              }, {
                key: "debugMesh",
                get: function get() {
                  return this._debugMesh;
                },
                set: function set(value) {
                  if (value !== this._debugMesh) {
                    this._debugMesh = value;

                    this._updateDebugDraw();

                    this.markForUpdateRenderData();
                  }
                }
              }, {
                key: "useTint",
                get: function get() {
                  return this._useTint;
                },
                set: function set(value) {
                  if (value !== this._useTint) {
                    this._useTint = value;

                    this._updateUseTint();

                    this.markForUpdateRenderData();
                  }
                }
              }, {
                key: "sockets",
                get: function get() {
                  return this._sockets;
                },
                set: function set(val) {

                  this._sockets = val;

                  this._updateSocketBindings();

                  this.attachUtil._syncAttachedNode();
                }
              }, {
                key: "socketNodes",
                get: function get() {
                  return this._socketNodes;
                }
              }]);

              return Skeleton;
            }(Renderable2D), _class6$1.SpineSocket = SpineSocket, _class6$1.AnimationCacheMode = AnimationCacheMode, _temp2$7), (_applyDecoratedDescriptor(_class5$6.prototype, "customMaterial", [override, _dec6$D, _dec7$A, _dec8$x], Object.getOwnPropertyDescriptor(_class5$6.prototype, "customMaterial"), _class5$6.prototype), _descriptor3$T = _applyDecoratedDescriptor(_class5$6.prototype, "paused", [_dec9$s], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _applyDecoratedDescriptor(_class5$6.prototype, "skeletonData", [editable, _dec10$q], Object.getOwnPropertyDescriptor(_class5$6.prototype, "skeletonData"), _class5$6.prototype), _applyDecoratedDescriptor(_class5$6.prototype, "_defaultSkinIndex", [_dec11$o, _dec12$n, _dec13$k], Object.getOwnPropertyDescriptor(_class5$6.prototype, "_defaultSkinIndex"), _class5$6.prototype), _applyDecoratedDescriptor(_class5$6.prototype, "_animationIndex", [_dec14$h, _dec15$h, _dec16$g], Object.getOwnPropertyDescriptor(_class5$6.prototype, "_animationIndex"), _class5$6.prototype), _applyDecoratedDescriptor(_class5$6.prototype, "defaultCacheMode", [_dec17$f, _dec18$f, editable, _dec19$f], Object.getOwnPropertyDescriptor(_class5$6.prototype, "defaultCacheMode"), _class5$6.prototype), _descriptor4$L = _applyDecoratedDescriptor(_class5$6.prototype, "loop", [serializable, _dec20$e], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _descriptor5$C = _applyDecoratedDescriptor(_class5$6.prototype, "_premultipliedAlpha", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return true;
              }
            }), _applyDecoratedDescriptor(_class5$6.prototype, "premultipliedAlpha", [editable, _dec21$e], Object.getOwnPropertyDescriptor(_class5$6.prototype, "premultipliedAlpha"), _class5$6.prototype), _descriptor6$s = _applyDecoratedDescriptor(_class5$6.prototype, "_timeScale", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1;
              }
            }), _applyDecoratedDescriptor(_class5$6.prototype, "timeScale", [_dec22$e, editable], Object.getOwnPropertyDescriptor(_class5$6.prototype, "timeScale"), _class5$6.prototype), _applyDecoratedDescriptor(_class5$6.prototype, "debugSlots", [editable, _dec23$e], Object.getOwnPropertyDescriptor(_class5$6.prototype, "debugSlots"), _class5$6.prototype), _applyDecoratedDescriptor(_class5$6.prototype, "debugBones", [editable, _dec24$c], Object.getOwnPropertyDescriptor(_class5$6.prototype, "debugBones"), _class5$6.prototype), _applyDecoratedDescriptor(_class5$6.prototype, "debugMesh", [editable, _dec25$c], Object.getOwnPropertyDescriptor(_class5$6.prototype, "debugMesh"), _class5$6.prototype), _applyDecoratedDescriptor(_class5$6.prototype, "useTint", [editable, _dec26$b], Object.getOwnPropertyDescriptor(_class5$6.prototype, "useTint"), _class5$6.prototype), _applyDecoratedDescriptor(_class5$6.prototype, "sockets", [_dec27$9, _dec28$9], Object.getOwnPropertyDescriptor(_class5$6.prototype, "sockets"), _class5$6.prototype), _descriptor7$m = _applyDecoratedDescriptor(_class5$6.prototype, "_useTint", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor8$m = _applyDecoratedDescriptor(_class5$6.prototype, "_preCacheMode", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return -1;
              }
            }), _descriptor9$i = _applyDecoratedDescriptor(_class5$6.prototype, "_cacheMode", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return AnimationCacheMode.REALTIME;
              }
            }), _descriptor10$i = _applyDecoratedDescriptor(_class5$6.prototype, "_defaultCacheMode", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return AnimationCacheMode.REALTIME;
              }
            }), _descriptor11$h = _applyDecoratedDescriptor(_class5$6.prototype, "_debugBones", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor12$e = _applyDecoratedDescriptor(_class5$6.prototype, "_debugSlots", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor13$a = _applyDecoratedDescriptor(_class5$6.prototype, "_skeletonData", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor14$9 = _applyDecoratedDescriptor(_class5$6.prototype, "defaultSkin", [serializable, _dec29$9], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return '';
              }
            }), _descriptor15$8 = _applyDecoratedDescriptor(_class5$6.prototype, "defaultAnimation", [_dec30$9, serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return '';
              }
            }), _descriptor16$8 = _applyDecoratedDescriptor(_class5$6.prototype, "_sockets", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            }), _descriptor17$6 = _applyDecoratedDescriptor(_class5$6.prototype, "_debugMesh", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            })), _class5$6)) || _class4$8) || _class4$8) || _class4$8) || _class4$8);
            legacyCC.internal.SpineSkeleton = Skeleton;

            var VertexEffectDelegate = function () {
              function VertexEffectDelegate() {
                this.name = 'sp.VertexEffectDelegate';
                this._vertexEffect = null;
                this._interpolation = null;
                this._effectType = void 0;
                this._vertexEffect = null;
                this._interpolation = null;
                this._effectType = 'none';
              }

              var _proto = VertexEffectDelegate.prototype;

              _proto.clear = function clear() {
                this._vertexEffect = null;
                this._interpolation = null;
                this._effectType = 'none';
              };

              _proto.initJitter = function initJitter(jitterX, jitterY) {
                this._effectType = 'jitter';
                this._vertexEffect = new spine$1.JitterEffect(jitterX, jitterY);
                return this._vertexEffect;
              };

              _proto.initSwirlWithPow = function initSwirlWithPow(radius, power) {
                this._interpolation = new spine$1.Pow(power);
                this._vertexEffect = new spine$1.SwirlEffect(radius, this._interpolation);
                return this._vertexEffect;
              };

              _proto.initSwirlWithPowOut = function initSwirlWithPowOut(radius, power) {
                this._interpolation = new spine$1.PowOut(power);
                this._vertexEffect = new spine$1.SwirlEffect(radius, this._interpolation);
                return this._vertexEffect;
              };

              _proto.getJitterVertexEffect = function getJitterVertexEffect() {
                return this._vertexEffect;
              };

              _proto.getSwirlVertexEffect = function getSwirlVertexEffect() {
                return this._vertexEffect;
              };

              _proto.getVertexEffect = function getVertexEffect() {
                return this._vertexEffect;
              };

              _proto.getEffectType = function getEffectType() {
                return this._effectType;
              };

              return VertexEffectDelegate;
            }();

            var FLAG_BATCH = 0x10;
            var FLAG_TWO_COLOR = 0x01;
            var _handleVal = 0x00;
            var _quadTriangles$1 = [0, 1, 2, 2, 3, 0];

            var _slotColor = new Color(0, 0, 255, 255);

            var _boneColor = new Color(255, 0, 0, 255);

            var _originColor = new Color(0, 255, 0, 255);

            var _meshColor = new Color(255, 255, 0, 255);

            var _finalColor$1 = new spine$1.Color(1, 1, 1, 1);

            var _darkColor$1 = new spine$1.Color(1, 1, 1, 1);

            var _tempPos$2 = new spine$1.Vector2();

            var _tempUv = new spine$1.Vector2();

            var _premultipliedAlpha;

            var _multiplier;

            var _slotRangeStart;

            var _slotRangeEnd;

            var _useTint;

            var _debugSlots;

            var _debugBones;

            var _debugMesh;

            var _nodeR;

            var _nodeG;

            var _nodeB;

            var _nodeA;

            var _finalColor32$1 = new Float32Array(4);

            var _darkColor32$1 = new Float32Array(4);

            var _vec3u_temp$1 = new Vec3();

            var _perVertexSize;

            var _perClipVertexSize;

            var _vertexFloatCount = 0;
            var _vertexCount = 0;
            var _vertexOffset = 0;
            var _vertexFloatOffset = 0;
            var _indexCount$1 = 0;
            var _indexOffset$1 = 0;
            var _vfOffset$2 = 0;

            var _tempr$1;

            var _tempg$1;

            var _tempb$1;

            var _inRange;

            var _mustFlush;

            var _x;

            var _y;

            var _m00;

            var _m04;

            var _m12;

            var _m01;

            var _m05;

            var _m13;

            var _r;

            var _g;

            var _b;

            var _fr;

            var _fg;

            var _fb;

            var _fa;

            var _dr;

            var _dg;

            var _db;

            var _da;

            var _comp$1;

            var _buffer;

            var _node;

            var _needColor;

            var _vertexEffect = null;
            var _currentMaterial = null;
            var _currentTexture = null;

            function _getSlotMaterial(blendMode) {
              var src;
              var dst;

              switch (blendMode) {
                case spine$1.BlendMode.Additive:
                  src = _premultipliedAlpha ? BlendFactor.ONE : BlendFactor.SRC_ALPHA;
                  dst = BlendFactor.ONE;
                  break;

                case spine$1.BlendMode.Multiply:
                  src = BlendFactor.DST_COLOR;
                  dst = BlendFactor.ONE_MINUS_SRC_ALPHA;
                  break;

                case spine$1.BlendMode.Screen:
                  src = BlendFactor.ONE;
                  dst = BlendFactor.ONE_MINUS_SRC_COLOR;
                  break;

                case spine$1.BlendMode.Normal:
                default:
                  src = _premultipliedAlpha ? BlendFactor.ONE : BlendFactor.SRC_ALPHA;
                  dst = BlendFactor.ONE_MINUS_SRC_ALPHA;
                  break;
              }

              return _comp$1.getMaterialForBlendAndTint(src, dst, _useTint ? SpineMaterialType.TWO_COLORED : SpineMaterialType.COLORED_TEXTURED);
            }

            function _handleColor(color) {
              _fa = color.fa * _nodeA;
              _multiplier = _premultipliedAlpha ? _fa / 255 : 1;
              _r = _nodeR * _multiplier;
              _g = _nodeG * _multiplier;
              _b = _nodeB * _multiplier;
              _fr = color.fr * _r;
              _fg = color.fg * _g;
              _fb = color.fb * _b;
              _finalColor32$1[0] = _fr / 255.0;
              _finalColor32$1[1] = _fg / 255.0;
              _finalColor32$1[2] = _fb / 255.0;
              _finalColor32$1[3] = _fa / 255.0;
              _dr = color.dr * _r;
              _dg = color.dg * _g;
              _db = color.db * _b;
              _da = _premultipliedAlpha ? 255 : 0;
              _darkColor32$1[0] = _dr / 255.0;
              _darkColor32$1[1] = _dg / 255.0;
              _darkColor32$1[2] = _db / 255.0;
              _darkColor32$1[3] = _da / 255.0;
            }

            var _tmpColor4 = new Float32Array(4);

            function _spineColorToFloat32Array4(spineColor) {
              _tmpColor4[0] = spineColor.r / 255.0;
              _tmpColor4[1] = spineColor.g / 255.0;
              _tmpColor4[2] = spineColor.b / 255.0;
              _tmpColor4[3] = spineColor.a / 255.0;
              return _tmpColor4;
            }

            function _vfmtFloatSize(useTint) {
              return useTint ? 3 + 2 + 4 + 4 : 3 + 2 + 4;
            }

            var simple$2 = {
              createData: function createData() {},
              updateRenderData: function updateRenderData(comp, ui) {
                _comp$1 = comp;
                var skeleton = comp._skeleton;

                if (!comp.isAnimationCached() && skeleton) {
                  skeleton.updateWorldTransform();
                }

                if (skeleton) {
                  updateComponentRenderData(comp);
                }
              },
              updateColor: function updateColor(comp) {
                if (!comp) return;
                _comp$1 = comp;

                _comp$1.markForUpdateRenderData();
              },
              fillBuffers: function fillBuffers(comp, renderer) {
                if (!comp || !comp.meshRenderDataArray) return;
                _comp$1 = comp;
                var dataArray = comp.meshRenderDataArray;
                var node = comp.node;
                var data = dataArray[comp._meshRenderDataArrayIdx];
                var renderData = data.renderData;
                var buffer = renderer.acquireBufferBatch(renderData.floatStride === 9 ? vfmtPosUvColor : vfmtPosUvTwoColor);
                var floatOffset = buffer.byteOffset >> 2;
                var indicesOffset = buffer.indicesOffset;
                var vertexOffset = buffer.vertexOffset;
                var isRecreate = buffer.request(renderData.vertexCount, renderData.indicesCount);

                if (!isRecreate) {
                  buffer = renderer.currBufferBatch;
                  floatOffset = 0;
                  indicesOffset = 0;
                  vertexOffset = 0;
                }

                var vBuf = buffer.vData;
                var iBuf = buffer.iData;
                var matrix = node.worldMatrix;
                var srcVBuf = renderData.vData;
                var srcVIdx = renderData.vertexStart;
                var srcIBuf = renderData.iData;
                var strideFloat = renderData.floatStride;
                vBuf.set(srcVBuf.subarray(srcVIdx, srcVIdx + renderData.vertexCount * strideFloat), floatOffset);

                for (var i = 0; i < renderData.vertexCount; i++) {
                  var pOffset = floatOffset + i * strideFloat;

                  _vec3u_temp$1.set(vBuf[pOffset], vBuf[pOffset + 1], vBuf[pOffset + 2]);

                  _vec3u_temp$1.transformMat4(matrix);

                  vBuf[pOffset] = _vec3u_temp$1.x;
                  vBuf[pOffset + 1] = _vec3u_temp$1.y;
                  vBuf[pOffset + 2] = _vec3u_temp$1.z;
                }

                var srcIOffset = renderData.indicesStart;

                for (var _i = 0; _i < renderData.indicesCount; _i += 1) {
                  iBuf[_i + indicesOffset] = srcIBuf[_i + srcIOffset] + vertexOffset;
                }
              }
            };

            function updateComponentRenderData(comp, ui) {
              if (!comp._skeleton) return;
              var nodeColor = comp.color;
              _nodeR = nodeColor.r / 255;
              _nodeG = nodeColor.g / 255;
              _nodeB = nodeColor.b / 255;
              _nodeA = nodeColor.a / 255;
              _useTint = comp.useTint || comp.isAnimationCached();
              _perVertexSize = _vfmtFloatSize(_useTint);
              _node = comp.node;
              comp.destroyRenderData();
              _buffer = comp.requestMeshRenderData(_perVertexSize);
              _comp$1 = comp;
              _currentMaterial = null;
              _mustFlush = true;
              _premultipliedAlpha = comp.premultipliedAlpha;
              _multiplier = 1.0;
              _handleVal = 0x00;
              _needColor = false;
              _vertexEffect = comp._effectDelegate && comp._effectDelegate._vertexEffect;

              if (nodeColor._val !== 0xffffffff || _premultipliedAlpha) {
                _needColor = true;
              }

              if (_useTint) {
                _handleVal |= FLAG_TWO_COLOR;
              }

              var worldMat;

              if (_comp$1.enableBatch) {
                worldMat = _node.worldMatrix;
                _mustFlush = false;
                _handleVal |= FLAG_BATCH;
              }

              if (comp.isAnimationCached()) {
                cacheTraverse(worldMat);
              } else {
                if (_vertexEffect) _vertexEffect.begin(comp._skeleton);
                realTimeTraverse(worldMat);
                if (_vertexEffect) _vertexEffect.end();
              }

              comp.attachUtil._syncAttachedNode();

              _node = undefined;
              _buffer = undefined;
              _comp$1 = undefined;
              _vertexEffect = null;
            }

            function fillVertices(skeletonColor, attachmentColor, slotColor, clipper, slot) {
              var vbuf = _buffer.renderData.vData;
              var ibuf = _buffer.renderData.iData;
              _finalColor$1.a = slotColor.a * attachmentColor.a * skeletonColor.a * _nodeA * 255;
              _multiplier = _premultipliedAlpha ? _finalColor$1.a : 255;
              _tempr$1 = _nodeR * attachmentColor.r * skeletonColor.r * _multiplier;
              _tempg$1 = _nodeG * attachmentColor.g * skeletonColor.g * _multiplier;
              _tempb$1 = _nodeB * attachmentColor.b * skeletonColor.b * _multiplier;
              _finalColor$1.r = _tempr$1 * slotColor.r;
              _finalColor$1.g = _tempg$1 * slotColor.g;
              _finalColor$1.b = _tempb$1 * slotColor.b;

              if (slot.darkColor == null) {
                _darkColor$1.set(0.0, 0.0, 0.0, 1.0);
              } else {
                _darkColor$1.r = slot.darkColor.r * _tempr$1;
                _darkColor$1.g = slot.darkColor.g * _tempg$1;
                _darkColor$1.b = slot.darkColor.b * _tempb$1;
              }

              _darkColor$1.a = _premultipliedAlpha ? 255 : 0;

              if (!clipper.isClipping()) {
                if (_vertexEffect) {
                  for (var v = _vertexFloatOffset, n = _vertexFloatOffset + _vertexFloatCount; v < n; v += _perVertexSize) {
                    _tempPos$2.x = vbuf[v];
                    _tempPos$2.y = vbuf[v + 1];
                    _tempUv.x = vbuf[v + 3];
                    _tempUv.y = vbuf[v + 4];

                    _vertexEffect.transform(_tempPos$2, _tempUv, _finalColor$1, _darkColor$1);

                    vbuf[v] = _tempPos$2.x;
                    vbuf[v + 1] = _tempPos$2.y;
                    vbuf[v + 3] = _tempUv.x;
                    vbuf[v + 4] = _tempUv.y;
                    vbuf.set(_spineColorToFloat32Array4(_finalColor$1), v + 5);

                    if (_useTint) {
                      vbuf.set(_spineColorToFloat32Array4(_darkColor$1), v + 9);
                    }
                  }
                } else {
                  _finalColor32$1.set(_spineColorToFloat32Array4(_finalColor$1));

                  _darkColor32$1.set(_spineColorToFloat32Array4(_darkColor$1));

                  for (var _v = _vertexFloatOffset, _n = _vertexFloatOffset + _vertexFloatCount; _v < _n; _v += _perVertexSize) {
                    vbuf.set(_finalColor32$1, _v + 5);

                    if (_useTint) {
                      vbuf.set(_darkColor32$1, _v + 9);
                    }
                  }
                }
              } else {
                _perClipVertexSize = _useTint ? 12 : 8;
                var vertices = vbuf.subarray(_vertexFloatOffset);
                var uvs = vbuf.subarray(_vertexFloatOffset + 3);
                clipper.clipTriangles(vertices, _vertexFloatCount, ibuf.subarray(_indexOffset$1), _indexCount$1, uvs, _finalColor$1, _darkColor$1, _useTint, _perVertexSize);
                var clippedVertices = new Float32Array(clipper.clippedVertices);
                var clippedTriangles = clipper.clippedTriangles;
                _indexCount$1 = clippedTriangles.length;
                _vertexFloatCount = clippedVertices.length / _perClipVertexSize * _perVertexSize;

                _buffer.renderData.reserve(_vertexFloatCount / _perVertexSize, _indexCount$1);

                _indexOffset$1 = _buffer.renderData.indicesCount;
                _vertexOffset = _buffer.renderData.vertexCount;
                _vertexFloatOffset = _buffer.renderData.vDataOffset;
                vbuf = _buffer.renderData.vData;
                ibuf = _buffer.renderData.iData;

                if (clippedTriangles.length > 0) {
                  ibuf.set(clippedTriangles, _indexOffset$1);
                }

                if (_vertexEffect) {
                  for (var _v2 = 0, _n2 = clippedVertices.length, offset = _vertexFloatOffset; _v2 < _n2; _v2 += _perClipVertexSize, offset += _perVertexSize) {
                    _tempPos$2.x = clippedVertices[_v2];
                    _tempPos$2.y = clippedVertices[_v2 + 1];

                    _finalColor$1.set(clippedVertices[_v2 + 2], clippedVertices[_v2 + 3], clippedVertices[_v2 + 4], clippedVertices[_v2 + 5]);

                    _tempUv.x = clippedVertices[_v2 + 6];
                    _tempUv.y = clippedVertices[_v2 + 7];

                    if (_useTint) {
                      _darkColor$1.set(clippedVertices[_v2 + 8], clippedVertices[_v2 + 9], clippedVertices[_v2 + 10], clippedVertices[_v2 + 11]);
                    } else {
                      _darkColor$1.set(0, 0, 0, 0);
                    }

                    _vertexEffect.transform(_tempPos$2, _tempUv, _finalColor$1, _darkColor$1);

                    vbuf[offset] = _tempPos$2.x;
                    vbuf[offset + 1] = _tempPos$2.y;
                    vbuf[offset + 3] = _tempUv.x;
                    vbuf[offset + 4] = _tempUv.y;
                    vbuf.set(_spineColorToFloat32Array4(_finalColor$1), offset + 5);

                    if (_useTint) {
                      vbuf.set(_spineColorToFloat32Array4(_darkColor$1), offset + 9);
                    }
                  }
                } else {
                  for (var _v3 = 0, _n3 = clippedVertices.length, _offset = _vertexFloatOffset; _v3 < _n3; _v3 += _perClipVertexSize, _offset += _perVertexSize) {
                    vbuf[_offset] = clippedVertices[_v3];
                    vbuf[_offset + 1] = clippedVertices[_v3 + 1];
                    vbuf[_offset + 3] = clippedVertices[_v3 + 6];
                    vbuf[_offset + 4] = clippedVertices[_v3 + 7];
                    vbuf[_offset + 5] = clippedVertices[_v3 + 2] / 255.0;
                    vbuf[_offset + 6] = clippedVertices[_v3 + 3] / 255.0;
                    vbuf[_offset + 7] = clippedVertices[_v3 + 4] / 255.0;
                    vbuf[_offset + 8] = clippedVertices[_v3 + 5] / 255.0;

                    if (_useTint) {
                      vbuf[_offset + 9] = clippedVertices[_v3 + 8] / 255.0;
                      vbuf[_offset + 10] = clippedVertices[_v3 + 9] / 255.0;
                      vbuf[_offset + 11] = clippedVertices[_v3 + 10] / 255.0;
                      vbuf[_offset + 12] = clippedVertices[_v3 + 11] / 255.0;
                    }
                  }
                }
              }
            }

            function realTimeTraverse(worldMat) {
              var vbuf;
              var ibuf;
              var locSkeleton = _comp$1._skeleton;
              var skeletonColor = locSkeleton.color;
              var graphics = _comp$1._debugRenderer;
              var clipper = _comp$1._clipper;
              var material = null;
              var attachment;
              var uvs;
              var triangles;
              var isRegion;
              var isMesh;
              var isClip;
              var slot;
              _slotRangeStart = _comp$1._startSlotIndex;
              _slotRangeEnd = _comp$1._endSlotIndex;
              _inRange = false;
              if (_slotRangeStart === -1) _inRange = true;
              _debugSlots = _comp$1.debugSlots;
              _debugBones = _comp$1.debugBones;
              _debugMesh = _comp$1.debugMesh;

              if (graphics && (_debugBones || _debugSlots || _debugMesh)) {
                graphics.clear();
                graphics.lineWidth = 5;
              }

              _perClipVertexSize = 12;
              _vertexFloatCount = 0;
              _vertexOffset = 0;
              _vertexFloatOffset = 0;
              _indexCount$1 = 0;
              _indexOffset$1 = 0;

              for (var slotIdx = 0, slotCount = locSkeleton.drawOrder.length; slotIdx < slotCount; slotIdx++) {
                var _buffer2;

                slot = locSkeleton.drawOrder[slotIdx];

                if (slot === undefined) {
                  continue;
                }

                if (_slotRangeStart >= 0 && _slotRangeStart === slot.data.index) {
                  _inRange = true;
                }

                if (!_inRange) {
                  clipper.clipEndWithSlot(slot);
                  continue;
                }

                if (_slotRangeEnd >= 0 && _slotRangeEnd === slot.data.index) {
                  _inRange = false;
                }

                _vertexFloatCount = 0;
                _indexCount$1 = 0;
                attachment = slot.getAttachment();

                if (!attachment) {
                  clipper.clipEndWithSlot(slot);
                  continue;
                }

                isRegion = attachment instanceof spine$1.RegionAttachment;
                isMesh = attachment instanceof spine$1.MeshAttachment;
                isClip = attachment instanceof spine$1.ClippingAttachment;

                if (isClip) {
                  clipper.clipStart(slot, attachment);
                  continue;
                }

                if (!isRegion && !isMesh) {
                  clipper.clipEndWithSlot(slot);
                  continue;
                }

                var texture = attachment.region.texture.getRealTexture();
                material = _getSlotMaterial(slot.data.blendMode);

                if (!material) {
                  clipper.clipEndWithSlot(slot);
                  continue;
                }

                if (!_currentMaterial) _currentMaterial = material;
                if (!((_buffer2 = _buffer) === null || _buffer2 === void 0 ? void 0 : _buffer2.renderData.material)) _buffer.renderData.material = _currentMaterial;

                if (_mustFlush || material.hash !== _currentMaterial.hash || texture && _currentTexture !== texture) {
                  _mustFlush = false;
                  _buffer = _comp$1.requestMeshRenderData(_perVertexSize);
                  _currentMaterial = material;
                  _currentTexture = texture;
                  _buffer.texture = texture;
                  _buffer.renderData.material = _currentMaterial;
                }

                if (isRegion) {
                  triangles = _quadTriangles$1;
                  _vertexFloatCount = 4 * _perVertexSize;
                  _indexCount$1 = 6;

                  _buffer.renderData.reserve(4, 6);

                  _indexOffset$1 = _buffer.renderData.indicesCount;
                  _vertexOffset = _buffer.renderData.vertexCount;
                  _vertexFloatOffset = _buffer.renderData.vDataOffset;
                  vbuf = _buffer.renderData.vData;
                  ibuf = _buffer.renderData.iData;
                  attachment.computeWorldVertices(slot.bone, vbuf, _vertexFloatOffset, _perVertexSize);

                  if (graphics && _debugSlots) {
                    graphics.strokeColor = _slotColor;
                    graphics.moveTo(vbuf[_vertexFloatOffset], vbuf[_vertexFloatOffset + 1]);

                    for (var ii = _vertexFloatOffset + _perVertexSize, nn = _vertexFloatOffset + _vertexFloatCount; ii < nn; ii += _perVertexSize) {
                      graphics.lineTo(vbuf[ii], vbuf[ii + 1]);
                    }

                    graphics.close();
                    graphics.stroke();
                  }
                } else if (isMesh) {
                  var mattachment = attachment;
                  triangles = mattachment.triangles;
                  _vertexFloatCount = (mattachment.worldVerticesLength >> 1) * _perVertexSize;
                  _indexCount$1 = triangles.length;

                  _buffer.renderData.reserve(mattachment.worldVerticesLength >> 1, _indexCount$1);

                  _indexOffset$1 = _buffer.renderData.indicesCount;
                  _vertexOffset = _buffer.renderData.vertexCount;
                  _vertexFloatOffset = _buffer.renderData.vDataOffset;
                  vbuf = _buffer.renderData.vData;
                  ibuf = _buffer.renderData.iData;
                  mattachment.computeWorldVertices(slot, 0, mattachment.worldVerticesLength, vbuf, _vertexFloatOffset, _perVertexSize);

                  if (graphics && _debugMesh) {
                    graphics.strokeColor = _meshColor;

                    for (var _ii = 0, _nn = triangles.length; _ii < _nn; _ii += 3) {
                      var v1 = triangles[_ii] * _perVertexSize + _vertexFloatOffset;
                      var v2 = triangles[_ii + 1] * _perVertexSize + _vertexFloatOffset;
                      var v3 = triangles[_ii + 2] * _perVertexSize + _vertexFloatOffset;
                      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 (_vertexFloatCount === 0 || _indexCount$1 === 0) {
                  clipper.clipEndWithSlot(slot);
                  continue;
                }

                var meshAttachment = attachment;
                ibuf.set(triangles, _indexOffset$1);
                uvs = meshAttachment.uvs;

                for (var v = _vertexFloatOffset, n = _vertexFloatOffset + _vertexFloatCount, u = 0; v < n; v += _perVertexSize, u += 2) {
                  vbuf[v + 3] = uvs[u];
                  vbuf[v + 4] = uvs[u + 1];
                }

                fillVertices(skeletonColor, meshAttachment.color, slot.color, clipper, slot);
                vbuf = _buffer.renderData.vData;
                ibuf = _buffer.renderData.iData;

                if (_indexCount$1 > 0) {
                  for (var _ii2 = _indexOffset$1, _nn2 = _indexOffset$1 + _indexCount$1; _ii2 < _nn2; _ii2++) {
                    ibuf[_ii2] += _vertexOffset;
                  }

                  if (worldMat) {
                    _m00 = worldMat.m00;
                    _m04 = worldMat.m04;
                    _m12 = worldMat.m12;
                    _m01 = worldMat.m01;
                    _m05 = worldMat.m05;
                    _m13 = worldMat.m13;

                    for (var _ii3 = _vertexFloatOffset, _nn3 = _vertexFloatOffset + _vertexFloatCount; _ii3 < _nn3; _ii3 += _perVertexSize) {
                      _x = vbuf[_ii3];
                      _y = vbuf[_ii3 + 1];
                      vbuf[_ii3] = _x * _m00 + _y * _m04 + _m12;
                      vbuf[_ii3 + 1] = _x * _m01 + _y * _m05 + _m13;
                    }
                  }

                  _buffer.renderData.advance(_vertexFloatCount / _perVertexSize, _indexCount$1);
                }

                clipper.clipEndWithSlot(slot);
              }

              clipper.clipEnd();

              if (graphics && _debugBones) {
                var bone;
                graphics.strokeColor = _boneColor;
                graphics.fillColor = _slotColor;

                for (var i = 0, _n4 = locSkeleton.bones.length; i < _n4; i++) {
                  bone = locSkeleton.bones[i];
                  var x = bone.data.length * bone.a + bone.worldX;
                  var 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(worldMat) {
              var frame = _comp$1._curFrame;
              if (!frame) return;
              var segments = frame.segments;
              if (segments.length === 0) return;
              _perClipVertexSize = 12;
              var vbuf;
              var ibuf;
              var material = null;
              var vertices = frame.vertices;
              var indices = frame.indices;
              var frameVFOffset = 0;
              var frameIndexOffset = 0;
              var segVFCount = 0;

              if (worldMat) {
                _m00 = worldMat.m00;
                _m01 = worldMat.m01;
                _m04 = worldMat.m04;
                _m05 = worldMat.m05;
                _m12 = worldMat.m12;
                _m13 = worldMat.m13;
              }

              var justTranslate = _m00 === 1 && _m01 === 0 && _m04 === 0 && _m05 === 1;
              var needBatch = _handleVal & FLAG_BATCH;
              var calcTranslate = needBatch && justTranslate;
              var colorOffset = 0;
              var colors = frame.colors;
              var nowColor = colors[colorOffset++];
              var maxVFOffset = nowColor.vfOffset;

              _handleColor(nowColor);

              for (var i = 0, n = segments.length; i < n; i++) {
                var segInfo = segments[i];
                material = _getSlotMaterial(segInfo.blendMode);
                if (!material) continue;
                if (!_currentMaterial) _currentMaterial = material;
                if (!_currentTexture) _currentTexture = segInfo.tex;
                if (_buffer.renderData.material) _buffer.renderData.material = _currentMaterial;

                if (_mustFlush || material.hash !== _currentMaterial.hash || segInfo.tex && segInfo.tex !== _currentTexture) {
                  _mustFlush = false;

                  if (!_buffer.texture) {
                    _buffer.texture = segInfo.tex;
                  }

                  _buffer = _comp$1.requestMeshRenderData(_vfmtFloatSize(_useTint));
                  _currentMaterial = material;
                  _currentTexture = segInfo.tex;
                  _buffer.texture = segInfo.tex;
                  _buffer.renderData.material = _currentMaterial;
                }

                _vertexCount = segInfo.vertexCount;
                _indexCount$1 = segInfo.indexCount;

                _buffer.renderData.reserve(_vertexCount, _indexCount$1);

                _indexOffset$1 = _buffer.renderData.indicesCount;
                _vertexOffset = _buffer.renderData.vertexCount;
                _vfOffset$2 = _buffer.renderData.vDataOffset;
                vbuf = _buffer.renderData.vData;
                ibuf = _buffer.renderData.iData;

                for (var ii = _indexOffset$1, il = _indexOffset$1 + _indexCount$1; ii < il; ii++) {
                  ibuf[ii] = _vertexOffset + indices[frameIndexOffset++];
                }

                segVFCount = segInfo.vfCount;
                var subArray = vertices.subarray(frameVFOffset, frameVFOffset + segVFCount);
                frameVFOffset += segVFCount;
                var floatOffset = _vfOffset$2;
                _perVertexSize = _vfmtFloatSize(_useTint);

                for (var _ii4 = 0; _ii4 < subArray.length;) {
                  vbuf[floatOffset + 0] = subArray[_ii4 + 0];
                  vbuf[floatOffset + 1] = subArray[_ii4 + 1];
                  vbuf[floatOffset + 3] = subArray[_ii4 + 3];
                  vbuf[floatOffset + 4] = subArray[_ii4 + 4];
                  vbuf[floatOffset + 5] = subArray[_ii4 + 5];
                  vbuf[floatOffset + 6] = subArray[_ii4 + 6];
                  vbuf[floatOffset + 7] = subArray[_ii4 + 7];
                  vbuf[floatOffset + 8] = subArray[_ii4 + 8];

                  if (_useTint) {
                    vbuf[floatOffset + 9] = subArray[_ii4 + 9];
                    vbuf[floatOffset + 10] = subArray[_ii4 + 10];
                    vbuf[floatOffset + 11] = subArray[_ii4 + 11];
                    vbuf[floatOffset + 12] = subArray[_ii4 + 12];
                  }

                  floatOffset += _perVertexSize;
                  _ii4 += 13;
                }

                if (calcTranslate) {
                  for (var _ii5 = _vfOffset$2, _il = _vfOffset$2 + segVFCount; _ii5 < _il; _ii5 += _perVertexSize) {
                    vbuf[_ii5] += _m12;
                    vbuf[_ii5 + 1] += _m13;
                  }
                } else if (needBatch) {
                  for (var _ii6 = _vfOffset$2, _il2 = _vfOffset$2 + segVFCount; _ii6 < _il2; _ii6 += _perVertexSize) {
                    _x = vbuf[_ii6];
                    _y = vbuf[_ii6 + 1];
                    vbuf[_ii6] = _x * _m00 + _y * _m04 + _m12;
                    vbuf[_ii6 + 1] = _x * _m01 + _y * _m05 + _m13;
                  }
                }

                _buffer.renderData.advance(_vertexCount, _indexCount$1);

                if (!_needColor) continue;
                var frameColorOffset = frameVFOffset - segVFCount;

                for (var _ii7 = _vfOffset$2, iEnd = _vfOffset$2 + segVFCount; _ii7 < iEnd; _ii7 += _perVertexSize, frameColorOffset += 6) {
                  if (frameColorOffset >= maxVFOffset) {
                    nowColor = colors[colorOffset++];

                    _handleColor(nowColor);

                    maxVFOffset = nowColor.vfOffset;
                  }

                  vbuf.set(_finalColor32$1, _ii7 + 5);
                  vbuf.set(_darkColor32$1, _ii7 + 9);
                }
              }
            }

            legacyCC.internal.SpineAssembler = simple$2;

            var simpleSpineAssembler = {
              getAssembler: function getAssembler() {
                return simple$2;
              }
            };
            Skeleton.Assembler = simpleSpineAssembler;

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

            var index$3 = /*#__PURE__*/Object.freeze({
                __proto__: null,
                spine: spine$1,
                get ATTACHMENT_TYPE () { return ATTACHMENT_TYPE; },
                get AnimationEventType () { return AnimationEventType; },
                timeScale: timeScale,
                get DefaultSkinsEnum () { return DefaultSkinsEnum; },
                get DefaultAnimsEnum () { return DefaultAnimsEnum; },
                get AnimationCacheMode () { return AnimationCacheMode; },
                get SpineMaterialType () { return SpineMaterialType; },
                SpineSocket: SpineSocket,
                Skeleton: Skeleton,
                SkeletonData: SkeletonData,
                SkeletonTexture: SkeletonTexture,
                convertFilter: convertFilter,
                convertWraps: convertWraps,
                VertexEffectDelegate: VertexEffectDelegate,
                simpleSpineAssembler: simpleSpineAssembler
            });
            exports('sp', index$3);

            var __extends$1=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 __());};}();var dragonBones={};(function(dragonBones){})(dragonBones||(dragonBones={}));(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 get(){return this._clock;},enumerable:true,configurable:true});Object.defineProperty(DragonBones.prototype,"eventManager",{get:function get(){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||(dragonBones={}));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$1=function __extends(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||(dragonBones={}));(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||(dragonBones={}));(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||(dragonBones={}));(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||(dragonBones={}));(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||(dragonBones={}));(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||(dragonBones={}));(function(dragonBones){var UserData=function(_super){__extends$1(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$1(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||(dragonBones={}));(function(dragonBones){var DragonBonesData=function(_super){__extends$1(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||(dragonBones={}));(function(dragonBones){var ArmatureData=function(_super){__extends$1(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$1(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$1(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$1(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||(dragonBones={}));(function(dragonBones){var ConstraintData=function(_super){__extends$1(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$1(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$1(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||(dragonBones={}));(function(dragonBones){var CanvasData=function(_super){__extends$1(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||(dragonBones={}));(function(dragonBones){var SkinData=function(_super){__extends$1(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||(dragonBones={}));(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$1(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$1(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$1(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$1(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$1(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$1(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$1(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||(dragonBones={}));(function(dragonBones){var BoundingBoxData=function(_super){__extends$1(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$1(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$1(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$1(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||(dragonBones={}));(function(dragonBones){var AnimationData=function(_super){__extends$1(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$1(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||(dragonBones={}));(function(dragonBones){var AnimationConfig=function(_super){__extends$1(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||(dragonBones={}));(function(dragonBones){var TextureAtlasData=function(_super){__extends$1(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$1(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||(dragonBones={}));(function(dragonBones){var DeformVertices=function(_super){__extends$1(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||(dragonBones={}));(function(dragonBones_1){var Armature=function(_super){__extends$1(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 get(){return this._flipX;},set:function set(value){if(this._flipX===value){return;}this._flipX=value;this.invalidUpdate();},enumerable:true,configurable:true});Object.defineProperty(Armature.prototype,"flipY",{get:function get(){return this._flipY;},set:function set(value){if(this._flipY===value){return;}this._flipY=value;this.invalidUpdate();},enumerable:true,configurable:true});Object.defineProperty(Armature.prototype,"cacheFrameRate",{get:function get(){return this._armatureData.cacheFrameRate;},set:function set(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 get(){return this._armatureData.name;},enumerable:true,configurable:true});Object.defineProperty(Armature.prototype,"armatureData",{get:function get(){return this._armatureData;},enumerable:true,configurable:true});Object.defineProperty(Armature.prototype,"animation",{get:function get(){return this._animation;},enumerable:true,configurable:true});Object.defineProperty(Armature.prototype,"proxy",{get:function get(){return this._proxy;},enumerable:true,configurable:true});Object.defineProperty(Armature.prototype,"eventDispatcher",{get:function get(){return this._proxy;},enumerable:true,configurable:true});Object.defineProperty(Armature.prototype,"display",{get:function get(){return this._display;},enumerable:true,configurable:true});Object.defineProperty(Armature.prototype,"replacedTexture",{get:function get(){return this._replacedTexture;},set:function set(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 get(){return this._clock;},set:function set(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 get(){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||(dragonBones={}));(function(dragonBones){var TransformObject=function(_super){__extends$1(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 get(){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||(dragonBones={}));(function(dragonBones){var Bone=function(_super){__extends$1(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 get(){return this._boneData;},enumerable:true,configurable:true});Object.defineProperty(Bone.prototype,"visible",{get:function get(){return this._visible;},set:function set(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 get(){return this._boneData.name;},enumerable:true,configurable:true});Object.defineProperty(Bone.prototype,"parent",{get:function get(){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 get(){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||(dragonBones={}));(function(dragonBones){var Surface=function(_super){__extends$1(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||(dragonBones={}));(function(dragonBones){var Slot=function(_super){__extends$1(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 get(){return this._visible;},set:function set(value){if(this._visible===value){return;}this._visible=value;this._updateVisible();},enumerable:true,configurable:true});Object.defineProperty(Slot.prototype,"displayIndex",{get:function get(){return this._displayIndex;},set:function set(value){if(this._setDisplayIndex(value)){this.update(-1);}},enumerable:true,configurable:true});Object.defineProperty(Slot.prototype,"name",{get:function get(){return this._slotData.name;},enumerable:true,configurable:true});Object.defineProperty(Slot.prototype,"displayList",{get:function get(){return this._displayList.concat();},set:function set(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 get(){return this._slotData;},enumerable:true,configurable:true});Object.defineProperty(Slot.prototype,"rawDisplayDatas",{get:function get(){return this._rawDisplayDatas;},set:function set(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 get(){return this._displayData;},enumerable:true,configurable:true});Object.defineProperty(Slot.prototype,"boundingBoxData",{get:function get(){return this._boundingBoxData;},enumerable:true,configurable:true});Object.defineProperty(Slot.prototype,"rawDisplay",{get:function get(){return this._rawDisplay;},enumerable:true,configurable:true});Object.defineProperty(Slot.prototype,"meshDisplay",{get:function get(){return this._meshDisplay;},enumerable:true,configurable:true});Object.defineProperty(Slot.prototype,"display",{get:function get(){return this._display;},set:function set(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 get(){return this._childArmature;},set:function set(value){if(this._childArmature===value){return;}this.display=value;},enumerable:true,configurable:true});Object.defineProperty(Slot.prototype,"parent",{get:function get(){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||(dragonBones={}));(function(dragonBones){var Constraint=function(_super){__extends$1(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 get(){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$1(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$1(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||(dragonBones={}));(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 get(){return this._clock;},set:function set(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||(dragonBones={}));(function(dragonBones){var Animation=function(_super){__extends$1(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 get(){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 get(){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 get(){return this._lastAnimationState!==null?this._lastAnimationState.name:"";},enumerable:true,configurable:true});Object.defineProperty(Animation.prototype,"animationNames",{get:function get(){return this._animationNames;},enumerable:true,configurable:true});Object.defineProperty(Animation.prototype,"animations",{get:function get(){return this._animations;},set:function set(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 get(){this._animationConfig.clear();return this._animationConfig;},enumerable:true,configurable:true});Object.defineProperty(Animation.prototype,"lastAnimationState",{get:function get(){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 get(){console.warn("Deprecated.");return this._animationNames;},enumerable:true,configurable:true});Object.defineProperty(Animation.prototype,"animationDataList",{get:function get(){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||(dragonBones={}));(function(dragonBones){var AnimationState=function(_super){__extends$1(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 get(){return this._fadeState<0;},enumerable:true,configurable:true});Object.defineProperty(AnimationState.prototype,"isFadeOut",{get:function get(){return this._fadeState>0;},enumerable:true,configurable:true});Object.defineProperty(AnimationState.prototype,"isFadeComplete",{get:function get(){return this._fadeState===0;},enumerable:true,configurable:true});Object.defineProperty(AnimationState.prototype,"isPlaying",{get:function get(){return (this._playheadState&2)!==0&&this._actionTimeline.playState<=0;},enumerable:true,configurable:true});Object.defineProperty(AnimationState.prototype,"isCompleted",{get:function get(){return this._actionTimeline.playState>0;},enumerable:true,configurable:true});Object.defineProperty(AnimationState.prototype,"currentPlayTimes",{get:function get(){return this._actionTimeline.currentPlayTimes;},enumerable:true,configurable:true});Object.defineProperty(AnimationState.prototype,"totalTime",{get:function get(){return this._duration;},enumerable:true,configurable:true});Object.defineProperty(AnimationState.prototype,"currentTime",{get:function get(){return this._actionTimeline.currentTime;},set:function set(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 get(){return this._animationData;},enumerable:true,configurable:true});return AnimationState;}(dragonBones.BaseObject);dragonBones.AnimationState=AnimationState;var BonePose=function(_super){__extends$1(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||(dragonBones={}));(function(dragonBones){var TimelineState=function(_super){__extends$1(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$1(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$1(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$1(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$1(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||(dragonBones={}));(function(dragonBones){var ActionTimelineState=function(_super){__extends$1(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$1(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$1(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$1(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$1(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$1(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$1(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$1(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$1(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$1(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$1(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$1(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||(dragonBones={}));(function(dragonBones){var EventObject=function(_super){__extends$1(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||(dragonBones={}));(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||(dragonBones={}));(function(dragonBones){var ObjectDataParser=function(_super){__extends$1(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%Int16Array.BYTES_PER_ELEMENT!==0){this._intArray.push(0);}if(this._frameIntArray.length%Int16Array.BYTES_PER_ELEMENT!==0){this._frameIntArray.push(0);}if(this._frameArray.length%Int16Array.BYTES_PER_ELEMENT!==0){this._frameArray.push(0);}if(this._timelineArray.length%Uint16Array.BYTES_PER_ELEMENT!==0){this._timelineArray.push(0);}var l1=this._intArray.length*Int16Array.BYTES_PER_ELEMENT;var l2=this._floatArray.length*Float32Array.BYTES_PER_ELEMENT;var l3=this._frameIntArray.length*Int16Array.BYTES_PER_ELEMENT;var l4=this._frameFloatArray.length*Float32Array.BYTES_PER_ELEMENT;var l5=this._frameArray.length*Int16Array.BYTES_PER_ELEMENT;var l6=this._timelineArray.length*Uint16Array.BYTES_PER_ELEMENT;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||(dragonBones={}));(function(dragonBones){var BinaryDataParser=function(_super){__extends$1(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/Int16Array.BYTES_PER_ELEMENT);var floatArray=new Float32Array(this._binary,this._binaryOffset+offsets[2],l2/Float32Array.BYTES_PER_ELEMENT);var frameIntArray=new Int16Array(this._binary,this._binaryOffset+offsets[4],l3/Int16Array.BYTES_PER_ELEMENT);var frameFloatArray=new Float32Array(this._binary,this._binaryOffset+offsets[6],l4/Float32Array.BYTES_PER_ELEMENT);var frameArray=new Int16Array(this._binary,this._binaryOffset+offsets[8],l5/Int16Array.BYTES_PER_ELEMENT);var timelineArray=new Uint16Array(this._binary,this._binaryOffset+offsets[10],l6/Uint16Array.BYTES_PER_ELEMENT);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/Uint8Array.BYTES_PER_ELEMENT);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||(dragonBones={}));(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 get(){return this._dragonBones.clock;},enumerable:true,configurable:true});Object.defineProperty(BaseFactory.prototype,"dragonBones",{get:function get(){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||(dragonBones={}));(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||(dragonBones={}));var DragonBones=dragonBones.DragonBones;var BaseObject=dragonBones.BaseObject;var Matrix=dragonBones.Matrix;var Transform=dragonBones.Transform;var ColorTransform=dragonBones.ColorTransform;var Point$2=dragonBones.Point;var Rectangle=dragonBones.Rectangle;var UserData=dragonBones.UserData;var ActionData=dragonBones.ActionData;var DragonBonesData=dragonBones.DragonBonesData;var ArmatureData=dragonBones.ArmatureData;var BoneData=dragonBones.BoneData;var SurfaceData=dragonBones.SurfaceData;var SlotData=dragonBones.SlotData;var ConstraintData=dragonBones.ConstraintData;var IKConstraintData=dragonBones.IKConstraintData;var PathConstraintData=dragonBones.PathConstraintData;var CanvasData=dragonBones.CanvasData;var SkinData=dragonBones.SkinData;var VerticesData=dragonBones.VerticesData;var DisplayData=dragonBones.DisplayData;var ImageDisplayData=dragonBones.ImageDisplayData;var ArmatureDisplayData=dragonBones.ArmatureDisplayData;var MeshDisplayData=dragonBones.MeshDisplayData;var BoundingBoxDisplayData=dragonBones.BoundingBoxDisplayData;var PathDisplayData=dragonBones.PathDisplayData;var WeightData=dragonBones.WeightData;var BoundingBoxData=dragonBones.BoundingBoxData;var RectangleBoundingBoxData=dragonBones.RectangleBoundingBoxData;var EllipseBoundingBoxData=dragonBones.EllipseBoundingBoxData;var PolygonBoundingBoxData=dragonBones.PolygonBoundingBoxData;var AnimationData=dragonBones.AnimationData;var TimelineData=dragonBones.TimelineData;var AnimationConfig=dragonBones.AnimationConfig;var TextureAtlasData=dragonBones.TextureAtlasData;var TextureData=dragonBones.TextureData;var DeformVertices=dragonBones.DeformVertices;var Armature=dragonBones.Armature;var TransformObject=dragonBones.TransformObject;var Bone=dragonBones.Bone;var Surface=dragonBones.Surface;var Slot=dragonBones.Slot;var Constraint$1=dragonBones.Constraint;var IKConstraint=dragonBones.IKConstraint;var PathConstraint=dragonBones.PathConstraint;var WorldClock=dragonBones.WorldClock;var Animation$1=dragonBones.Animation;var AnimationState$1=dragonBones.AnimationState;var BonePose=dragonBones.BonePose;var BlendState$1=dragonBones.BlendState;var TimelineState=dragonBones.TimelineState;var TweenTimelineState=dragonBones.TweenTimelineState;var BoneTimelineState=dragonBones.BoneTimelineState;var SlotTimelineState=dragonBones.SlotTimelineState;var ConstraintTimelineState=dragonBones.ConstraintTimelineState;var ActionTimelineState=dragonBones.ActionTimelineState;var ZOrderTimelineState=dragonBones.ZOrderTimelineState;var BoneAllTimelineState=dragonBones.BoneAllTimelineState;var BoneTranslateTimelineState=dragonBones.BoneTranslateTimelineState;var BoneRotateTimelineState=dragonBones.BoneRotateTimelineState;var BoneScaleTimelineState=dragonBones.BoneScaleTimelineState;var SurfaceTimelineState=dragonBones.SurfaceTimelineState;var SlotDislayTimelineState=dragonBones.SlotDislayTimelineState;var SlotColorTimelineState=dragonBones.SlotColorTimelineState;var DeformTimelineState=dragonBones.DeformTimelineState;var IKConstraintTimelineState=dragonBones.IKConstraintTimelineState;var AnimationTimelineState=dragonBones.AnimationTimelineState;var EventObject=dragonBones.EventObject;var DataParser=dragonBones.DataParser;var ObjectDataParser=dragonBones.ObjectDataParser;var ActionFrame=dragonBones.ActionFrame;var BinaryDataParser=dragonBones.BinaryDataParser;var BaseFactory=dragonBones.BaseFactory;var BuildArmaturePackage=dragonBones.BuildArmaturePackage;var BinaryOffset=dragonBones.BinaryOffset;var ArmatureType=dragonBones.ArmatureType;var BoneType=dragonBones.BoneType;var DisplayType=dragonBones.DisplayType;var BoundingBoxType=dragonBones.BoundingBoxType;var ActionType=dragonBones.ActionType;var BlendMode=dragonBones.BlendMode;var TweenType=dragonBones.TweenType;var TimelineType=dragonBones.TimelineType;

            var _dec$1U, _class$1X, _temp$1O, _dec2$1o, _class3$I, _temp2$8;
            var CCTextureAtlasData = (_dec$1U = ccclass('dragonBones.CCTextureAtlasData'), _dec$1U(_class$1X = (_temp$1O = function (_TextureAtlasData) {
              _inheritsLoose(CCTextureAtlasData, _TextureAtlasData);

              function CCTextureAtlasData() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _TextureAtlasData.call.apply(_TextureAtlasData, [this].concat(args)) || this;
                _this._renderTexture = null;
                return _this;
              }

              CCTextureAtlasData.toString = function toString() {
                return '[class dragonBones.CCTextureAtlasData]';
              };

              var _proto = CCTextureAtlasData.prototype;

              _proto.createTexture = function createTexture() {
                return BaseObject.borrowObject(CCTextureData);
              };

              _proto._onClear = function _onClear() {
                _TextureAtlasData.prototype._onClear.call(this);

                this.renderTexture = null;
              };

              _createClass(CCTextureAtlasData, [{
                key: "renderTexture",
                get: function get() {
                  return this._renderTexture;
                },
                set: function set(value) {
                  this._renderTexture = value;

                  if (value) {
                    for (var k in this.textures) {
                      var textureData = this.textures[k];

                      if (!textureData.spriteFrame) {
                        var rect = null;

                        if (textureData.rotated) {
                          rect = new Rect(textureData.region.x, textureData.region.y, textureData.region.height, textureData.region.width);
                        } else {
                          rect = new Rect(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 (var _k in this.textures) {
                      var _textureData = this.textures[_k];
                      _textureData.spriteFrame = null;
                    }
                  }
                }
              }]);

              return CCTextureAtlasData;
            }(TextureAtlasData), _temp$1O)) || _class$1X);
            var CCTextureData = (_dec2$1o = ccclass('dragonBones.CCTextureData'), _dec2$1o(_class3$I = (_temp2$8 = function (_TextureData) {
              _inheritsLoose(CCTextureData, _TextureData);

              function CCTextureData() {
                var _this2;

                for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
                  args[_key3] = arguments[_key3];
                }

                _this2 = _TextureData.call.apply(_TextureData, [this].concat(args)) || this;
                _this2.spriteFrame = null;
                return _this2;
              }

              CCTextureData.toString = function toString() {
                return '[class dragonBones.CCTextureData]';
              };

              var _proto2 = CCTextureData.prototype;

              _proto2._onClear = function _onClear() {
                _TextureData.prototype._onClear.call(this);

                this.spriteFrame = null;
              };

              return CCTextureData;
            }(TextureData), _temp2$8)) || _class3$I);

            var _dec$1V, _class$1Y, _temp$1P;
            var CCSlot = (_dec$1V = ccclass('dragonBones.CCSlot'), _dec$1V(_class$1Y = (_temp$1P = function (_Slot) {
              _inheritsLoose(CCSlot, _Slot);

              CCSlot.toString = function toString() {
                return '[class dragonBones.CCSlot]';
              };

              function CCSlot() {
                var _this;

                _this = _Slot.call(this) || this;
                _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();
                return _this;
              }

              var _proto = CCSlot.prototype;

              _proto.getTexture = function getTexture() {
                if (this._textureData) {
                  var sp = this._textureData.spriteFrame;
                  var tex = sp.texture instanceof ImageAsset ? sp.texture._texture : sp.texture;
                  return tex;
                }

                return null;
              };

              _proto.calculWorldMatrix = function calculWorldMatrix() {
                var parent = this._armature._parent;

                if (parent) {
                  this._mulMat(this._worldMatrix, parent._worldMatrix, this._matrix);
                } else {
                  Mat4.copy(this._worldMatrix, this._matrix);
                }

                this._worldMatrixDirty = false;
              };

              _proto._onClear = function _onClear() {
                _Slot.prototype._onClear.call(this);

                this._localVertices.length = 0;
                this._indices.length = 0;
                Mat4.identity(this._matrix);
                Mat4.identity(this._worldMatrix);
                this._worldMatrixDirty = true;
                this._color = new Color();
                this._visible = false;
              };

              _proto._onUpdateDisplay = function _onUpdateDisplay() {};

              _proto._initDisplay = function _initDisplay(value) {};

              _proto._addDisplay = function _addDisplay() {
                this._visible = true;
              };

              _proto._replaceDisplay = function _replaceDisplay(value) {};

              _proto._removeDisplay = function _removeDisplay() {
                this._visible = false;
              };

              _proto._disposeDisplay = function _disposeDisplay(object) {};

              _proto._updateVisible = function _updateVisible() {
                this._visible = this.parent.visible;
              };

              _proto._updateGlueMesh = function _updateGlueMesh() {};

              _proto._updateZOrder = function _updateZOrder() {};

              _proto._updateBlendMode = function _updateBlendMode() {
                if (this._childArmature) {
                  var childSlots = this._childArmature.getSlots();

                  for (var i = 0, l = childSlots.length; i < l; i++) {
                    var slot = childSlots[i];
                    slot._blendMode = this._blendMode;

                    slot._updateBlendMode();
                  }
                }
              };

              _proto._updateColor = function _updateColor() {
                var 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;
              };

              _proto._updateFrame = function _updateFrame() {
                this._indices.length = 0;
                var indices = this._indices;
                var localVertices = this._localVertices;
                var indexOffset = 0;
                var vfOffset = 0;
                var currentTextureData = this._textureData;
                if (!this._display || this._displayIndex < 0 || !currentTextureData || !currentTextureData.spriteFrame) return;
                var texture = currentTextureData.spriteFrame.texture;
                var textureAtlasWidth = texture.width;
                var textureAtlasHeight = texture.height;
                var region = currentTextureData.region;

                if (textureAtlasWidth === 0 || textureAtlasHeight === 0) {
                  console.error("SpriteFrame " + currentTextureData.spriteFrame.name + " incorrect size " + textureAtlasWidth + " x " + textureAtlasHeight);
                  return;
                }

                var currentVerticesData = this._deformVertices !== null && this._display === this._meshDisplay ? this._deformVertices.verticesData : null;

                if (currentVerticesData) {
                  var data = currentVerticesData.data;
                  var intArray = data.intArray;
                  var floatArray = data.floatArray;
                  var vertexCount = intArray[currentVerticesData.offset + BinaryOffset.MeshVertexCount];
                  var triangleCount = intArray[currentVerticesData.offset + BinaryOffset.MeshTriangleCount];
                  var vertexOffset = intArray[currentVerticesData.offset + BinaryOffset.MeshFloatOffset];

                  if (vertexOffset < 0) {
                    vertexOffset += 65536;
                  }

                  var uvOffset = vertexOffset + vertexCount * 2;
                  var scale = this._armature._armatureData.scale;

                  for (var 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 (var _i = 0; _i < triangleCount * 3; ++_i) {
                    indices[indexOffset++] = intArray[currentVerticesData.offset + BinaryOffset.MeshVertexIndices + _i];
                  }

                  localVertices.length = vfOffset;
                  indices.length = indexOffset;
                  var isSkinned = !!currentVerticesData.weight;

                  if (isSkinned) {
                    this._identityTransform();
                  }
                } else {
                  var _l = region.x / textureAtlasWidth;

                  var b = (region.y + region.height) / textureAtlasHeight;
                  var r = (region.x + region.width) / textureAtlasWidth;
                  var 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;
              };

              _proto._updateMesh = function _updateMesh() {
                var scale = this._armature._armatureData.scale;
                var deformVertices = this._deformVertices.vertices;
                var bones = this._deformVertices.bones;
                var verticesData = this._deformVertices.verticesData;
                var weightData = verticesData.weight;
                var hasDeform = deformVertices.length > 0 && verticesData.inheritDeform;
                var localVertices = this._localVertices;

                if (weightData) {
                  var data = verticesData.data;
                  var intArray = data.intArray;
                  var floatArray = data.floatArray;
                  var vertexCount = intArray[verticesData.offset + BinaryOffset.MeshVertexCount];
                  var weightFloatOffset = intArray[weightData.offset + BinaryOffset.WeigthFloatOffset];

                  if (weightFloatOffset < 0) {
                    weightFloatOffset += 65536;
                  }

                  for (var i = 0, iB = weightData.offset + BinaryOffset.WeigthBoneIndices + bones.length, iV = weightFloatOffset, iF = 0, lvi = 0; i < vertexCount; i++, lvi += 4) {
                    var boneCount = intArray[iB++];
                    var xG = 0.0;
                    var yG = 0.0;

                    for (var j = 0; j < boneCount; ++j) {
                      var boneIndex = intArray[iB++];
                      var bone = bones[boneIndex];

                      if (bone !== null) {
                        var matrix = bone.globalTransformMatrix;
                        var weight = floatArray[iV++];
                        var xL = floatArray[iV++] * scale;
                        var 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) {
                  var isSurface = this._parent._boneData.type !== BoneType.Bone;
                  var _data = verticesData.data;
                  var _intArray = _data.intArray;
                  var _floatArray = _data.floatArray;
                  var _vertexCount = _intArray[verticesData.offset + BinaryOffset.MeshVertexCount];
                  var vertexOffset = _intArray[verticesData.offset + BinaryOffset.MeshFloatOffset];

                  if (vertexOffset < 0) {
                    vertexOffset += 65536;
                  }

                  for (var _i2 = 0, l = _vertexCount, _lvi = 0; _i2 < l; _i2++, _lvi += 4) {
                    var x = _floatArray[vertexOffset + _i2 * 2] * scale + deformVertices[_i2 * 2];
                    var y = _floatArray[vertexOffset + _i2 * 2 + 1] * scale + deformVertices[_i2 * 2 + 1];

                    if (isSurface) {
                      var _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();
                }
              };

              _proto._identityTransform = function _identityTransform() {
                var 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;
              };

              _proto._updateTransform = function _updateTransform() {
                var 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;
              };

              _proto.updateWorldMatrix = function updateWorldMatrix() {
                if (!this._armature) return;
                var parentSlot = this._armature._parent;

                if (parentSlot) {
                  parentSlot.updateWorldMatrix();
                }

                if (this._worldMatrixDirty) {
                  this.calculWorldMatrix();
                  var childArmature = this.childArmature;
                  if (!childArmature) return;
                  var slots = childArmature.getSlots();

                  for (var i = 0, n = slots.length; i < n; i++) {
                    var slot = slots[i];

                    if (slot) {
                      slot._worldMatrixDirty = true;
                    }
                  }
                }
              };

              _proto._mulMat = function _mulMat(out, a, b) {
                var aa = a.m00;
                var ab = a.m01;
                var ac = a.m04;
                var ad = a.m05;
                var atx = a.m12;
                var aty = a.m13;
                var ba = b.m00;
                var bb = b.m01;
                var bc = b.m04;
                var bd = b.m05;
                var btx = b.m12;
                var 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;
                }
              };

              return CCSlot;
            }(Slot), _temp$1P)) || _class$1Y);

            var _dec$1W, _class$1Z, _temp$1Q;
            var CCArmatureDisplay = (_dec$1W = ccclass('dragonBones.CCArmatureDisplay'), _dec$1W(_class$1Z = (_temp$1Q = function (_DisplayData) {
              _inheritsLoose(CCArmatureDisplay, _DisplayData);

              function CCArmatureDisplay() {
                var _this;

                _this = _DisplayData.call(this) || this;
                _this.shouldAdvanced = false;
                _this._ccNode = null;
                _this._ccComponent = null;
                _this._eventTarget = void 0;
                _this._armature = null;
                _this._eventTarget = new EventTarget();
                return _this;
              }

              var _proto = CCArmatureDisplay.prototype;

              _proto.hasEvent = function hasEvent(type) {
                console.warn('Method not implemented.');
                return false;
              };

              _proto.addEvent = function addEvent(type, listener, thisObject) {
                console.warn('Method not implemented.');
              };

              _proto.removeEvent = function removeEvent(type, listener, thisObject) {
                console.warn('Method not implemented.');
              };

              _proto.setEventTarget = function setEventTarget(eventTarget) {
                this._eventTarget = eventTarget;
              };

              _proto.getRootDisplay = function getRootDisplay() {
                var parentSlot = this._armature._parent;

                if (!parentSlot) {
                  return this;
                }

                var slot;

                while (parentSlot) {
                  slot = parentSlot;
                  parentSlot = parentSlot._armature._parent;
                }

                return slot._armature.display;
              };

              _proto.convertToRootSpace = function convertToRootSpace(pos) {
                var slot = this._armature._parent;

                if (!slot) {
                  return pos;
                }

                slot.updateWorldMatrix();
                var worldMatrix = slot._worldMatrix;
                var 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;
              };

              _proto.convertToWorldSpace = function convertToWorldSpace(point) {
                var _ccNode$_uiProps$uiTr;

                var newPos = this.convertToRootSpace(point);
                var 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);
              };

              _proto.getRootNode = function getRootNode() {
                var rootDisplay = this.getRootDisplay();
                return rootDisplay && rootDisplay._ccNode;
              };

              _proto.dbInit = function dbInit(armature) {
                this._armature = armature;
              };

              _proto.dbClear = function dbClear() {
                this._armature = null;
              };

              _proto.dbUpdate = function dbUpdate() {
                if (this._ccComponent) {
                  this._ccComponent.markForUpdateRenderData();
                }
              };

              _proto.advanceTimeBySelf = function advanceTimeBySelf(on) {
                this.shouldAdvanced = !!on;
              };

              _proto.hasDBEventListener = function hasDBEventListener(type) {
                return this._eventTarget.hasEventListener(type);
              };

              _proto.addDBEventListener = function addDBEventListener(type, listener, target) {
                this._eventTarget.on(type, listener, target);
              };

              _proto.removeDBEventListener = function removeDBEventListener(type, listener, target) {
                this._eventTarget.off(type, listener, target);
              };

              _proto.dispatchDBEvent = function dispatchDBEvent(type, eventObject) {
                this._eventTarget.emit(type, eventObject);
              };

              _createClass(CCArmatureDisplay, [{
                key: "node",
                get: function get() {
                  return this;
                }
              }]);

              return CCArmatureDisplay;
            }(DisplayData), _temp$1Q)) || _class$1Z);

            var _dec$1X, _class$1_, _class2$1H, _temp$1R;
            var CCFactory = (_dec$1X = ccclass('CCFactory'), _dec$1X(_class$1_ = (_temp$1R = _class2$1H = function (_BaseFactory) {
              _inheritsLoose(CCFactory, _BaseFactory);

              CCFactory.getInstance = function getInstance() {
                if (!CCFactory._factory) {
                  CCFactory._factory = new CCFactory();
                }

                return CCFactory._factory;
              };

              function CCFactory() {
                var _this;

                _this = _BaseFactory.call(this) || this;
                _this.id = void 0;
                _this.uuid = void 0;
                _this._slots = void 0;
                var eventManager = new CCArmatureDisplay();
                _this._dragonBones = new DragonBones(eventManager);

                if ( director.getScheduler()) {
                  game.on(Game.EVENT_RESTART, _this.initUpdate, _assertThisInitialized(_this));

                  _this.initUpdate();
                }

                _this.id = _this.uuid = 'CCFactory';
                return _this;
              }

              var _proto = CCFactory.prototype;

              _proto.initUpdate = function initUpdate(dt) {
                Scheduler.enableForTarget(this);
                director.getScheduler().scheduleUpdate(this, Scheduler.PRIORITY_SYSTEM, false);
              };

              _proto.update = function update(dt) {
                this._dragonBones.advanceTime(dt);
              };

              _proto.getDragonBonesDataByRawData = function getDragonBonesDataByRawData(rawData) {
                var dataParser = rawData instanceof ArrayBuffer ? BaseFactory._binaryParser : this._dataParser;
                return dataParser.parseDragonBonesData(rawData, 1.0);
              };

              _proto.buildArmatureDisplay = function buildArmatureDisplay(armatureName, dragonBonesName, skinName, textureAtlasName) {
                var armature = this.buildArmature(armatureName, dragonBonesName, skinName, textureAtlasName);
                return armature ? armature._display : null;
              };

              _proto.createArmatureNode = function createArmatureNode(comp, armatureName, node) {
                node = node || new Node$1();
                var 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;
              };

              _proto._buildTextureAtlasData = function _buildTextureAtlasData(textureAtlasData, textureAtlas) {
                if (textureAtlasData) {
                  textureAtlasData.renderTexture = textureAtlas;
                } else {
                  textureAtlasData = BaseObject.borrowObject(CCTextureAtlasData);
                }

                return textureAtlasData;
              };

              _proto._sortSlots = function _sortSlots() {
                var slots = this._slots;
                var sortedSlots = [];

                for (var i = 0, l = slots.length; i < l; i++) {
                  var slot = slots[i];
                  var zOrder = slot._zOrder;
                  var inserted = false;

                  for (var j = sortedSlots.length - 1; j >= 0; j--) {
                    if (zOrder >= sortedSlots[j]._zOrder) {
                      sortedSlots.splice(j + 1, 0, slot);
                      inserted = true;
                      break;
                    }
                  }

                  if (!inserted) {
                    sortedSlots.splice(0, 0, slot);
                  }
                }

                this._slots = sortedSlots;
              };

              _proto._buildArmature = function _buildArmature(dataPackage) {
                var armature = BaseObject.borrowObject(Armature);
                armature._skinData = dataPackage.skin;
                armature._animation = BaseObject.borrowObject(Animation$1);
                armature._animation._armature = armature;
                armature._animation.animations = dataPackage.armature.animations;
                armature._isChildArmature = false;
                var display = new CCArmatureDisplay();
                armature.init(dataPackage.armature, display, display, this._dragonBones);
                return armature;
              };

              _proto._buildSlot = function _buildSlot(dataPackage, slotData, displays) {
                var slot = BaseObject.borrowObject(CCSlot);
                var display = slot;
                slot.init(slotData, displays, display, display);
                return slot;
              };

              _proto.getDragonBonesDataByUUID = function getDragonBonesDataByUUID(uuid) {
                for (var name in this._dragonBonesDataMap) {
                  if (name.indexOf(uuid) !== -1) {
                    return this._dragonBonesDataMap[name];
                  }
                }

                return null;
              };

              _proto.removeDragonBonesDataByUUID = function removeDragonBonesDataByUUID(uuid, disposeData) {
                if (disposeData === undefined) {
                  disposeData = true;
                }

                for (var name in this._dragonBonesDataMap) {
                  if (name.indexOf(uuid) === -1) continue;

                  if (disposeData) {
                    this._dragonBones.bufferObject(this._dragonBonesDataMap[name]);
                  }

                  delete this._dragonBonesDataMap[name];
                }
              };

              return CCFactory;
            }(BaseFactory), _class2$1H._factory = null, _temp$1R)) || _class$1_);

            var MaxCacheTime$1 = 30;
            var FrameTime$1 = 1 / 60;
            var _vertices$2 = [];
            var _indices$1 = [];
            var _boneInfoOffset$1 = 0;
            var _indexOffset$2 = 0;
            var _vfOffset$3 = 0;
            var _preTexUrl$1 = null;
            var _preBlendMode$1 = null;
            var _segVCount$1 = 0;
            var _segICount$1 = 0;
            var _segOffset$1 = 0;
            var _colorOffset$1 = 0;
            var _preColor = 0;

            var _x$1;

            var _y$1;

            var AnimationCache$1 = function () {
              function AnimationCache() {
                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;
              }

              var _proto = AnimationCache.prototype;

              _proto.init = function init(armatureInfo, animationName) {
                this._inited = true;
                this._armatureInfo = armatureInfo;
                this._animationName = animationName;
              };

              _proto.clear = function clear() {
                this._inited = false;

                for (var i = 0, n = this.frames.length; i < n; i++) {
                  var frame = this.frames[i];
                  frame.segments.length = 0;
                }

                this.invalidAllFrame();
              };

              _proto.begin = function begin() {
                if (!this._invalid) return;
                var armatureInfo = this._armatureInfo;
                var curAnimationCache = armatureInfo.curAnimationCache;

                if (curAnimationCache && curAnimationCache !== this) {
                  if (this._privateMode) {
                    curAnimationCache.invalidAllFrame();
                  } else {
                    curAnimationCache.updateToFrame();
                  }
                }

                var armature = armatureInfo.armature;
                var animation = armature.animation;
                animation.play(this._animationName, 1);
                armatureInfo.curAnimationCache = this;
                this._invalid = false;
                this._frameIdx = -1;
                this.totalTime = 0;
                this.isCompleted = false;
              };

              _proto.end = function end() {
                if (!this._needToUpdate()) {
                  this._armatureInfo.curAnimationCache = null;
                  this.frames.length = this._frameIdx + 1;
                  this.isCompleted = true;
                }
              };

              _proto._needToUpdate = function _needToUpdate(toFrameIdx) {
                var armatureInfo = this._armatureInfo;
                var armature = armatureInfo.armature;
                var animation = armature.animation;
                return !animation.isCompleted && this.totalTime < MaxCacheTime$1 && (toFrameIdx === undefined || this._frameIdx < toFrameIdx);
              };

              _proto.updateToFrame = function updateToFrame(toFrameIdx) {
                if (!this._inited) return;
                this.begin();
                if (!this._needToUpdate(toFrameIdx)) return;
                var armatureInfo = this._armatureInfo;
                var 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();
              };

              _proto.isInited = function isInited() {
                return this._inited;
              };

              _proto.isInvalid = function isInvalid() {
                return this._invalid;
              };

              _proto.invalidAllFrame = function invalidAllFrame() {
                this.isCompleted = false;
                this._invalid = true;
              };

              _proto.updateAllFrame = function updateAllFrame() {
                this.invalidAllFrame();
                this.updateToFrame();
              };

              _proto.enableCacheAttachedInfo = function enableCacheAttachedInfo() {
                if (!this._enableCacheAttachedInfo) {
                  this._enableCacheAttachedInfo = true;
                  this.invalidAllFrame();
                }
              };

              _proto._updateFrame = function _updateFrame(armature, index) {
                _vfOffset$3 = 0;
                _boneInfoOffset$1 = 0;
                _indexOffset$2 = 0;
                _preTexUrl$1 = null;
                _preBlendMode$1 = null;
                _segVCount$1 = 0;
                _segICount$1 = 0;
                _segOffset$1 = 0;
                _colorOffset$1 = 0;
                _preColor = 0;
                this.frames[index] = this.frames[index] || {
                  segments: [],
                  colors: [],
                  boneInfos: [],
                  vertices: null,
                  uintVert: null,
                  indices: null
                };
                var frame = this.frames[index];
                var segments = this._tempSegments = frame.segments;
                var colors = this._tempColors = frame.colors;
                var boneInfos = this._tempBoneInfos = frame.boneInfos;

                this._traverseArmature(armature, 1.0);

                if (_colorOffset$1 > 0) {
                  colors[_colorOffset$1 - 1].vfOffset = _vfOffset$3;
                }

                colors.length = _colorOffset$1;
                boneInfos.length = _boneInfoOffset$1;
                var preSegOffset = _segOffset$1 - 1;

                if (preSegOffset >= 0) {
                  if (_segICount$1 > 0) {
                    var preSegInfo = segments[preSegOffset];
                    preSegInfo.indexCount = _segICount$1;
                    preSegInfo.vfCount = _segVCount$1 * 5;
                    preSegInfo.vertexCount = _segVCount$1;
                    segments.length = _segOffset$1;
                  } else {
                    segments.length = _segOffset$1 - 1;
                  }
                }

                if (segments.length === 0) return;
                var vertices = frame.vertices;
                var uintVert = frame.uintVert;

                if (!vertices || vertices.length < _vfOffset$3) {
                  vertices = frame.vertices = new Float32Array(_vfOffset$3);
                  uintVert = frame.uintVert = new Uint32Array(vertices.buffer);
                }

                for (var i = 0, j = 0; i < _vfOffset$3;) {
                  vertices[i++] = _vertices$2[j++];
                  vertices[i++] = _vertices$2[j++];
                  vertices[i++] = _vertices$2[j++];
                  vertices[i++] = _vertices$2[j++];
                  uintVert[i++] = _vertices$2[j++];
                }

                var indices = frame.indices;

                if (!indices || indices.length < _indexOffset$2) {
                  indices = frame.indices = new Uint16Array(_indexOffset$2);
                }

                for (var _i = 0; _i < _indexOffset$2; _i++) {
                  indices[_i] = _indices$1[_i];
                }

                frame.vertices = vertices;
                frame.uintVert = uintVert;
                frame.indices = indices;
              };

              _proto._traverseArmature = function _traverseArmature(armature, parentOpacity) {
                var colors = this._tempColors;
                var segments = this._tempSegments;
                var boneInfos = this._tempBoneInfos;
                var gVertices = _vertices$2;
                var gIndices = _indices$1;
                var slots = armature._slots;
                var slotVertices;
                var slotIndices;
                var slot;
                var slotMatrix;
                var slotColor;
                var colorVal;
                var texture;
                var preSegOffset;
                var preSegInfo;
                var bones = armature._bones;

                if (this._enableCacheAttachedInfo) {
                  for (var i = 0, l = bones.length; i < l; i++, _boneInfoOffset$1++) {
                    var bone = bones[i];
                    var boneInfo = boneInfos[_boneInfoOffset$1];

                    if (!boneInfo) {
                      boneInfo = boneInfos[_boneInfoOffset$1] = {
                        globalTransformMatrix: new Matrix()
                      };
                    }

                    var boneMat = bone.globalTransformMatrix;
                    var cacheBoneMat = boneInfo.globalTransformMatrix;
                    cacheBoneMat.copyFrom(boneMat);
                  }
                }

                for (var _i2 = 0, _l = slots.length; _i2 < _l; _i2++) {
                  slot = slots[_i2];
                  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$1 !== texture.nativeUrl || _preBlendMode$1 !== slot._blendMode) {
                    _preTexUrl$1 = texture.nativeUrl;
                    _preBlendMode$1 = slot._blendMode;
                    preSegOffset = _segOffset$1 - 1;

                    if (preSegOffset >= 0) {
                      if (_segICount$1 > 0) {
                        preSegInfo = segments[preSegOffset];
                        preSegInfo.indexCount = _segICount$1;
                        preSegInfo.vertexCount = _segVCount$1;
                        preSegInfo.vfCount = _segVCount$1 * 5;
                      } else {
                        _segOffset$1--;
                      }
                    }

                    segments[_segOffset$1] = {
                      tex: texture,
                      blendMode: slot._blendMode,
                      indexCount: 0,
                      vertexCount: 0,
                      vfCount: 0
                    };
                    _segOffset$1++;
                    _segICount$1 = 0;
                    _segVCount$1 = 0;
                  }

                  colorVal = (slotColor.a * parentOpacity << 24 >>> 0) + (slotColor.b << 16) + (slotColor.g << 8) + slotColor.r;

                  if (_preColor !== colorVal) {
                    _preColor = colorVal;

                    if (_colorOffset$1 > 0) {
                      colors[_colorOffset$1 - 1].vfOffset = _vfOffset$3;
                    }

                    colors[_colorOffset$1++] = {
                      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 (var j = 0, vl = slotVertices.length; j < vl;) {
                    _x$1 = slotVertices[j++];
                    _y$1 = slotVertices[j++];
                    gVertices[_vfOffset$3++] = _x$1 * slotMatrix.m00 + _y$1 * slotMatrix.m04 + slotMatrix.m12;
                    gVertices[_vfOffset$3++] = _x$1 * slotMatrix.m01 + _y$1 * slotMatrix.m05 + slotMatrix.m13;
                    gVertices[_vfOffset$3++] = slotVertices[j++];
                    gVertices[_vfOffset$3++] = slotVertices[j++];
                    gVertices[_vfOffset$3++] = colorVal;
                  }

                  for (var ii = 0, il = slotIndices.length; ii < il; ii++) {
                    gIndices[_indexOffset$2++] = _segVCount$1 + slotIndices[ii];
                  }
                  _segICount$1 += slotIndices.length;
                  _segVCount$1 += slotVertices.length / 4;
                }
              };

              return AnimationCache;
            }();
            var ArmatureCache = function () {
              function ArmatureCache() {
                this._privateMode = false;
                this._animationPool = {};
                this._armatureCache = {};
              }

              var _proto2 = ArmatureCache.prototype;

              _proto2.enablePrivateMode = function enablePrivateMode() {
                this._privateMode = true;
              };

              _proto2.dispose = function dispose() {
                for (var _key in this._armatureCache) {
                  var armatureInfo = this._armatureCache[_key];

                  if (armatureInfo) {
                    var armature = armatureInfo.armature;
                    if (armature) armature.dispose();
                  }
                }

                this._armatureCache = {};
                this._animationPool = {};
              };

              _proto2._removeArmature = function _removeArmature(armatureKey) {
                var armatureInfo = this._armatureCache[armatureKey];
                var animationsCache = armatureInfo.animationsCache;

                for (var aniKey in animationsCache) {
                  var animationCache = animationsCache[aniKey];
                  if (!animationCache) continue;
                  this._animationPool[armatureKey + "#" + aniKey] = animationCache;
                  animationCache.clear();
                }

                var armature = armatureInfo.armature;
                if (armature) armature.dispose();
                delete this._armatureCache[armatureKey];
              };

              _proto2.resetArmature = function resetArmature(uuid) {
                for (var armatureKey in this._armatureCache) {
                  if (armatureKey.indexOf(uuid) === -1) continue;

                  this._removeArmature(armatureKey);
                }
              };

              _proto2.getArmatureCache = function getArmatureCache(armatureName, armatureKey, atlasUUID) {
                var armatureInfo = this._armatureCache[armatureKey];
                var armature;

                if (!armatureInfo) {
                  var factory = CCFactory.getInstance();
                  var 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: armature,
                    animationsCache: {},
                    curAnimationCache: null
                  };
                } else {
                  armature = armatureInfo.armature;
                }

                return armature;
              };

              _proto2.getAnimationCache = function getAnimationCache(armatureKey, animationName) {
                var armatureInfo = this._armatureCache[armatureKey];
                if (!armatureInfo) return null;
                var animationsCache = armatureInfo.animationsCache;
                return animationsCache[animationName];
              };

              _proto2.initAnimationCache = function initAnimationCache(armatureKey, animationName) {
                if (!animationName) return null;
                var armatureInfo = this._armatureCache[armatureKey];
                var armature = armatureInfo && armatureInfo.armature;
                if (!armature) return null;
                var animation = armature.animation;
                var hasAni = animation.hasAnimation(animationName);
                if (!hasAni) return null;
                var animationsCache = armatureInfo.animationsCache;
                var animationCache = animationsCache[animationName];

                if (!animationCache) {
                  var 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;
              };

              _proto2.invalidAnimationCache = function invalidAnimationCache(armatureKey) {
                var armatureInfo = this._armatureCache[armatureKey];
                var armature = armatureInfo && armatureInfo.armature;
                if (!armature) return;
                var animationsCache = armatureInfo.animationsCache;

                for (var aniKey in animationsCache) {
                  var animationCache = animationsCache[aniKey];
                  animationCache.invalidAllFrame();
                }
              };

              _proto2.updateAnimationCache = function updateAnimationCache(armatureKey, animationName) {
                if (animationName) {
                  var animationCache = this.initAnimationCache(armatureKey, animationName);
                  if (!animationCache) return;
                  animationCache.updateAllFrame();
                } else {
                  var armatureInfo = this._armatureCache[armatureKey];
                  var armature = armatureInfo && armatureInfo.armature;
                  if (!armature) return;
                  var animationsCache = armatureInfo.animationsCache;

                  for (var aniKey in animationsCache) {
                    var _animationCache = animationsCache[aniKey];

                    _animationCache.updateAllFrame();
                  }
                }
              };

              ArmatureCache.canCache = function canCache(armature) {
                var slots = armature._slots;

                for (var i = 0, l = slots.length; i < l; i++) {
                  var slot = slots[i];

                  if (slot.childArmature) {
                    return false;
                  }
                }

                return true;
              };

              return ArmatureCache;
            }();
            ArmatureCache.FrameTime = FrameTime$1;
            ArmatureCache.sharedCache = new ArmatureCache();

            var _dec$1Y, _class$1$, _class2$1I, _descriptor$1v, _temp$1S;
            var DragonBonesAsset = (_dec$1Y = ccclass('dragonBones.DragonBonesAsset'), _dec$1Y(_class$1$ = (_class2$1I = (_temp$1S = function (_Asset) {
              _inheritsLoose(DragonBonesAsset, _Asset);

              function DragonBonesAsset() {
                var _this;

                for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                  args[_key] = arguments[_key];
                }

                _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;

                _initializerDefineProperty(_this, "_dragonBonesJson", _descriptor$1v, _assertThisInitialized(_this));

                _this._factory = null;
                _this._dragonBonesJsonData = void 0;
                _this._armaturesEnum = null;
                return _this;
              }

              var _proto = DragonBonesAsset.prototype;

              _proto.constructctor = function constructctor() {
                this.reset();
              };

              _proto.createNode = function createNode(callback) {
                var node = new Node$1(this.name);
                var armatureDisplay = node.addComponent('dragonBones.ArmatureDisplay');
                armatureDisplay.dragonAsset = this;
                return callback(null, node);
              };

              _proto.reset = function reset() {
                this._clear();
              };

              _proto.init = function init(factory, atlasUUID) {
                {
                  this._factory = factory;
                }

                if (!this._dragonBonesJsonData && this.dragonBonesJson) {
                  this._dragonBonesJsonData = JSON.parse(this.dragonBonesJson);
                }

                var rawData = null;

                if (this._dragonBonesJsonData) {
                  rawData = this._dragonBonesJsonData;
                } else {
                  rawData = this._nativeAsset;
                }

                if (!this._uuid) {
                  var dbData = this._factory.getDragonBonesDataByRawData(rawData);

                  if (dbData) {
                    this._uuid = dbData.name;
                  } else {
                    console.warn('dragonbones name is empty');
                  }
                }

                var armatureKey = this._uuid + "#" + atlasUUID;

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

              _proto.getArmatureEnum = function getArmatureEnum() {
                if (this._armaturesEnum) {
                  return this._armaturesEnum;
                }

                this.init();

                var dragonBonesData = this._factory.getDragonBonesDataByUUID(this._uuid);

                if (dragonBonesData) {
                  var armatureNames = dragonBonesData.armatureNames;
                  var enumDef = {};

                  for (var i = 0; i < armatureNames.length; i++) {
                    var name = armatureNames[i];
                    enumDef[name] = i;
                  }

                  return this._armaturesEnum = Enum(enumDef);
                }

                return null;
              };

              _proto.getAnimsEnum = function getAnimsEnum(armatureName) {
                this.init();

                var dragonBonesData = this._factory.getDragonBonesDataByUUID(this._uuid);

                if (dragonBonesData) {
                  var armature = dragonBonesData.getArmature(armatureName);

                  if (!armature) {
                    return null;
                  }

                  var enumDef = {
                    '<None>': 0
                  };
                  var anims = armature.animations;
                  var i = 0;

                  for (var animName in anims) {
                    if (anims.hasOwnProperty(animName)) {
                      enumDef[animName] = i + 1;
                      i++;
                    }
                  }

                  return Enum(enumDef);
                }

                return null;
              };

              _proto.destroy = function destroy() {
                this._clear();

                return _Asset.prototype.destroy.call(this);
              };

              _proto._clear = function _clear() {
                if (this._factory) {
                  ArmatureCache.sharedCache.resetArmature(this._uuid);

                  this._factory.removeDragonBonesDataByUUID(this._uuid, true);
                }
              };

              _createClass(DragonBonesAsset, [{
                key: "dragonBonesJson",
                get: function get() {
                  return this._dragonBonesJson;
                },
                set: function set(value) {
                  this._dragonBonesJson = value;
                  this._dragonBonesJsonData = JSON.parse(value);
                  this.reset();
                }
              }]);

              return DragonBonesAsset;
            }(Asset), _temp$1S), (_descriptor$1v = _applyDecoratedDescriptor(_class2$1I.prototype, "_dragonBonesJson", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return '';
              }
            })), _class2$1I)) || _class$1$);
            legacyCC.internal.DragonBonesAsset = DragonBonesAsset;

            var _dec$1Z, _dec2$1p, _class$20, _class2$1J, _descriptor$1w, _descriptor2$1b, _descriptor3$U, _descriptor4$M, _temp$1T;
            var DragonBonesAtlasAsset = (_dec$1Z = ccclass('dragonBones.DragonBonesAtlasAsset'), _dec2$1p = type(Texture2D), _dec$1Z(_class$20 = (_class2$1J = (_temp$1T = function (_Asset) {
              _inheritsLoose(DragonBonesAtlasAsset, _Asset);

              function DragonBonesAtlasAsset() {
                var _this;

                _this = _Asset.call(this) || this;

                _initializerDefineProperty(_this, "_atlasJson", _descriptor$1w, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_texture", _descriptor2$1b, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_atlasJsonData", _descriptor3$U, _assertThisInitialized(_this));

                _this._factory = null;

                _initializerDefineProperty(_this, "_textureAtlasData", _descriptor4$M, _assertThisInitialized(_this));

                _this._clear();

                return _this;
              }

              var _proto = DragonBonesAtlasAsset.prototype;

              _proto.createNode = function createNode(callback) {
                var node = new Node$1(this.name);
                var armatureDisplay = node.addComponent('dragonBones.ArmatureDisplay');
                armatureDisplay.dragonAtlasAsset = this;
                return callback(null, node);
              };

              _proto.init = function init(factory) {
                this._factory = factory;

                if (!this._atlasJsonData) {
                  this._atlasJsonData = JSON.parse(this.atlasJson);
                }

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

              _proto.destroy = function destroy() {
                this._clear();

                return _Asset.prototype.destroy.call(this);
              };

              _proto._clear = function _clear() {

                if (this._factory) {
                  ArmatureCache.sharedCache.resetArmature(this._uuid);

                  this._factory.removeTextureAtlasData(this._uuid, true);

                  this._factory.removeDragonBonesDataByUUID(this._uuid, true);
                }

                this._textureAtlasData = null;
              };

              _createClass(DragonBonesAtlasAsset, [{
                key: "atlasJson",
                get: function get() {
                  return this._atlasJson;
                },
                set: function set(value) {
                  this._atlasJson = value;
                  this._atlasJsonData = JSON.parse(this.atlasJson);

                  this._clear();
                }
              }, {
                key: "texture",
                get: function get() {
                  return this._texture;
                },
                set: function set(value) {
                  this._texture = value;

                  this._clear();
                }
              }]);

              return DragonBonesAtlasAsset;
            }(Asset), _temp$1T), (_descriptor$1w = _applyDecoratedDescriptor(_class2$1J.prototype, "_atlasJson", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return '';
              }
            }), _descriptor2$1b = _applyDecoratedDescriptor(_class2$1J.prototype, "_texture", [serializable, _dec2$1p], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor3$U = _applyDecoratedDescriptor(_class2$1J.prototype, "_atlasJsonData", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return {};
              }
            }), _descriptor4$M = _applyDecoratedDescriptor(_class2$1J.prototype, "_textureAtlasData", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            })), _class2$1J)) || _class$20);
            legacyCC.internal.DragonBonesAtlasAsset = DragonBonesAtlasAsset;

            var _dec$1_, _class$21, _temp$1U;

            var _tempMat4 = new Mat4();

            var AttachUtil$1 = (_dec$1_ = ccclass('dragonBones.AttachUtil'), _dec$1_(_class$21 = (_temp$1U = function () {
              function AttachUtil() {
                this._inited = false;
                this._armature = null;
                this._armatureNode = null;
                this._armatureDisplay = null;
              }

              var _proto = AttachUtil.prototype;

              _proto.init = function init(armatureDisplay) {
                this._inited = true;
                this._armature = armatureDisplay._armature;
                this._armatureNode = armatureDisplay.node;
                this._armatureDisplay = armatureDisplay;
              };

              _proto.reset = function reset() {
                this._inited = false;
                this._armature = null;
                this._armatureNode = null;
                this._armatureDisplay = null;
              };

              _proto._syncAttachedNode = function _syncAttachedNode() {
                var _this = this;

                if (!this._inited) return;
                var rootMatrix = this._armatureNode.worldMatrix;
                var boneInfos = null;

                var isCached = this._armatureDisplay.isAnimationCached();

                if (isCached && this._armatureDisplay) {
                  boneInfos = this._armatureDisplay._curFrame && this._armatureDisplay._curFrame.boneInfos;
                  if (!boneInfos) return;
                }

                var sockets = this._armatureDisplay.sockets;
                var socketNodes = this._armatureDisplay.socketNodes;
                var scale = new Vec3();

                var matrixHandle = function matrixHandle(node, boneMat) {
                  var 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;

                  if (!node._oldScale) {
                    node._oldScale = node.scale.clone();
                  }

                  scale.set(node._oldScale);
                  node.matrix = _tempMat4;
                  node.scale = scale.multiply(_this._armatureNode.scale);
                };

                var bones = this._armature.getBones();

                for (var l = sockets.length - 1; l >= 0; l--) {
                  var sock = sockets[l];
                  var boneNode = sock.target;
                  if (!boneNode) continue;

                  if (!boneNode.isValid) {
                    socketNodes["delete"](sock.path);
                    sockets.splice(l, 1);
                    continue;
                  }

                  var bone = isCached ? boneInfos[sock.boneIndex] : bones[sock.boneIndex];
                  if (!bone) continue;
                  matrixHandle(boneNode, bone.globalTransformMatrix);
                }
              };

              return AttachUtil;
            }(), _temp$1U)) || _class$21);

            var _dec$1$, _dec2$1q, _class$22, _class2$1K, _descriptor$1x, _descriptor2$1c, _temp$1V, _dec3$12, _dec4$W, _dec5$L, _dec6$E, _dec7$B, _dec8$y, _dec9$t, _dec10$r, _dec11$p, _dec12$o, _dec13$l, _dec14$i, _dec15$i, _dec16$h, _dec17$g, _dec18$g, _dec19$g, _dec20$f, _dec21$f, _dec22$f, _dec23$f, _dec24$d, _dec25$d, _class4$9, _class5$7, _descriptor3$V, _descriptor4$N, _descriptor5$D, _descriptor6$t, _descriptor7$n, _descriptor8$n, _descriptor9$j, _descriptor10$j, _descriptor11$i, _descriptor12$f, _descriptor13$b, _descriptor14$a, _descriptor15$9, _descriptor16$9, _class6$2, _temp2$9;
            var DefaultArmaturesEnum;

            (function (DefaultArmaturesEnum) {
              DefaultArmaturesEnum[DefaultArmaturesEnum["default"] = -1] = "default";
            })(DefaultArmaturesEnum || (DefaultArmaturesEnum = {}));

            ccenum(DefaultArmaturesEnum);
            var DefaultAnimsEnum$1;

            (function (DefaultAnimsEnum) {
              DefaultAnimsEnum[DefaultAnimsEnum["<None>"] = 0] = "<None>";
            })(DefaultAnimsEnum$1 || (DefaultAnimsEnum$1 = {}));

            ccenum(DefaultAnimsEnum$1);
            var DefaultCacheMode;

            (function (DefaultCacheMode) {
              DefaultCacheMode[DefaultCacheMode["REALTIME"] = 0] = "REALTIME";
            })(DefaultCacheMode || (DefaultCacheMode = {}));

            ccenum(DefaultAnimsEnum$1);
            var timeScale$1 = 1;
            var AnimationCacheMode$1;

            (function (AnimationCacheMode) {
              AnimationCacheMode[AnimationCacheMode["REALTIME"] = 0] = "REALTIME";
              AnimationCacheMode[AnimationCacheMode["SHARED_CACHE"] = 1] = "SHARED_CACHE";
              AnimationCacheMode[AnimationCacheMode["PRIVATE_CACHE"] = 2] = "PRIVATE_CACHE";
            })(AnimationCacheMode$1 || (AnimationCacheMode$1 = {}));

            ccenum(AnimationCacheMode$1);

            function setEnumAttr$1(obj, propName, enumDef) {
              CCClass.Attr.setClassAttr(obj, propName, 'type', 'Enum');
              CCClass.Attr.setClassAttr(obj, propName, 'enumList', Enum.getList(enumDef));
            }

            var DragonBoneSocket = (_dec$1$ = ccclass('dragonBones.ArmatureDisplay.DragonBoneSocket'), _dec2$1q = type(Node$1), _dec$1$(_class$22 = (_class2$1K = (_temp$1V = function DragonBoneSocket(path, target) {
              if (path === void 0) {
                path = '';
              }

              if (target === void 0) {
                target = null;
              }

              _initializerDefineProperty(this, "path", _descriptor$1x, this);

              _initializerDefineProperty(this, "target", _descriptor2$1c, this);

              this.boneIndex = null;
              this.path = path;
              this.target = target;
            }, _temp$1V), (_descriptor$1x = _applyDecoratedDescriptor(_class2$1K.prototype, "path", [serializable, editable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return '';
              }
            }), _descriptor2$1c = _applyDecoratedDescriptor(_class2$1K.prototype, "target", [_dec2$1q, editable, serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            })), _class2$1K)) || _class$22);
            setClassAlias(DragonBoneSocket, 'dragonBones.ArmatureDisplay.DragonBoneSocket');
            var ArmatureDisplay = (_dec3$12 = ccclass('dragonBones.ArmatureDisplay'), _dec4$W = help(), _dec5$L = menu(), _dec6$E = type(DragonBonesAsset), _dec7$B = tooltip(), _dec8$y = type(DragonBonesAtlasAsset), _dec9$t = tooltip(), _dec10$r = visible(), _dec11$p = visible(), _dec12$o = displayName(), _dec13$l = type(DefaultArmaturesEnum), _dec14$i = tooltip(), _dec15$i = type(DefaultAnimsEnum$1), _dec16$h = displayName(), _dec17$g = tooltip(), _dec18$g = displayName(), _dec19$g = tooltip(), _dec20$f = tooltip(), _dec21$f = tooltip(), _dec22$f = tooltip(), _dec23$f = tooltip(), _dec24$d = type([DragonBoneSocket]), _dec25$d = tooltip(), _dec3$12(_class4$9 = _dec4$W(_class4$9 = _dec5$L(_class4$9 = executeInEditMode(_class4$9 = (_class5$7 = (_temp2$9 = _class6$2 = function (_Renderable2D) {
              _inheritsLoose(ArmatureDisplay, _Renderable2D);

              function ArmatureDisplay() {
                var _this;

                _this = _Renderable2D.call(this) || this;

                _initializerDefineProperty(_this, "playTimes", _descriptor3$V, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "premultipliedAlpha", _descriptor4$N, _assertThisInitialized(_this));

                _this._armature = null;
                _this.attachUtil = void 0;

                _initializerDefineProperty(_this, "_defaultArmatureIndexValue", _descriptor5$D, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_dragonAsset", _descriptor6$t, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_dragonAtlasAsset", _descriptor7$n, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_armatureName", _descriptor8$n, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_animationName", _descriptor9$j, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_animationIndexValue", _descriptor10$j, _assertThisInitialized(_this));

                _this._preCacheMode = -1;
                _this._cacheMode = AnimationCacheMode$1.REALTIME;

                _initializerDefineProperty(_this, "_defaultCacheModeValue", _descriptor11$i, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_timeScale", _descriptor12$f, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_playTimes", _descriptor13$b, _assertThisInitialized(_this));

                _initializerDefineProperty(_this, "_debugBones", _descriptor14$a, _assertThisInitialized(_this));

                _this._debugDraw = null;

                _initializerDefineProperty(_this, "_enableBatch", _descriptor15$9, _assertThisInitialized(_this));

                _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._meshRenderDataArray = [];
                _this._materialCache = {};
                _this._enumArmatures = Enum({});
                _this._enumAnimations = Enum({});
                _this._socketNodes = new Map();
                _this._cachedSockets = new Map();

                _initializerDefineProperty(_this, "_sockets", _descriptor16$9, _assertThisInitialized(_this));

                _this._inited = void 0;
                _this._meshRenderDataArrayIdx = 0;
                _this._cacheModeEnum = void 0;
                _this._eventTarget = new EventTarget();
                _this._inited = false;
                _this.attachUtil = new AttachUtil$1();

                _this.initFactory();

                setEnumAttr$1(_assertThisInitialized(_this), '_animationIndex', _this._enumAnimations);
                setEnumAttr$1(_assertThisInitialized(_this), '_defaultArmatureIndex', _this._enumArmatures);
                return _this;
              }

              var _proto = ArmatureDisplay.prototype;

              _proto.initFactory = function initFactory() {
                this._factory = CCFactory.getInstance();
              };

              _proto.onLoad = function onLoad() {
                var children = this.node.children;

                for (var i = 0, n = children.length; i < n; i++) {
                  var child = children[i];
                  var pos = child.name && child.name.search('CHILD_ARMATURE-');

                  if (pos === 0) {
                    child.destroy();
                  }
                }
              };

              _proto.requestMeshRenderData = function requestMeshRenderData() {
                var arr = this._meshRenderDataArray;

                if (arr.length > 0 && arr[arr.length - 1].renderData.vertexCount === 0) {
                  return arr[arr.length - 1];
                }

                var renderData = new MeshRenderData();
                var comb = {
                  renderData: renderData,
                  texture: null
                };
                arr.push(comb);
                return comb;
              };

              _proto.destroyRenderData = function destroyRenderData() {
                if (this._meshRenderDataArray) {
                  this._meshRenderDataArray.forEach(function (rd) {
                    rd.renderData.reset();
                  });

                  this._meshRenderDataArray.length = 0;
                }
              };

              _proto.resetRenderData = function resetRenderData() {
                if (this._meshRenderDataArray) {
                  this._meshRenderDataArray.forEach(function (rd) {
                    rd.renderData.reset();
                  });
                }
              };

              _proto.getMaterialForBlend = function getMaterialForBlend(src, dst) {
                var key = src + "/" + dst;
                var inst = this._materialCache[key];

                if (inst) {
                  return inst;
                }

                var material = this.getMaterial(0);
                var matInfo = {
                  parent: material,
                  subModelIdx: 0,
                  owner: this
                };
                inst = new MaterialInstance(matInfo);
                inst.recompileShaders({
                  USE_LOCAL: false
                }, 0);
                this._materialCache[key] = inst;
                inst.overridePipelineStates({
                  blendState: {
                    targets: [{
                      blendSrc: src,
                      blendDst: dst
                    }]
                  }
                });
                return inst;
              };

              _proto._render = function _render(ui) {
                if (this._meshRenderDataArray) {
                  for (var i = 0; i < this._meshRenderDataArray.length; i++) {
                    var mat = this.material;
                    this._meshRenderDataArrayIdx = i;
                    var m = this._meshRenderDataArray[i];
                    this.material = m.renderData.material;

                    if (m.texture) {
                      ui.commitComp(this, m.texture, this._assembler, null);
                    }

                    this.material = mat;
                  }
                }
              };

              _proto._updateBatch = function _updateBatch() {
                this._materialCache = {};
                this.destroyRenderData();
                this.markForUpdateRenderData();
              };

              _proto._updateMaterial = function _updateMaterial() {
                this.markForUpdateRenderData();
              };

              _proto.disableRender = function disableRender() {};

              _proto._validateRender = function _validateRender() {
                var texture = this.dragonAtlasAsset && this.dragonAtlasAsset.texture;

                if (!texture || !texture.loaded) {
                  this.disableRender();
                  return false;
                }

                return true;
              };

              _proto.__preload = function __preload() {
                _Renderable2D.prototype.__preload.call(this);

                this._init();
              };

              _proto._init = function _init() {

                this._cacheMode = this._defaultCacheMode;
                if (this._inited) return;
                this._inited = true;

                this._parseDragonAtlasAsset();

                this._refresh();

                var children = this.node.children;

                for (var i = 0, n = children.length; i < n; i++) {
                  var child = children[i];

                  if (child && child.name === 'DEBUG_DRAW_NODE') {
                    child.destroy();
                  }
                }

                this._updateDebugDraw();

                this._indexBoneSockets();

                this._updateSocketBindings();
              };

              _proto.getArmatureKey = function getArmatureKey() {
                return this._armatureKey;
              };

              _proto.setAnimationCacheMode = function 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();
                }
              };

              _proto.isAnimationCached = function isAnimationCached() {
                return this._cacheMode !== AnimationCacheMode$1.REALTIME;
              };

              _proto.onEnable = function onEnable() {
                _Renderable2D.prototype.onEnable.call(this);

                if (this._armature && !this.isAnimationCached()) {
                  this._factory._dragonBones.clock.add(this._armature);
                }

                this._flushAssembler();
              };

              _proto.onDisable = function onDisable() {
                _Renderable2D.prototype.onDisable.call(this);

                if (this._armature && !this.isAnimationCached()) {
                  this._factory._dragonBones.clock.remove(this._armature);
                }
              };

              _proto._emitCacheCompleteEvent = function _emitCacheCompleteEvent() {
                this._eventTarget.emit(EventObject.LOOP_COMPLETE);

                this._eventTarget.emit(EventObject.COMPLETE);
              };

              _proto.update = function update(dt) {
                if (!this.isAnimationCached()) return;
                if (!this._frameCache) return;
                this.markForUpdateRenderData();
                var frameCache = this._frameCache;

                if (!frameCache.isInited()) {
                  return;
                }

                var frames = frameCache.frames;

                if (!this._playing) {
                  if (frameCache.isInvalid()) {
                    frameCache.updateToFrame();
                    this._curFrame = frames[frames.length - 1];
                  }

                  return;
                }

                var frameTime = ArmatureCache.FrameTime;

                if (this._accTime === 0 && this._playCount === 0) {
                  this._eventTarget.emit(EventObject.START);
                }

                var globalTimeScale = timeScale$1;
                this._accTime += dt * this.timeScale * globalTimeScale;
                var frameIdx = Math.floor(this._accTime / frameTime);

                if (!frameCache.isCompleted) {
                  frameCache.updateToFrame(frameIdx);
                }

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

              _proto.onDestroy = function onDestroy() {
                this._materialInstances = this._materialInstances.filter(function (instance) {
                  return !!instance;
                });

                _Renderable2D.prototype.onDestroy.call(this);

                this._inited = false;

                {
                  if (this._cacheMode === AnimationCacheMode$1.PRIVATE_CACHE) {
                    this._armatureCache.dispose();

                    this._armatureCache = null;
                    this._armature = null;
                  } else if (this._cacheMode === AnimationCacheMode$1.SHARED_CACHE) {
                    this._armatureCache = null;
                    this._armature = null;
                  } else if (this._armature) {
                    this._armature.dispose();

                    this._armature = null;
                  }
                }

                this.destroyRenderData();
              };

              _proto._updateDebugDraw = function _updateDebugDraw() {
                if (this.debugBones) {
                  if (!this._debugDraw) {
                    var debugDrawNode = new Node$1('DEBUG_DRAW_NODE');
                    debugDrawNode.hideFlags |= CCObject.Flags.DontSave | CCObject.Flags.HideInHierarchy;
                    var debugDraw = debugDrawNode.addComponent(Graphics);
                    debugDraw.lineWidth = 1;
                    debugDraw.strokeColor = new Color(255, 0, 0, 255);
                    this._debugDraw = debugDraw;
                  }

                  this._debugDraw.node.parent = this.node;
                } else if (this._debugDraw) {
                  this._debugDraw.node.parent = null;
                }

                this.destroyRenderData();
                this.markForUpdateRenderData();
              };

              _proto._buildArmature = function _buildArmature() {
                if (!this.dragonAsset || !this.dragonAtlasAsset || !this.armatureName) return;

                if (this._armature) {
                  {
                    if (this._preCacheMode === AnimationCacheMode$1.PRIVATE_CACHE) {
                      this._armatureCache.dispose();
                    } else if (this._preCacheMode === AnimationCacheMode$1.REALTIME) {
                      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 === AnimationCacheMode$1.SHARED_CACHE) {
                    this._armatureCache = ArmatureCache.sharedCache;
                  } else if (this._cacheMode === AnimationCacheMode$1.PRIVATE_CACHE) {
                    this._armatureCache = new ArmatureCache();

                    this._armatureCache.enablePrivateMode();
                  }
                }

                var 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 = AnimationCacheMode$1.REALTIME;
                  }
                }

                this._preCacheMode = this._cacheMode;

                if ( this._cacheMode === AnimationCacheMode$1.REALTIME) {
                  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 !== AnimationCacheMode$1.REALTIME && this.debugBones) {
                  console.warn('Debug bones is invalid in cached mode');
                }

                if (this._armature) {
                  var armatureData = this._armature.armatureData;
                  var aabb = armatureData.aabb;

                  this.node._uiProps.uiTransformComp.setContentSize(aabb.width, aabb.height);
                }

                this._updateBatch();

                this.attachUtil.init(this);

                if (this.animationName) {
                  this.playAnimation(this.animationName, this.playTimes);
                }

                this.destroyRenderData();
                this.markForUpdateRenderData();
              };

              _proto.querySockets = function querySockets() {
                if (!this._armature) {
                  return [];
                }

                if (this._cachedSockets.size === 0) {
                  this._indexBoneSockets();
                }

                return Array.from(this._cachedSockets.keys()).sort();
              };

              _proto.setBlendHash = function setBlendHash() {
                if (this._blendHash !== -1) this._blendHash = -1;
              };

              _proto.querySocketPathByName = function querySocketPathByName(name) {
                var ret = [];

                for (var _iterator = _createForOfIteratorHelperLoose(this._cachedSockets.keys()), _step; !(_step = _iterator()).done;) {
                  var _key = _step.value;

                  if (_key.endsWith(name)) {
                    ret.push(_key);
                  }
                }

                return ret;
              };

              _proto._parseDragonAtlasAsset = function _parseDragonAtlasAsset() {
                if (this.dragonAtlasAsset) {
                  this.dragonAtlasAsset.init(this._factory);
                }
              };

              _proto._refresh = function _refresh() {
                this._buildArmature();

                this.markForUpdateRenderData();
              };

              _proto._updateCacheModeEnum = function _updateCacheModeEnum() {
                this._cacheModeEnum = Enum({});

                if (this._armature) {
                  Object.assign(this._cacheModeEnum, AnimationCacheMode$1);
                } else {
                  Object.assign(this._cacheModeEnum, DefaultCacheMode);
                }

                setEnumAttr$1(this, '_defaultCacheMode', this._cacheModeEnum);
              };

              _proto._updateAnimEnum = function _updateAnimEnum() {
                var 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);
                setEnumAttr$1(this, '_animationIndex', this._enumAnimations);
              };

              _proto._updateArmatureEnum = function _updateArmatureEnum() {
                var armatureEnum;

                if (this.dragonAsset) {
                  armatureEnum = this.dragonAsset.getArmatureEnum();
                } else {
                  armatureEnum = DefaultArmaturesEnum;
                }

                this._enumArmatures = Enum({});
                Object.assign(this._enumArmatures, armatureEnum || DefaultArmaturesEnum);
                Enum.update(this._enumArmatures);
                setEnumAttr$1(this, '_defaultArmatureIndex', this._enumArmatures);
              };

              _proto._indexBoneSockets = function _indexBoneSockets() {
                if (!this._armature) {
                  return;
                }

                this._cachedSockets.clear();

                var nameToBone = this._cachedSockets;

                var cacheBoneName = function cacheBoneName(bi, bones, cache) {
                  if (cache.has(bi)) {
                    return cache.get(bi);
                  }

                  var bone = bones[bi];

                  if (!bone.parent) {
                    cache.set(bi, bone.name);
                    bone.path = bone.name;
                    return bone.name;
                  }

                  var name = cacheBoneName(bone.parent._boneIndex, bones, cache) + "/" + bone.name;
                  cache.set(bi, name);
                  bone.path = name;
                  return name;
                };

                var walkArmature = function walkArmature(prefix, armature) {
                  var bones = armature.getBones();
                  var boneToName = new Map();

                  for (var i = 0; i < bones.length; i++) {
                    bones[i]._boneIndex = i;
                  }

                  for (var _i = 0; _i < bones.length; _i++) {
                    cacheBoneName(_i, bones, boneToName);
                  }

                  for (var _iterator2 = _createForOfIteratorHelperLoose(boneToName.keys()), _step2; !(_step2 = _iterator2()).done;) {
                    var bone = _step2.value;
                    nameToBone.set("" + prefix + boneToName.get(bone), bone);
                  }

                  var slots = armature.getSlots();

                  for (var _i2 = 0; _i2 < slots.length; _i2++) {
                    if (slots[_i2].childArmature) {
                      walkArmature(slots[_i2].name, slots[_i2].childArmature);
                    }
                  }
                };

                walkArmature('', this._armature);
              };

              _proto.playAnimation = function playAnimation(animName, playTimes) {
                this.playTimes = playTimes === undefined ? -1 : playTimes;
                this.animationName = animName;

                if (this.isAnimationCached()) {
                  var 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;
              };

              _proto.updateAnimationCache = function updateAnimationCache(animName) {
                if (!this.isAnimationCached()) return;

                this._armatureCache.updateAnimationCache(this._armatureKey, animName);
              };

              _proto.invalidAnimationCache = function invalidAnimationCache() {
                if (!this.isAnimationCached()) return;

                this._armatureCache.invalidAnimationCache(this._armatureKey);
              };

              _proto.getArmatureNames = function getArmatureNames() {
                var dragonBonesData = this._factory.getDragonBonesData(this._armatureKey);

                return dragonBonesData && dragonBonesData.armatureNames || [];
              };

              _proto.getAnimationNames = function getAnimationNames(armatureName) {
                var ret = [];

                var dragonBonesData = this._factory.getDragonBonesData(this._armatureKey);

                if (dragonBonesData) {
                  var armatureData = dragonBonesData.getArmature(armatureName);

                  if (armatureData) {
                    for (var animName in armatureData.animations) {
                      if (armatureData.animations.hasOwnProperty(animName)) {
                        ret.push(animName);
                      }
                    }
                  }
                }

                return ret;
              };

              _proto.on = function on(eventType, listener, target) {
                this.addEventListener(eventType, listener, target);
              };

              _proto.off = function off(eventType, listener, target) {
                this.removeEventListener(eventType, listener, target);
              };

              _proto.once = function once(eventType, listener, target) {
                this._eventTarget.once(eventType, listener, target);
              };

              _proto.addEventListener = function addEventListener(eventType, listener, target) {
                this._eventTarget.on(eventType, listener, target);
              };

              _proto.removeEventListener = function removeEventListener(eventType, listener, target) {
                this._eventTarget.off(eventType, listener, target);
              };

              _proto.buildArmature = function buildArmature(armatureName, node) {
                return this._factory.createArmatureNode(this, armatureName, node);
              };

              _proto.armature = function armature() {
                return this._armature;
              };

              _proto._flushAssembler = function _flushAssembler() {
                var assembler = ArmatureDisplay.Assembler.getAssembler(this);

                if (this._assembler !== assembler) {
                  this._assembler = assembler;
                }

                if (this._meshRenderDataArray.length === 0) {
                  if (this._assembler && this._assembler.createData) {
                    this._assembler.createData(this);

                    this.markForUpdateRenderData();
                    this._colorDirty = true;

                    this._updateColor();
                  }
                }
              };

              _proto._updateSocketBindings = function _updateSocketBindings() {
                if (!this._armature) return;

                this._socketNodes.clear();

                for (var i = 0, l = this._sockets.length; i < l; i++) {
                  var socket = this._sockets[i];

                  if (socket.path && socket.target) {
                    var 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);
                  }
                }
              };

              _proto._verifySockets = function _verifySockets(sockets) {
                for (var i = 0, l = sockets.length; i < l; i++) {
                  var 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;
                    }
                  }
                }
              };

              _createClass(ArmatureDisplay, [{
                key: "dragonAsset",
                get: function get() {
                  return this._dragonAsset;
                },
                set: function set(value) {
                  this._dragonAsset = value;

                  this._refresh();
                }
              }, {
                key: "dragonAtlasAsset",
                get: function get() {
                  return this._dragonAtlasAsset;
                },
                set: function set(value) {
                  this._dragonAtlasAsset = value;

                  this._parseDragonAtlasAsset();

                  this._refresh();
                }
              }, {
                key: "armatureName",
                get: function get() {
                  return this._armatureName;
                },
                set: function set(name) {
                  this._armatureName = name;
                  var 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);
                  }
                }
              }, {
                key: "animationName",
                get: function get() {
                  return this._animationName;
                },
                set: function set(value) {
                  this._animationName = value;
                }
              }, {
                key: "_defaultArmatureIndex",
                get: function get() {
                  return this._defaultArmatureIndexValue;
                },
                set: function set(value) {
                  this._defaultArmatureIndexValue = value;
                  var armatureName = '';

                  if (this.dragonAsset) {
                    var 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.resetRenderData();
                  this.markForUpdateRenderData();
                }
              }, {
                key: "_animationIndex",
                get: function get() {
                  return this._animationIndexValue;
                },
                set: function set(value) {
                  this._animationIndexValue = value;

                  if (this._animationIndex === 0) {
                    this.animationName = '';
                    return;
                  }

                  var animsEnum;

                  if (this.dragonAsset) {
                    animsEnum = this.dragonAsset.getAnimsEnum(this.armatureName);
                  }

                  if (!animsEnum) {
                    return;
                  }

                  var animName = animsEnum[this._animationIndex];

                  if (animName !== undefined) {
                    this.playAnimation(animName, this.playTimes);
                  } else {
                    errorID(7402, this.name);
                  }
                }
              }, {
                key: "_defaultCacheMode",
                get: function get() {
                  return this._defaultCacheModeValue;
                },
                set: function set(value) {
                  this._defaultCacheModeValue = value;

                  if (this._defaultCacheMode !== AnimationCacheMode$1.REALTIME) {
                    if (this._armature && !ArmatureCache.canCache(this._armature)) {
                      this._defaultCacheMode = AnimationCacheMode$1.REALTIME;
                      console.warn('Animation cache mode doesn\'t support skeletal nesting');
                      return;
                    }
                  }

                  this.setAnimationCacheMode(this._defaultCacheMode);
                }
              }, {
                key: "timeScale",
                get: function get() {
                  return this._timeScale;
                },
                set: function set(value) {
                  this._timeScale = value;

                  if (this._armature && !this.isAnimationCached()) {
                    this._armature.animation.timeScale = this.timeScale;
                  }
                }
              }, {
                key: "debugBones",
                get: function get() {
                  return this._debugBones;
                },
                set: function set(value) {
                  this._debugBones = value;

                  this._updateDebugDraw();
                }
              }, {
                key: "sockets",
                get: function get() {
                  return this._sockets;
                },
                set: function set(val) {
                  this._verifySockets(val);

                  this._sockets = val;

                  this._updateSocketBindings();

                  if (val.length > 0 && this._frameCache) {
                    this._frameCache.enableCacheAttachedInfo();
                  }
                }
              }, {
                key: "socketNodes",
                get: function get() {
                  return this._socketNodes;
                }
              }, {
                key: "meshRenderDataArray",
                get: function get() {
                  return this._meshRenderDataArray;
                }
              }]);

              return ArmatureDisplay;
            }(Renderable2D), _class6$2.AnimationCacheMode = AnimationCacheMode$1, _temp2$9), (_applyDecoratedDescriptor(_class5$7.prototype, "dragonAsset", [editable, _dec6$E, _dec7$B], Object.getOwnPropertyDescriptor(_class5$7.prototype, "dragonAsset"), _class5$7.prototype), _applyDecoratedDescriptor(_class5$7.prototype, "dragonAtlasAsset", [editable, _dec8$y, _dec9$t], Object.getOwnPropertyDescriptor(_class5$7.prototype, "dragonAtlasAsset"), _class5$7.prototype), _applyDecoratedDescriptor(_class5$7.prototype, "armatureName", [_dec10$r], Object.getOwnPropertyDescriptor(_class5$7.prototype, "armatureName"), _class5$7.prototype), _applyDecoratedDescriptor(_class5$7.prototype, "animationName", [_dec11$p], Object.getOwnPropertyDescriptor(_class5$7.prototype, "animationName"), _class5$7.prototype), _applyDecoratedDescriptor(_class5$7.prototype, "_defaultArmatureIndex", [_dec12$o, editable, _dec13$l, _dec14$i], Object.getOwnPropertyDescriptor(_class5$7.prototype, "_defaultArmatureIndex"), _class5$7.prototype), _applyDecoratedDescriptor(_class5$7.prototype, "_animationIndex", [editable, _dec15$i, _dec16$h, _dec17$g], Object.getOwnPropertyDescriptor(_class5$7.prototype, "_animationIndex"), _class5$7.prototype), _applyDecoratedDescriptor(_class5$7.prototype, "_defaultCacheMode", [editable, _dec18$g, _dec19$g], Object.getOwnPropertyDescriptor(_class5$7.prototype, "_defaultCacheMode"), _class5$7.prototype), _applyDecoratedDescriptor(_class5$7.prototype, "timeScale", [editable, _dec20$f, serializable], Object.getOwnPropertyDescriptor(_class5$7.prototype, "timeScale"), _class5$7.prototype), _descriptor3$V = _applyDecoratedDescriptor(_class5$7.prototype, "playTimes", [_dec21$f, editable, serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return -1;
              }
            }), _descriptor4$N = _applyDecoratedDescriptor(_class5$7.prototype, "premultipliedAlpha", [serializable, editable, _dec22$f], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _applyDecoratedDescriptor(_class5$7.prototype, "debugBones", [_dec23$f, editable], Object.getOwnPropertyDescriptor(_class5$7.prototype, "debugBones"), _class5$7.prototype), _applyDecoratedDescriptor(_class5$7.prototype, "sockets", [_dec24$d, _dec25$d], Object.getOwnPropertyDescriptor(_class5$7.prototype, "sockets"), _class5$7.prototype), _descriptor5$D = _applyDecoratedDescriptor(_class5$7.prototype, "_defaultArmatureIndexValue", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return DefaultArmaturesEnum["default"];
              }
            }), _descriptor6$t = _applyDecoratedDescriptor(_class5$7.prototype, "_dragonAsset", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor7$n = _applyDecoratedDescriptor(_class5$7.prototype, "_dragonAtlasAsset", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return null;
              }
            }), _descriptor8$n = _applyDecoratedDescriptor(_class5$7.prototype, "_armatureName", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return '';
              }
            }), _descriptor9$j = _applyDecoratedDescriptor(_class5$7.prototype, "_animationName", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return '';
              }
            }), _descriptor10$j = _applyDecoratedDescriptor(_class5$7.prototype, "_animationIndexValue", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 0;
              }
            }), _descriptor11$i = _applyDecoratedDescriptor(_class5$7.prototype, "_defaultCacheModeValue", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return AnimationCacheMode$1.REALTIME;
              }
            }), _descriptor12$f = _applyDecoratedDescriptor(_class5$7.prototype, "_timeScale", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return 1;
              }
            }), _descriptor13$b = _applyDecoratedDescriptor(_class5$7.prototype, "_playTimes", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return -1;
              }
            }), _descriptor14$a = _applyDecoratedDescriptor(_class5$7.prototype, "_debugBones", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor15$9 = _applyDecoratedDescriptor(_class5$7.prototype, "_enableBatch", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return false;
              }
            }), _descriptor16$9 = _applyDecoratedDescriptor(_class5$7.prototype, "_sockets", [serializable], {
              configurable: true,
              enumerable: true,
              writable: true,
              initializer: function initializer() {
                return [];
              }
            })), _class5$7)) || _class4$9) || _class4$9) || _class4$9) || _class4$9);
            legacyCC.internal.ArmatureDisplay = ArmatureDisplay;

            var NEED_COLOR = 0x01;
            var NEED_BATCH = 0x10;
            var STRIDE_FLOAT = 9;

            var _boneColor$1 = new Color(255, 0, 0, 255);

            var _slotColor$1 = new Color(0, 0, 255, 255);

            var _originColor$1 = new Color(0, 255, 0, 255);

            var _nodeR$1;

            var _nodeG$1;

            var _nodeB$1;

            var _nodeA$1;

            var _premultipliedAlpha$1;

            var _mustFlush$1;

            var _buffer$1;

            var _node$1;

            var _comp$2;

            var _vfOffset$4;

            var _indexOffset$3;

            var _vertexOffset$1;

            var _vertexCount$1;

            var _indexCount$2;

            var _x$2;

            var _y$2;

            var _c = new Float32Array(4);

            var _handleVal$1;

            var _m00$1;

            var _m04$1;

            var _m12$1;

            var _m01$1;

            var _m05$1;

            var _m13$1;

            var _vec3u_temp$2 = new Vec3();

            function _getSlotMaterial$1(tex, blendMode) {
              if (!tex) return null;
              var src;
              var dst;

              switch (blendMode) {
                case 1:
                  src = _premultipliedAlpha$1 ? BlendFactor.ONE : BlendFactor.SRC_ALPHA;
                  dst = BlendFactor.ONE;
                  break;

                case 10:
                  src = BlendFactor.DST_COLOR;
                  dst = BlendFactor.ONE_MINUS_SRC_ALPHA;
                  break;

                case 12:
                  src = BlendFactor.ONE;
                  dst = BlendFactor.ONE_MINUS_SRC_COLOR;
                  break;

                case 0:
                default:
                  src = _premultipliedAlpha$1 ? BlendFactor.ONE : BlendFactor.SRC_ALPHA;
                  dst = BlendFactor.ONE_MINUS_SRC_ALPHA;
                  break;
              }

              _comp$2.setBlendHash();

              return _comp$2.getMaterialForBlend(src, dst);
            }

            function _handleColor$1(color, parentOpacity) {
              var _a = color.a * parentOpacity * _nodeA$1;

              var _multiply = _premultipliedAlpha$1 ? _a / 255.0 : 1.0;

              var _r = color.r * _nodeR$1 * _multiply / 255.0;

              var _g = color.g * _nodeG$1 * _multiply / 255.0;

              var _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;
            }

            function _intToColor(v) {
              _c[0] = (0xFF & v >>> 24) / 255.0;
              _c[1] = (0xFF & v >>> 16) / 255.0;
              _c[2] = (0xFF & v >>> 8) / 255.0;
              _c[3] = (0xFF & v >>> 0) / 255.0;
            }

            var simple$3 = {
              createData: function createData() {},
              updateRenderData: function updateRenderData(comp, ui) {
                _comp$2 = comp;
                updateComponentRenderData$1(comp);
              },
              updateColor: function updateColor(comp) {
                if (!comp) return;
                _comp$2 = comp;

                _comp$2.markForUpdateRenderData();
              },
              fillBuffers: function fillBuffers(comp, renderer) {
                if (!comp || comp.meshRenderDataArray.length === 0) return;
                var dataArray = comp.meshRenderDataArray;
                var node = comp.node;
                var buffer = renderer.acquireBufferBatch();
                var floatOffset = buffer.byteOffset >> 2;
                var indicesOffset = buffer.indicesOffset;
                var vertexOffset = buffer.vertexOffset;
                var data = dataArray[comp._meshRenderDataArrayIdx];
                var renderData = data.renderData;
                var isRecreate = buffer.request(renderData.vertexCount, renderData.indicesCount);

                if (!isRecreate) {
                  buffer = renderer.currBufferBatch;
                  floatOffset = 0;
                  indicesOffset = 0;
                  vertexOffset = 0;
                }

                var vBuf = buffer.vData;
                var iBuf = buffer.iData;
                var matrix = node.worldMatrix;
                var srcVBuf = renderData.vData;
                var srcVIdx = renderData.vertexStart;
                var srcIBuf = renderData.iData;
                vBuf.set(srcVBuf.slice(srcVIdx, srcVIdx + renderData.vertexCount * STRIDE_FLOAT), floatOffset);

                if (!comp._enableBatch) {
                  for (var i = 0; i < renderData.vertexCount; i++) {
                    var pOffset = floatOffset + i * STRIDE_FLOAT;

                    _vec3u_temp$2.set(vBuf[pOffset], vBuf[pOffset + 1], vBuf[pOffset + 2]);

                    _vec3u_temp$2.transformMat4(matrix);

                    vBuf[pOffset] = _vec3u_temp$2.x;
                    vBuf[pOffset + 1] = _vec3u_temp$2.y;
                    vBuf[pOffset + 2] = _vec3u_temp$2.z;
                  }
                }

                var srcIOffset = renderData.indicesStart;

                for (var _i = 0; _i < renderData.indicesCount; _i += 1) {
                  iBuf[_i + indicesOffset] = srcIBuf[_i + srcIOffset] + vertexOffset;
                }
              }
            };

            function realTimeTraverse$1(armature, parentMat, parentOpacity) {
              var slots = armature._slots;
              var vbuf;
              var ibuf;
              var material;
              var vertices;
              var indices;
              var slotColor;
              var slot;
              var slotMat = new Mat4();

              for (var i = 0, l = slots.length; i < l; i++) {
                slot = slots[i];
                slotColor = slot._color;
                if (!slot._visible || !slot._displayData) continue;

                if (parentMat) {
                  slot._mulMat(slot._worldMatrix, parentMat, slot._matrix);
                } else {
                  Mat4.copy(slot._worldMatrix, slot._matrix);
                }

                if (slot.childArmature) {
                  realTimeTraverse$1(slot.childArmature, slot._worldMatrix, parentOpacity * slotColor.a / 255);
                  continue;
                }

                material = _getSlotMaterial$1(slot.getTexture(), slot._blendMode);

                if (!material) {
                  continue;
                }

                if (!_buffer$1.renderData.material) {
                  _buffer$1.renderData.material = material;
                }

                if (!_buffer$1.texture) {
                  _buffer$1.texture = slot.getTexture();
                }

                if (_mustFlush$1 || material !== _buffer$1.renderData.material || _buffer$1.texture !== slot.getTexture()) {
                  _mustFlush$1 = false;
                  _buffer$1 = _comp$2.requestMeshRenderData();
                  _buffer$1.renderData.material = material;
                  _buffer$1.texture = slot.getTexture();
                }

                _handleColor$1(slotColor, parentOpacity);

                slotMat.set(slot._worldMatrix);
                vertices = slot._localVertices;
                _vertexCount$1 = vertices.length >> 2;
                indices = slot._indices;
                _indexCount$2 = indices.length;
                var rd = _buffer$1.renderData;
                rd.reserve(_vertexCount$1, _indexCount$2);
                _indexOffset$3 = rd.indicesCount;
                _vfOffset$4 = rd.vDataOffset;
                _vertexOffset$1 = rd.vertexCount;
                vbuf = _buffer$1.renderData.vData;
                ibuf = _buffer$1.renderData.iData;
                _m00$1 = slotMat.m00;
                _m04$1 = slotMat.m04;
                _m12$1 = slotMat.m12;
                _m01$1 = slotMat.m01;
                _m05$1 = slotMat.m05;
                _m13$1 = slotMat.m13;

                for (var vi = 0, vl = vertices.length; vi < vl;) {
                  _x$2 = vertices[vi++];
                  _y$2 = vertices[vi++];
                  vbuf[_vfOffset$4] = _x$2 * _m00$1 + _y$2 * _m04$1 + _m12$1;
                  vbuf[_vfOffset$4 + 1] = _x$2 * _m01$1 + _y$2 * _m05$1 + _m13$1;
                  vbuf[_vfOffset$4 + 3] = vertices[vi++];
                  vbuf[_vfOffset$4 + 4] = vertices[vi++];
                  vbuf.set(_c, _vfOffset$4 + 5);
                  _vfOffset$4 += STRIDE_FLOAT;
                }

                for (var ii = 0, il = indices.length; ii < il; ii++) {
                  ibuf[_indexOffset$3++] = _vertexOffset$1 + indices[ii];
                }

                _buffer$1.renderData.advance(_vertexCount$1, _indexCount$2);
              }
            }

            function cacheTraverse$1(frame, parentMat) {
              if (!frame) return;
              var segments = frame.segments;
              if (segments.length === 0) return;
              var vbuf;
              var ibuf;
              var material;
              var vertices = frame.vertices;
              var colorArray = new Uint32Array(vertices.buffer);
              var indices = frame.indices;
              var frameVFOffset = 0;
              var frameIndexOffset = 0;
              var segVFCount = 0;

              if (parentMat) {
                _m00$1 = parentMat.m00;
                _m01$1 = parentMat.m01;
                _m04$1 = parentMat.m04;
                _m05$1 = parentMat.m05;
                _m12$1 = parentMat.m12;
                _m13$1 = parentMat.m13;
              }

              var justTranslate = _m00$1 === 1 && _m01$1 === 0 && _m04$1 === 0 && _m05$1 === 1;
              var needBatch = _handleVal$1 & NEED_BATCH;
              var calcTranslate = needBatch && justTranslate;
              var colorOffset = 0;
              var colors = frame.colors;
              var nowColor = colors[colorOffset++];
              var maxVFOffset = nowColor.vfOffset;

              _handleColor$1(nowColor, 1.0);

              for (var i = 0, n = segments.length; i < n; i++) {
                var segInfo = segments[i];
                material = _getSlotMaterial$1(segInfo.tex, segInfo.blendMode);

                if (!_buffer$1.renderData.material) {
                  _buffer$1.renderData.material = material;
                }

                if (!_buffer$1.texture) {
                  _buffer$1.texture = segInfo.tex;
                }

                if (_mustFlush$1 || _buffer$1.renderData.material !== material || _buffer$1.texture !== segInfo.tex) {
                  _mustFlush$1 = false;
                  _buffer$1 = _comp$2.requestMeshRenderData();
                  _buffer$1.renderData.material = material;
                  _buffer$1.texture = segInfo.tex;
                }

                _vertexCount$1 = segInfo.vertexCount;
                _indexCount$2 = segInfo.indexCount;
                var rd = _buffer$1.renderData;
                rd.reserve(_vertexCount$1, _indexCount$2);
                _indexOffset$3 = rd.indicesCount;
                _vfOffset$4 = rd.vDataOffset;
                _vertexOffset$1 = rd.vertexCount;
                vbuf = _buffer$1.renderData.vData;
                ibuf = _buffer$1.renderData.iData;

                for (var ii = _indexOffset$3, il = _indexOffset$3 + _indexCount$2; ii < il; ii++) {
                  ibuf[ii] = _vertexOffset$1 + indices[frameIndexOffset++];
                }

                segVFCount = segInfo.vfCount;

                for (var _ii = frameVFOffset, jj = _vfOffset$4; _ii < frameVFOffset + segVFCount;) {
                  vbuf[jj] = vertices[_ii++];
                  vbuf[jj + 1] = vertices[_ii++];
                  vbuf[jj + 3] = vertices[_ii++];
                  vbuf[jj + 4] = vertices[_ii++];

                  _intToColor(colorArray[_ii++]);

                  vbuf.set(_c, jj + 5);
                  jj += STRIDE_FLOAT;
                }

                frameVFOffset += segVFCount;

                if (calcTranslate) {
                  for (var _ii2 = _vfOffset$4, _il = _vfOffset$4 + segVFCount; _ii2 < _il; _ii2 += STRIDE_FLOAT) {
                    vbuf[_ii2] += _m12$1;
                    vbuf[_ii2 + 1] += _m13$1;
                  }
                } else if (needBatch) {
                  for (var _ii3 = _vfOffset$4, _il2 = _vfOffset$4 + segVFCount; _ii3 < _il2; _ii3 += STRIDE_FLOAT) {
                    _x$2 = vbuf[_ii3];
                    _y$2 = vbuf[_ii3 + 1];
                    vbuf[_ii3] = _x$2 * _m00$1 + _y$2 * _m04$1 + _m12$1;
                    vbuf[_ii3 + 1] = _x$2 * _m01$1 + _y$2 * _m05$1 + _m13$1;
                  }
                }

                _buffer$1.renderData.advance(_vertexCount$1, _indexCount$2);

                if (!(_handleVal$1 & NEED_COLOR)) continue;
                var frameColorOffset = frameVFOffset - segVFCount;

                for (var _ii4 = _vfOffset$4 + 5, _il3 = _vfOffset$4 + 4 + segVFCount; _ii4 < _il3; _ii4 += STRIDE_FLOAT, frameColorOffset += STRIDE_FLOAT) {
                  if (frameColorOffset >= maxVFOffset) {
                    nowColor = colors[colorOffset++];

                    _handleColor$1(nowColor, 1.0);

                    maxVFOffset = nowColor.vfOffset;
                  }

                  vbuf.set(_c, _ii4);
                }
              }
            }

            function updateComponentRenderData$1(comp, batcher) {
              var armature = comp._armature;
              if (!armature) return;
              comp.markForUpdateRenderData();
              comp.destroyRenderData();
              _mustFlush$1 = true;
              _premultipliedAlpha$1 = comp.premultipliedAlpha;
              _node$1 = comp.node;
              _buffer$1 = comp.requestMeshRenderData();
              _comp$2 = comp;
              _handleVal$1 = 0;
              var nodeColor = comp.color;
              _nodeR$1 = nodeColor.r / 255;
              _nodeG$1 = nodeColor.g / 255;
              _nodeB$1 = nodeColor.b / 255;
              _nodeA$1 = nodeColor.a / 255;

              if (nodeColor._val !== 0xffffffff) {
                _handleVal$1 |= NEED_COLOR;
              }

              var worldMat;

              if (_comp$2._enableBatch) {
                worldMat = _node$1.worldMatrix;
                _mustFlush$1 = false;
                _handleVal$1 |= NEED_BATCH;
              }

              if (comp.isAnimationCached()) {
                cacheTraverse$1(comp._curFrame, worldMat);
              } else {
                realTimeTraverse$1(armature, worldMat, 1.0);
                var graphics = comp._debugDraw;

                if (comp.debugBones && graphics) {
                  graphics.clear();
                  graphics.lineWidth = 5;
                  graphics.strokeColor = _boneColor$1;
                  graphics.fillColor = _slotColor$1;
                  var bones = armature.getBones();

                  for (var i = 0, l = bones.length; i < l; i++) {
                    var bone = bones[i];
                    var boneLength = Math.max(bone.boneData.length, 5);
                    var startX = bone.globalTransformMatrix.tx;
                    var startY = bone.globalTransformMatrix.ty;
                    var endX = startX + bone.globalTransformMatrix.a * boneLength;
                    var 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;
                    }
                  }
                }
              }

              comp.attachUtil._syncAttachedNode();

              _node$1 = undefined;
              _buffer$1 = undefined;
              _comp$2 = undefined;
            }

            legacyCC.internal.DragonBonesAssembler = simple$3;

            var simpleDragonBoneAssembler = {
              getAssembler: function getAssembler() {
                return simple$3;
              }
            };
            ArmatureDisplay.Assembler = simpleDragonBoneAssembler;

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

            var EventType$9;

            (function (EventType) {
              EventType[EventType["Frame"] = 0] = "Frame";
              EventType[EventType["Sound"] = 1] = "Sound";
            })(EventType$9 || (EventType$9 = {}));

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

            var index$4 = /*#__PURE__*/Object.freeze({
                __proto__: null,
                get ExtensionType () { return ExtensionType; },
                get EventType () { return EventType$9; },
                get AnimationFadeOutMode () { return AnimationFadeOutMode; },
                CCFactory: CCFactory,
                CCSlot: CCSlot,
                CCTextureAtlasData: CCTextureAtlasData,
                CCTextureData: CCTextureData,
                CCArmatureDisplay: CCArmatureDisplay,
                AnimationCache: AnimationCache$1,
                ArmatureCache: ArmatureCache,
                DragonBonesAsset: DragonBonesAsset,
                DragonBonesAtlasAsset: DragonBonesAtlasAsset,
                timeScale: timeScale$1,
                get AnimationCacheMode () { return AnimationCacheMode$1; },
                DragonBoneSocket: DragonBoneSocket,
                ArmatureDisplay: ArmatureDisplay,
                AttachUtil: AttachUtil$1,
                simpleDragonBoneAssembler: simpleDragonBoneAssembler,
                DragonBones: DragonBones,
                BaseObject: BaseObject,
                Matrix: Matrix,
                Transform: Transform,
                ColorTransform: ColorTransform,
                Point: Point$2,
                Rectangle: Rectangle,
                UserData: UserData,
                ActionData: ActionData,
                DragonBonesData: DragonBonesData,
                ArmatureData: ArmatureData,
                BoneData: BoneData,
                SurfaceData: SurfaceData,
                SlotData: SlotData,
                ConstraintData: ConstraintData,
                IKConstraintData: IKConstraintData,
                PathConstraintData: PathConstraintData,
                CanvasData: CanvasData,
                SkinData: SkinData,
                VerticesData: VerticesData,
                DisplayData: DisplayData,
                ImageDisplayData: ImageDisplayData,
                ArmatureDisplayData: ArmatureDisplayData,
                MeshDisplayData: MeshDisplayData,
                BoundingBoxDisplayData: BoundingBoxDisplayData,
                PathDisplayData: PathDisplayData,
                WeightData: WeightData,
                BoundingBoxData: BoundingBoxData,
                RectangleBoundingBoxData: RectangleBoundingBoxData,
                EllipseBoundingBoxData: EllipseBoundingBoxData,
                PolygonBoundingBoxData: PolygonBoundingBoxData,
                AnimationData: AnimationData,
                TimelineData: TimelineData,
                AnimationConfig: AnimationConfig,
                TextureAtlasData: TextureAtlasData,
                TextureData: TextureData,
                DeformVertices: DeformVertices,
                Armature: Armature,
                TransformObject: TransformObject,
                Bone: Bone,
                Surface: Surface,
                Slot: Slot,
                Constraint: Constraint$1,
                IKConstraint: IKConstraint,
                PathConstraint: PathConstraint,
                WorldClock: WorldClock,
                Animation: Animation$1,
                AnimationState: AnimationState$1,
                BonePose: BonePose,
                BlendState: BlendState$1,
                TimelineState: TimelineState,
                TweenTimelineState: TweenTimelineState,
                BoneTimelineState: BoneTimelineState,
                SlotTimelineState: SlotTimelineState,
                ConstraintTimelineState: ConstraintTimelineState,
                ActionTimelineState: ActionTimelineState,
                ZOrderTimelineState: ZOrderTimelineState,
                BoneAllTimelineState: BoneAllTimelineState,
                BoneTranslateTimelineState: BoneTranslateTimelineState,
                BoneRotateTimelineState: BoneRotateTimelineState,
                BoneScaleTimelineState: BoneScaleTimelineState,
                SurfaceTimelineState: SurfaceTimelineState,
                SlotDislayTimelineState: SlotDislayTimelineState,
                SlotColorTimelineState: SlotColorTimelineState,
                DeformTimelineState: DeformTimelineState,
                IKConstraintTimelineState: IKConstraintTimelineState,
                AnimationTimelineState: AnimationTimelineState,
                EventObject: EventObject,
                DataParser: DataParser,
                ObjectDataParser: ObjectDataParser,
                ActionFrame: ActionFrame,
                BinaryDataParser: BinaryDataParser,
                BaseFactory: BaseFactory,
                BuildArmaturePackage: BuildArmaturePackage,
                BinaryOffset: BinaryOffset,
                ArmatureType: ArmatureType,
                BoneType: BoneType,
                DisplayType: DisplayType,
                BoundingBoxType: BoundingBoxType,
                ActionType: ActionType,
                BlendMode: BlendMode,
                TweenType: TweenType,
                TimelineType: TimelineType
            });
            exports('dragonBones', index$4);

        }
    };
});
